问:
Material Design Lite blocks my tooltip from showing
the mdl class mdl-layout__content is blocking my tooltip from showing in my graph. I made a codepen that shows the problem.  Are there style settings I can make to still use this class for my nav, but show my tooltip.

Link to CodePen that shows the issue

here's my HTML code

```<code>    <html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="A front-end template that helps you build fast, modern mobile web apps.">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">

    <title>New UI 07052017</title>
    <link href="css/layout.css" rel="stylesheet" type="text/css">

    <!-- Material Design Lite
    <link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.orange-indigo.min.css"> -->
    <link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.orange-indigo.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <!-- <link rel="stylesheet" href="https://storage.googleapis.com/code.getmdl.io/1.0.6/material.indigo-pink.min.css"> -->
    <link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    <!-- Bootstrap -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/angular-toggle-switch-bootstrap-3.css" type="text/css" media="screen">
    <link href="css/bootstrap-material-design.css" rel="stylesheet">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/flot/0.8.3/jquery.flot.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/flot/0.8.3/jquery.flot.time.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.4/raphael-min.js"></script>

    <script language="javascript" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/flot/0.8.3/jquery.flot.resize.js"></script>

    <!--<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script> **** updated to 1.6.1 on 6/29/17-->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>

    <!-- <script src="https://www.gstatic.com/firebasejs/3.2.0/firebase.js"></script> -->
    <script src="https://www.gstatic.com/firebasejs/3.6.6/firebase.js"></script>

    <!-- <script src="https://cdn.firebase.com/libs/angularfire/2.0.1/angularfire.min.js"></script> -->
    <script src="https://cdn.firebase.com/libs/angularfire/2.3.0/angularfire.min.js"></script>

    <script src="js/angular-toggle-switch.min.js"></script>
    <script src="js/angularScripts.js"></script>

    <!-- JustGage tools for the dashboard -->
    <script src="js/justgage.js"></script>

    <script src="https://storage.googleapis.com/code.getmdl.io/1.0.6/material.min.js"></script>
    <script defer src="https://code.getmdl.io/1.1.3/material.min.js"></script>

    <!-- Add to homescreen for Chrome on Android -->
    <meta name="mobile-web-app-capable" content="yes">
    <link rel="icon" sizes="192x192" href="images/android-icon-192x192.png">

    <!-- Add to homescreen for Safari on iOS -->
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-title" content="Pellet Pirate">
    <link rel="apple-touch-icon-precomposed" href="images/apple-icon-114x114.png">

    <!-- Tile icon for Win8 (144x144 + tile color) -->
    <meta name="msapplication-TileImage" content="images/apple-icon-144x144.png">
    <meta name="msapplication-TileColor" content="#3372DF">

    <link rel="shortcut icon" href="images/pelletpirate-icon-32x32.png">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="https://code.getmdl.io/1.2.0/material.cyan-light_blue.min.css">
    <link rel="stylesheet" href="css/styles.css">

    <!-- Import and configure the Firebase SDK -->
    <!-- These scripts are made available when the app is served or deployed on Firebase Hosting -->
    <!-- If you do not serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup -->
    <script src="/__/firebase/4.0.0/firebase-app.js"></script>
    <script src="/__/firebase/4.0.0/firebase-auth.js"></script>
    <script src="/__/firebase/init.js"></script>

    <style>
        #view-source {
        position: fixed;
        display: block;
        right: 0;
        bottom: 0;
        margin-right: 40px;
        margin-bottom: 40px;
        z-index: 900;
        }
    </style>

</head>

<body ng-app="PelletPirate">
        <div class="demo-layout mdl-layout mdl-js-layout mdl-layout--fixed-drawer mdl-layout--fixed-header">
        <header class="demo-header mdl-layout__header mdl-color--grey-100 mdl-color-text--grey-600">
            <div class="mdl-layout__header-row">
                <span class="mdl-layout-title">smoker</span>
                <div class="mdl-layout-spacer"></div>
                <div class="mdl-textfield mdl-js-textfield mdl-textfield--expandable">
                        <label class="mdl-button mdl-js-button mdl-button--icon" for="search">
                        <i class="material-icons">search</i>
                        </label>
                        <div class="mdl-textfield__expandable-holder">
                        <input class="mdl-textfield__input" type="text" id="search">
                        <label class="mdl-textfield__label" for="search">Enter your query...</label>
                        </div>
                </div>
                <button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon" id="hdrbtn">
                        <i class="material-icons">more_vert</i>
                </button>
            </div>
        </header>

        <div class="demo-drawer mdl-layout__drawer mdl-color--blue-grey-900 mdl-color-text--blue-grey-50">
                <header class="demo-drawer-header">

                </header>
                <nav class="demo-navigation mdl-navigation mdl-color--blue-grey-800">
                    <a class="mdl-navigation__link" href=""><i class="mdl-color-text--blue-grey-400 material-icons" role="presentation">whatshot</i>Manage a Cook</a>
                    <a class="mdl-navigation__link" href=""><i class="mdl-color-text--blue-grey-400 material-icons" role="presentation">inbox</i>Inbox</a>
                    <a class="mdl-navigation__link" href=""><i class="mdl-color-text--blue-grey-400 material-icons" role="presentation">delete</i>Trash</a>
                    <div class="mdl-layout-spacer"></div>
                    <a class="mdl-navigation__link" href=""><i class="mdl-color-text--blue-grey-400 material-icons" role="presentation">help_outline</i>
                    <span class="visuallyhidden">Help</span></a>
                </nav>
        </div>

<!-- *********************************************************************************************************************-->

<!-- need help here. I'm not sure what settings to make in CSS to enable the tooltip popup to show. If I comment out the  -->
<!-- the mdl-layout__content class then the tooltips show but my graph now drifts left behind my left nav -->

<!-- *********************************************************************************************************************-->

        <main class="mdl-layout__content mdl-color--grey-100">
        <!-- <main class="mdl-color--grey-100"> -->

            <div class="mdl-grid demo-content">

                <div class="demo-graphs mdl-shadow--2dp mdl-color--white mdl-cell mdl-cell--8-col">

                    <div class="plot-container">
                        <div id="temp-placeholder" class="plot-placeholder"></div>
                    </div>

                </div>

                <div class="row" id="ControlsRow">
                    <div class="mdl-cell mdl-cell--12-col">
                        <div class="plot-container">
                            <div id="controls-placeholder" class="plot-placeholder"></div>
                        </div>
                    </div>
                </div>

            </div>

            <footer class="mdl-mini-footer">
                <div class="mdl-mini-footer--middle-section">
                    <div class="mdl-logo">"It's a Pirate's life for me."</div>
                    <ul class="mdl-mini-footer--link-list">
                        <li><a href="#">Help</a></li>
                        <li><a href="#">Privacy & Terms</a></li>
                    </ul>
                </div>
            </footer>
        </main>
    </div>
</body>

<script src="https://www.gstatic.com/firebasejs/4.1.2/firebase.js"></script>
<script>
  // Initialize Firebase
  var config = {
    apiKey: "AIzaSyD3_xJ0aYVK3VwjuuliOdb6t5wbbi87RB8",
    authDomain: "pelletpirate.firebaseapp.com",
    databaseURL: "https://pelletpirate.firebaseio.com",
    projectId: "pelletpirate",
    storageBucket: "pelletpirate.appspot.com",
    messagingSenderId: "731610976061"
  };
  firebase.initializeApp(config);
  var Ref = firebase.database().ref()
</script>

<script src="js/scripts.js"></script>
<script src="js/Cscripts.js"></script>

</html>
</code>```

答:
I figured it out:  z-index to bring the tooltip to the forefront. In CSS:</p>

```<code>#tooltip {
  z-index: 1;
}
</code>```

Body:
the mdl class mdl-layout__content is blocking my tooltip from showing in my graph. I made a codepen that shows the problem.  Are there style settings I can make to still use this class for my nav, but show my tooltip.

Link to CodePen that shows the issue

here's my HTML code

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="A front-end template that helps you build fast, modern mobile web apps.">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">

    <title>New UI 07052017</title>
    <link href="css/layout.css" rel="stylesheet" type="text/css">

    <link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.orange-indigo.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

    <link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/angular-toggle-switch-bootstrap-3.css" type="text/css" media="screen">
    <link href="css/bootstrap-material-design.css" rel="stylesheet">

    <meta name="mobile-web-app-capable" content="yes">
    <link rel="icon" sizes="192x192" href="images/android-icon-192x192.png">

    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-title" content="Pellet Pirate">
    <link rel="apple-touch-icon-precomposed" href="images/apple-icon-114x114.png">

    <meta name="msapplication-TileImage" content="images/apple-icon-144x144.png">
    <meta name="msapplication-TileColor" content="#3372DF">

    <link rel="shortcut icon" href="images/pelletpirate-icon-32x32.png">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="https://code.getmdl.io/1.2.0/material.cyan-light_blue.min.css">
    <link rel="stylesheet" href="css/styles.css">

                smoker

                        search

                        <input class="mdl-textfield__input" type="text" id="search">
                        Enter your query...

                <button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon" id="hdrbtn">
                        more_vert
                </button>

                    whatshotManage a Cook
                    inboxInbox
                    deleteTrash

                    help_outline
                    Help

"It's a Pirate's life for me."

Help

Privacy & Terms

Body:
I figured it out:  z-index to bring the tooltip to the forefront. In CSS:

#tooltip {
  z-index: 1;
}


来源: stackexchange

问:
Docker container cannot resolve hostnames
i am creating a docker-compose.yaml file that has to create a pypi local repository and a container with a dev application i am writing. The problem is that, inspite of the fact that i have created custom network and specified hostnames, containers cannot see each other.

More specifically, pypi has to be up and running; during my tests, i ran it manually, and msalembic should use the local pypi repository to load eggs. But i can't see the pypi host.

```<code>version: '3'
services:
  # Alembic MS
  msalembic:
    build:
      context: .
      dockerfile: AlembicMSDockerfile
    ports:
      - "5432:5432"
    hostname: alembicms
    volumes:
      - "${PWD}/msalembic/postgres/psql_data:/var/lib/postgresql/data"
    environment:
      POSTGRES_USER: ${PGUSER}
      POSTGRES_PASSWORD: ${PGPASSWORD}
      POSTGRES_DB: goodboy
      ENVIRONMENT: ${ENVIRONMENT}
    networks:
      - custom_network
    depends_on:
        - pypi
  # Private internal Pypi repository
  pypi:
    build:
        context: pypi
        dockerfile: Dockerfile
        args:
          HTACCESS: ${HTACCESS}
    hostname: pypi
    volumes:
      - "${PWD}/pypi/:/srv/pypi:rw"
    ports:
      - "9090:80"
    container_name: pypi
    networks:
      - custom_network
networks:
  custom_network:
</code>```

Contents of the AlembicMSDockerfile:

```<code>FROM python:3.6
MAINTAINER Bruno Ripa <XXX>
#RUN pip install -f http://pypi:9090 --trusted-host pypi alembicms
RUN ping pypi
ENTRYPOINT ["alembicms"]
</code>```

Of course i can browse and publish packages in the local pypi repository.

Thanks.

答:
The port mapping you specified is only relevant when the ports of a container are exposed to the host network (e.g. if you want to access them from your host via http://localhost:9090).

When linking containers inside a docker network, the services are exposed on the ports defined in the Dockerfile. So, according to your port mapping, the pypi container exposes port 80, which you should also use when you want to access it from another container in the same docker network.

So, when you run the built image of AlembicMSDockerfile, you can access your pypi container on port 80 via the docker network. In your special case, you want to access the pypi container already during build time of the alembic ms image. This is currently not supported within docker-compose as you can read from the issues here.

As long as this is not released, you could probably run the pypi container on its own and use the docker build --net=host --add-host=pypi_on_host:<yourhostip> --file=AlembicMSDockerfile and then modify the RUN command to use http://pypi_on_host:9090 (where you need the mapped port, as you no longer access it using a docker internal network). Not really elegant, but at least there is no direct reference to your host IP in the Dockerfile then...

ContentLicense: CC BY-SA 3.0

Body:
i am creating a docker-compose.yaml file that has to create a pypi local repository and a container with a dev application i am writing. The problem is that, inspite of the fact that i have created custom network and specified hostnames, containers cannot see each other.

More specifically, pypi has to be up and running; during my tests, i ran it manually, and msalembic should use the local pypi repository to load eggs. But i can't see the pypi host.

version: '3'
services:
  # Alembic MS
  msalembic:
    build:
      context: .
      dockerfile: AlembicMSDockerfile
    ports:
      - "5432:5432"
    hostname: alembicms
    volumes:
      - "${PWD}/msalembic/postgres/psql_data:/var/lib/postgresql/data"
    environment:
      POSTGRES_USER: ${PGUSER}
      POSTGRES_PASSWORD: ${PGPASSWORD}
      POSTGRES_DB: goodboy
      ENVIRONMENT: ${ENVIRONMENT}
    networks:
      - custom_network
    depends_on:
        - pypi
  # Private internal Pypi repository
  pypi:
    build:
        context: pypi
        dockerfile: Dockerfile
        args:
          HTACCESS: ${HTACCESS}
    hostname: pypi
    volumes:
      - "${PWD}/pypi/:/srv/pypi:rw"
    ports:
      - "9090:80"
    container_name: pypi
    networks:
      - custom_network
networks:
  custom_network:

Contents of the AlembicMSDockerfile:

FROM python:3.6
MAINTAINER Bruno Ripa <XXX>
#RUN pip install -f http://pypi:9090 --trusted-host pypi alembicms
RUN ping pypi
ENTRYPOINT ["alembicms"]

Of course i can browse and publish packages in the local pypi repository.

Thanks.


问:
Getting unintended movement in CSS animation
I have created some animations and applied them to divs using javascript. Basically, what I'm doing is making cards rotate and translateX on hover and get back. When I'm trying to get back, 2 of the divs first unintentionally moves up before animating.

Yes, I know my code can be compressed, but I was just creating a draft animation at that moment.

HTML

```<code><head>
  <link rel="stylesheet" type="text/css" href="index.css">
  <script src="index.js"></script>
</head>

<body>
  <div class="container" style="position:absolute; left:40%; top:20%;">
    <div class="card" id="c1"><p>Anti-Social</p>
      <h5 id="stud">STUDIOS</h5>
    </div>
    <div class="card" id="c2"></div>
    <div class="card" id="c3"></div>
  </div>
</body>
</code>```

CSS

```<code>*{
  margin: 0;
  padding: 0;
}
#stud{
  color: #3F3F3F;
  opacity:0;
}

@keyframes fadein {
    from { opacity: 0;}
    to   { opacity: 1;}
}

@keyframes fadeout {
    from { opacity: 1;}
    to   { opacity: 0;}
}

body{
  background-color: #1E2226;
}

.card{
  width: 250px;
  height: 300px;
  display:flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
  align-items: center;
  color: #0F0F0F;
  font-size: 200%;
}

#c1{
  background-color: rgba(242, 242, 242, 1);
  z-index: 3;
  position: absolute;
  top: 0;
  left: 0;
}

#c2{
  background-color: rgba(242,242,242, 0.6);
  z-index: 2;
  position: absolute;
  top: 0;
  left: 0;
}

#c3{
  background-color: rgba(242,242,242, 0.3);
  z-index: 1;
  position: absolute;
  top: 0;
  left: 0;
}

@keyframes inright {
  0%{transform: rotate(0deg) translateX(0%);}
  100%{transform: rotate(15deg) translateX(10%);}
}

@keyframes inleft {
  0%{transform: rotate(0deg) translateX(0%);}
  100%{transform: rotate(-15deg) translateX(-10%);}
}

@keyframes outright {
  0%{transform: translateX(10%) rotate(15deg);}
  100%{transform: translateX(0%) rotate(0deg);}
}

@keyframes outleft {
  0%{transform: translateX(-10%) rotate(-15deg);}
  100%{transform: translateX(0%) rotate(0deg);}
}
</code>```

See The Problem Here when You remove cursor from the card:
Codepen: https://codepen.io/iamshivam/pen/mwLZRq

答:
The order of the transforms in the keyframes actually matter, refer to CSS3 transform order matters: rightmost operation first

If you do this for all keyframes, changing

```<code>@keyframes outleft {
  0%{transform: translateX(-10%) rotate(-15deg);}
  100%{transform: translateX(0%) rotate(0deg);}
}
</code>```

to

```<code>@keyframes outleft {
  0%{transform: rotate(-15deg) translateX(-10%);}
  100%{transform: rotate(0deg) translateX(0%);}
}
</code>```

will work.

Body:
I have created some animations and applied them to divs using javascript. Basically, what I'm doing is making cards rotate and translateX on hover and get back. When I'm trying to get back, 2 of the divs first unintentionally moves up before animating.

Yes, I know my code can be compressed, but I was just creating a draft animation at that moment.

HTML

  <link rel="stylesheet" type="text/css" href="index.css">

Anti-Social

STUDIOS

CSS

*{
  margin: 0;
  padding: 0;
}
#stud{
  color: #3F3F3F;
  opacity:0;
}

@keyframes fadein {
    from { opacity: 0;}
    to   { opacity: 1;}
}

@keyframes fadeout {
    from { opacity: 1;}
    to   { opacity: 0;}
}

body{
  background-color: #1E2226;
}

.card{
  width: 250px;
  height: 300px;
  display:flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
  align-items: center;
  color: #0F0F0F;
  font-size: 200%;
}

#c1{
  background-color: rgba(242, 242, 242, 1);
  z-index: 3;
  position: absolute;
  top: 0;
  left: 0;
}

#c2{
  background-color: rgba(242,242,242, 0.6);
  z-index: 2;
  position: absolute;
  top: 0;
  left: 0;
}

#c3{
  background-color: rgba(242,242,242, 0.3);
  z-index: 1;
  position: absolute;
  top: 0;
  left: 0;
}

@keyframes inright {
  0%{transform: rotate(0deg) translateX(0%);}
  100%{transform: rotate(15deg) translateX(10%);}
}

@keyframes inleft {
  0%{transform: rotate(0deg) translateX(0%);}
  100%{transform: rotate(-15deg) translateX(-10%);}
}

@keyframes outright {
  0%{transform: translateX(10%) rotate(15deg);}
  100%{transform: translateX(0%) rotate(0deg);}
}

@keyframes outleft {
  0%{transform: translateX(-10%) rotate(-15deg);}
  100%{transform: translateX(0%) rotate(0deg);}
}

See The Problem Here when You remove cursor from the card:
Codepen: https://codepen.io/iamshivam/pen/mwLZRq

Body:
The order of the transforms in the keyframes actually matter, refer to CSS3 transform order matters: rightmost operation first

If you do this for all keyframes, changing

@keyframes outleft {
  0%{transform: translateX(-10%) rotate(-15deg);}
  100%{transform: translateX(0%) rotate(0deg);}
}

to

@keyframes outleft {
  0%{transform: rotate(-15deg) translateX(-10%);}
  100%{transform: rotate(0deg) translateX(0%);}
}

will work.


问:
A div is inheriting it's parent's width which is not what I want
Is there a way to make the div's width the same as the width of the image inside of it and ignore the width of the parent? My wrapper is 1200px, my image container's width is not set and the image inside the container is not hard coded so I can't hard code the width of the image container. I wanna make the image container wrap around the image and have the same width as it. Any way to do that?</p>

```<code>    <?php
        include 'header.php';
        include 'includes/comments.inc.php';
        include 'includes/images.inc.php';
    ?>
    <div class="wrapper">

    <?php

        $imagePath = $_SERVER['QUERY_STRING'];
        $realImagePath = substr($imagePath, 1);

        $sql = "SELECT * FROM image WHERE path='$realImagePath'";
        $result = mysqli_query($conn, $sql);
        $getResult = mysqli_fetch_assoc($result);

        echo "<div class='imageContainer'>"
                        ."<h1>".$getResult['name'].'</h1>'
                        .'<div class="relativeContainer"><img class="uploadedRealImg" src="uploads/'.$realImagePath .'" alt="Random image" /></div>'."<br><br>"
                        .$getResult['description']."<br><br>"
                        .$getResult['date']."<br><br>"
                        .$getResult['author']."<br><br></div>";

                            if (isset($_SESSION['id'])) {
                                $id = $_SESSION['id'];
                                $sql2 = "SELECT * FROM user WHERE id='$id'";
                                $result2 = mysqli_query($conn, $sql2);
                                $getResult2 = mysqli_fetch_assoc($result2);

                                    if ($getResult2['username'] == $getResult['author']) {
                                        echo "<form method='POST' action='".deleteImage($conn)."'>
                                                <input type='hidden' name='id' value='".$getResult['id']."'>
                                                <input type='hidden' name='path' value='".$getResult['path']."'>
                                                <input type='hidden' name='author' value='".$getResult['author']."'>
                                                <button id='delImage' type='submit' name='imageDelete'>Delete Image</button>
                                            </form>";
                                        }
                                }

        echo "<form method='POST' action='".setComments($conn)."'>
                <textarea class='commentSection' name='message'></textarea><br>
                <button type='submit' name='commentSubmit'>Comment</button>
            </form>";

    ?>

    <div id="comments">
        <?php
            getComments($conn);
        ?>
    </div>

    <?php
        echo "<button id='moreComments'>Show more comments</button>";
    ?>

</div>
<?php
    include 'footer.php';
?>

css

    .wrapper {
        width: 63.1%;
      margin: 0 auto;
      height: 100%;
    }
    .imageContainer {
      text-align: center;
      position: relative;
    }
    .uploadedImg {
      width: 500px;
      height: auto;
    }
    .uploadedRealImg {
      max-width: 1200px;
    }
    .commentSection {
      width: 100%;
      height: 150px;
    }
    #delImage {
      padding: 0;
      border: none;
      width: 100px;
      height: 100px;
      position: absolute;
      top: 0px;
      right: 0px;
    }
    .relativeContainer {
      position: relative;
    }
</code>```

答:
Yes it's possible. One of the ways is setting display: table to the image container, and make sure that the  element has display: block. I put together an example below. Notice the red border of the image container.

#wrapper{
  width: 1200px;
}
.image-container{
  display:table;
  border: 1px solid red;
}
.image-container img{
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <div class="image-container">
    <img src="https://lastfm-img2.akamaized.net/i/u/avatar300s/a96ecf5e524449ec866a6674709bb212.jpg">
  </div>
</div></code>```

Body:
Is there a way to make the div's width the same as the width of the image inside of it and ignore the width of the parent? My wrapper is 1200px, my image container's width is not set and the image inside the container is not hard coded so I can't hard code the width of the image container. I wanna make the image container wrap around the image and have the same width as it. Any way to do that?

    <?php
        include 'header.php';
        include 'includes/comments.inc.php';
        include 'includes/images.inc.php';
    ?>

    <?php

        $imagePath = $_SERVER['QUERY_STRING'];
        $realImagePath = substr($imagePath, 1);

        $sql = "SELECT * FROM image WHERE path='$realImagePath'";
        $result = mysqli_query($conn, $sql);
        $getResult = mysqli_fetch_assoc($result);

        echo "
"
                        ."
".$getResult['name'].'
'
                        .'

'."

"
                        .$getResult['description']."

"
                        .$getResult['date']."

"
                        .$getResult['author']."

";

                            if (isset($_SESSION['id'])) {
                                $id = $_SESSION['id'];
                                $sql2 = "SELECT * FROM user WHERE id='$id'";
                                $result2 = mysqli_query($conn, $sql2);
                                $getResult2 = mysqli_fetch_assoc($result2);

                                    if ($getResult2['username'] == $getResult['author']) {
                                        echo "<form method='POST' action='".deleteImage($conn)."'>
                                                <input type='hidden' name='id' value='".$getResult['id']."'>
                                                <input type='hidden' name='path' value='".$getResult['path']."'>
                                                <input type='hidden' name='author' value='".$getResult['author']."'>
                                                <button id='delImage' type='submit' name='imageDelete'>Delete Image</button>
                                            </form>";
                                        }
                                }

        echo "<form method='POST' action='".setComments($conn)."'>
                <textarea class='commentSection' name='message'></textarea>

                <button type='submit' name='commentSubmit'>Comment</button>
            </form>";

    ?>

        <?php
            getComments($conn);
        ?>

    <?php
        echo "<button id='moreComments'>Show more comments</button>";
    ?>

<?php
    include 'footer.php';
?>

css

    .wrapper {
        width: 63.1%;
      margin: 0 auto;
      height: 100%;
    }
    .imageContainer {
      text-align: center;
      position: relative;
    }
    .uploadedImg {
      width: 500px;
      height: auto;
    }
    .uploadedRealImg {
      max-width: 1200px;
    }
    .commentSection {
      width: 100%;
      height: 150px;
    }
    #delImage {
      padding: 0;
      border: none;
      width: 100px;
      height: 100px;
      position: absolute;
      top: 0px;
      right: 0px;
    }
    .relativeContainer {
      position: relative;
    }

Body:
Yes it's possible. One of the ways is setting display: table to the image container, and make sure that the <img> element has display: block. I put together an example below. Notice the red border of the image container.

#wrapper{
  width: 1200px;
}
.image-container{
  display:table;
  border: 1px solid red;
}
.image-container img{
  display: block;
}

<div id="wrapper">
  <div class="image-container">
    <img src="https://lastfm-img2.akamaized.net/i/u/avatar300s/a96ecf5e524449ec866a6674709bb212.jpg">
  </div>
</div>


问:
Compare String with Pattern
Want to using C# Regex to match string. but always return false. code below

```<code>bool isMatch(string preDZ, string matchStr)
{

    string pat = preDZ + "/d{8}";
    Regex reg = new Regex(pat);

    return reg.Match(matchStr).Success;
}
</code>```

Print(isMatch("AS", "AS00000001"));

but always return false. how to set the pattern to match the string "AS" + 8 length digits?

答:
Just try something looks like this:</p>

```<code>bool isMatch(string preDZ, string matchStr)
{
    string pat = preDZ + @"\d{8}";
    Regex reg = new Regex(pat);

    return reg.Match(matchStr).Success;
}
</code>```

Title: Compare String with Pattern

Body:
Want to using C# Regex to match string. but always return false. code below

bool isMatch(string preDZ, string matchStr)
{

    string pat = preDZ + "/d{8}";
    Regex reg = new Regex(pat);

    return reg.Match(matchStr).Success;
}

Print(isMatch("AS", "AS00000001"));

but always return false. how to set the pattern to match the string "AS" + 8 length digits?

Body:
Just try something looks like this:

bool isMatch(string preDZ, string matchStr)
{
    string pat = preDZ + @"\d{8}";
    Regex reg = new Regex(pat);

    return reg.Match(matchStr).Success;
}


问:
Template default argument as a pointer to itself
I am trying to develop a generic tree template class, basically, representing a hierarchy of identical nodes. It takes 2 template arguments, the first one is a data, and the second - a type which would reference another node (prev,next,parent,child). By default, I want it to be a conventional pointer to the node, but for my purpose I also need it to be something different (e.g an integer index into the memory pool). The code below does not compile. Instinctively, I feel it can be done, but I don't know how. Could anyone provide an insight into this?

```<code>template <typename U, typename TPTR = TreeNode_t<U>*>
class TreeNode_t
{
public:
    TPTR    prev;
    TPTR    next;
    TPTR    parent;
    TPTR    children;
    U m;
public:
    TreeNode_t() : prev(0), next(0), parent(0){}
    ~TreeNode_t(){}
    U &data() { return m; }
    const U &data() const { return m; }
    ...
</code>```

To be specific, in general I instantiate it like this:

```<code>TreeNode_t<double> tree1;
</code>```

But, sometimes I would like it this way:

```<code>TreeNode_t<double, unsigned> tree2;
</code>```

答:
provide a special default as void and use type inside the class:

```<code>template <typename U, typename TPTR = void>
class TreeNode_t
{
    using NodeType = std::conditional_t<std::is_same<void, TPTR>::value, TreeNode_t*, TPTR>;
public:
    NodeType    prev;
    NodeType    next;
    NodeType    parent;
    NodeType    children;
    U m;
// ...
};
</code>```

Body:
I am trying to develop a generic tree template class, basically, representing a hierarchy of identical nodes. It takes 2 template arguments, the first one is a data, and the second - a type which would reference another node (prev,next,parent,child). By default, I want it to be a conventional pointer to the node, but for my purpose I also need it to be something different (e.g an integer index into the memory pool). The code below does not compile. Instinctively, I feel it can be done, but I don't know how. Could anyone provide an insight into this?

template <typename U, typename TPTR = TreeNode_t*>
class TreeNode_t
{
public:
    TPTR    prev;
    TPTR    next;
    TPTR    parent;
    TPTR    children;
    U m;
public:
    TreeNode_t() : prev(0), next(0), parent(0){}
    ~TreeNode_t(){}
    U &data() { return m; }
    const U &data() const { return m; }
    ...

To be specific, in general I instantiate it like this:

TreeNode_t<double> tree1;

But, sometimes I would like it this way:

TreeNode_t<double, unsigned> tree2;

Body:
provide a special default as void and use type inside the class:

template <typename U, typename TPTR = void>
class TreeNode_t
{
    using NodeType = std::conditional_t<std::is_same<void, TPTR>::value, TreeNode_t*, TPTR>;
public:
    NodeType    prev;
    NodeType    next;
    NodeType    parent;
    NodeType    children;
    U m;
// ...
};


问:
Updating screen with messages from a thread that raises events (ASP.NET)
I have a very long running process that I start in a thread. This raises events with messages to say what it is doing.

How can I update a label on screen with these messages? (The label is in an update panel if that makes it easier).

If this is not possible, is there a better way you can suggest?

答:
Use the Background-worker   it is very useful the update the UI
link text</p>

ContentLicense: CC BY-SA 2.5


问:
Shape Detection API: "DOMException: Source would taint origin"
I am playing with Shape Detection API (https://github.com/WICG/shape-detection-api), basing on this examples: https://wicg.github.io/shape-detection-api/#examples

I am trying to get the simplest one to work:

```<code>let faceDetector = new FaceDetector({fastMode: true, maxDetectedFaces: 1});
// Assuming |theImage| is e.g. a <img> content, or a Blob.

faceDetector.detect(theImage)
.then(detectedFaces => {
  for (const face of detectedFaces) {
    console.log(' Face @ (${face.boundingBox.x}, ${face.boundingBox.y}),' +
    ' size ${face.boundingBox.width}x${face.boundingBox.height}');
  }
}).catch(() => {
  console.error("Face Detection failed, boo.");
})
</code>```

However, I am getting error:

```<code>VM153:1 Uncaught (in promise) DOMException: Source would taint origin.
</code>```

Image variable with I am using is one of images from stackoverflow:

```<code><img src="https://www.gravatar.com/avatar/619aaf27f793d8ffdbc879c74884c0cc?s=32&d=identicon&r=PG" alt="" width="32" height="32" id="testimg">
</code>```

My browser is Google Chrome Canary 61.0.3128.0, with the Experimental Web Features enabled.

Did I miss something?

答:
The answer is here:
https://wicg.github.io/shape-detection-api/#image-sources-for-detection

"If any ImageBitmapSource have an effective script origin (HTML Standard §concept-origin) which is not the same as the Document’s effective script origin, then reject the Promise with a new DOMException whose name is SecurityError."

Do not miss wrap you code if you are using loading image via HTML tag

```<code>window.onload = () => {
    // TODO: put you code here
};
</code>```

or via Image constructor

```<code>let image = new Image();
image.src = 'faces.jpg'
image.onload = () => {
    // TODO: put your code here
}
</code>```

Code example

Body:
I am playing with Shape Detection API (https://github.com/WICG/shape-detection-api), basing on this examples: https://wicg.github.io/shape-detection-api/#examples

I am trying to get the simplest one to work:

let faceDetector = new FaceDetector({fastMode: true, maxDetectedFaces: 1});
// Assuming |theImage| is e.g. a  content, or a Blob.

faceDetector.detect(theImage)
.then(detectedFaces => {
  for (const face of detectedFaces) {
    console.log(' Face @ (${face.boundingBox.x}, ${face.boundingBox.y}),' +
    ' size ${face.boundingBox.width}x${face.boundingBox.height}');
  }
}).catch(() => {
  console.error("Face Detection failed, boo.");
})

However, I am getting error:

VM153:1 Uncaught (in promise) DOMException: Source would taint origin.

Image variable with I am using is one of images from stackoverflow:

My browser is Google Chrome Canary 61.0.3128.0, with the Experimental Web Features enabled.

Did I miss something?

Body:
The answer is here:
https://wicg.github.io/shape-detection-api/#image-sources-for-detection

"If any ImageBitmapSource have an effective script origin (HTML Standard §concept-origin) which is not the same as the Document’s effective script origin, then reject the Promise with a new DOMException whose name is SecurityError."

Do not miss wrap you code if you are using loading image via HTML tag

window.onload = () => {
    // TODO: put you code here
};

or via Image constructor

let image = new Image();
image.src = 'faces.jpg'
image.onload = () => {
    // TODO: put your code here
}

Code example


问:
WooCommerce single product custom Tab displaying a page content
I have created a custom tab for a single product and would like to know with the code below if there is a way to specify a certain page to act as the content for that tab?</p>

```<code>add_filter( 'woocommerce_product_tabs', 'woo_new_product_tab' );

function woo_new_product_tab( $tabs ) {

  // Adds the new tab

  $tabs['test_tab'] = array(
    'title'     => __( 'Seller Disclosure', 'woocommerce' ),
    'priority'  => 50,
    'callback'  => 'woo_new_product_tab_content'
  );

  return $tabs;

}

function woo_new_product_tab_content() {

  // The new tab content

  echo '<h2>Coming Soon</h2>';

}
</code>```

答:
This is possible calling a classic WordPress post content for a defined post ID (page) this way:

```<code>//Add a new tab in single product pages
add_filter( 'woocommerce_product_tabs', 'woo_new_product_tab' );
function woo_new_product_tab( $tabs ) {
    $tabs['test_tab'] = array(
        'title'     => __( 'Seller Disclosure', 'woocommerce' ),
        'priority'  => 50,
        'callback'  => 'woo_new_product_tab_content'
    );
    return $tabs;
}

// The tab content (with the page content)
function woo_new_product_tab_content() {
    // ==> ==> ==> ==> ==> ==> ==> Replace the ID HERE by your page ID
    $page_id = 324;
    $page_post_object = get_post( $page_id );

    // Get the page content
    $page_content = $page_post_object->post_content;

    // (optionally Get the page title
    $page_title = $page_post_object->post_title;

    // The title (Or the page title)
    echo '<h2>Coming Soon</h2>'; // Or: echo '<h2>' . $page_title . '</h2>';

    // The page content
    echo '<div class="page-content-container">' . $page_content . '</div>';
}
</code>```

Code goes in any php file of your active child theme (or theme) or also in any plugin php file.

This code Is tested and works.

Body:
I have created a custom tab for a single product and would like to know with the code below if there is a way to specify a certain page to act as the content for that tab?

add_filter( 'woocommerce_product_tabs', 'woo_new_product_tab' );

function woo_new_product_tab( $tabs ) {

  // Adds the new tab

  $tabs['test_tab'] = array(
    'title'     => __( 'Seller Disclosure', 'woocommerce' ),
    'priority'  => 50,
    'callback'  => 'woo_new_product_tab_content'
  );

  return $tabs;

}

function woo_new_product_tab_content() {

  // The new tab content

  echo '
Coming Soon
';

}

Body:
This is possible calling a classic WordPress post content for a defined post ID (page) this way:

//Add a new tab in single product pages
add_filter( 'woocommerce_product_tabs', 'woo_new_product_tab' );
function woo_new_product_tab( $tabs ) {
    $tabs['test_tab'] = array(
        'title'     => __( 'Seller Disclosure', 'woocommerce' ),
        'priority'  => 50,
        'callback'  => 'woo_new_product_tab_content'
    );
    return $tabs;
}

// The tab content (with the page content)
function woo_new_product_tab_content() {
    // ==> ==> ==> ==> ==> ==> ==> Replace the ID HERE by your page ID
    $page_id = 324;
    $page_post_object = get_post( $page_id );

    // Get the page content
    $page_content = $page_post_object->post_content;

    // (optionally Get the page title
    $page_title = $page_post_object->post_title;

    // The title (Or the page title)
    echo '<h2>Coming Soon</h2>'; // Or: echo '<h2>' . $page_title . '</h2>';

    // The page content
    echo '<div class="page-content-container">' . $page_content . '</div>';
}

Code goes in any php file of your active child theme (or theme) or also in any plugin php file.

This code Is tested and works.


问:
Strange behaviour of the push
Here is the simple script i cannot understand:

```<code>function test() {
  var o = {"groupName":"A"};
  var a = [];
  var b = [{"name":"1"}, {"name":"2"}];
  for (var i in b) {
    var name = b[i].name;
    o.itemName = name;
    a.push(o);
  }
  Logger.log (a);
}
</code>```

I expect result to be

```<code>[
  {
    "groupName": "A",
    "itemName": {
      "name": "1"
    }
  },
  {
    "groupName": "A",
    "itemName": {
      "name": "2"
    }
  }
]
</code>```

but it is not. It is

```<code>[
  {
    "groupName": "A",
    "itemName": {
      "name": "2"
    }
  },
  {
    "groupName": "A",
    "itemName": {
      "name": "2"
    }
  }
]
</code>```

I want result include the same groupName for both iterations, but have different itemName

See the script here:

https://script.google.com/d/1VexsBJWZ1SBnb_4vnN1JA7a9KJkYzJ-hOcXwXvD2wa_GTXvdgt9xVOZb/edit?usp=sharing

答:
When you are pushing object to array, JavaScript (Google Apps Script) do it by the reference, so next time you change o object, it will be changed everywhere in a array.

You can create o variable on every iteration to make it perform like expected:

```<code>function test() {
  var a = [];
  var b = [{"name":"1"}, {"name":"2"}];
  for (var i in b) {
    var name = b[i].name;
    var o = {"groupName":"A"};
    o.itemName = name;
    a.push(o);
  }
  Logger.log(a);
}
</code>```

Title: Strange behaviour of the push

Body:
Here is the simple script i cannot understand:

function test() {
  var o = {"groupName":"A"};
  var a = [];
  var b = [{"name":"1"}, {"name":"2"}];
  for (var i in b) {
    var name = b[i].name;
    o.itemName = name;
    a.push(o);
  }
  Logger.log (a);
}

I expect result to be

[
  {
    "groupName": "A",
    "itemName": {
      "name": "1"
    }
  },
  {
    "groupName": "A",
    "itemName": {
      "name": "2"
    }
  }
]

but it is not. It is

[
  {
    "groupName": "A",
    "itemName": {
      "name": "2"
    }
  },
  {
    "groupName": "A",
    "itemName": {
      "name": "2"
    }
  }
]

I want result include the same groupName for both iterations, but have different itemName

See the script here:

https://script.google.com/d/1VexsBJWZ1SBnb_4vnN1JA7a9KJkYzJ-hOcXwXvD2wa_GTXvdgt9xVOZb/edit?usp=sharing

Body:
When you are pushing object to array, JavaScript (Google Apps Script) do it by the reference, so next time you change o object, it will be changed everywhere in a array.

You can create o variable on every iteration to make it perform like expected:

function test() {
  var a = [];
  var b = [{"name":"1"}, {"name":"2"}];
  for (var i in b) {
    var name = b[i].name;
    var o = {"groupName":"A"};
    o.itemName = name;
    a.push(o);
  }
  Logger.log(a);
}


问:
Partial rendering after page loaded
I have a page that contains some usercontrols. I would like to load these usercontrols after postback like an ajax rendering.

Each usercontrols display a list from database and I dont want the user to wait while server code builds up the response I think it will be useful if the page is displayed for the user and after the usercontrols are loaded through an ajax request.

Is there an exist solution in ASP.NET MVC? Is there an exist solution for this problem?

thanks advance: l.

答:
Just use jQuery to bind the HTML returned from the action method (which should return a partial view result - e.g the output of the user control/partial):

Controller:

```<code>[HttpGet]
public PartialViewResult GetSomeData()
{
   var data = somewhere.GetSomething();
   return PartialView(data); // partial view should be typed to data.
}
</code>```

jQuery:

```<code>$(document).ready(function() {
   $.get('/home/getsomedata/', function(data) {
      $('#target').html(data);
   });
});
</code>```

Title: Partial rendering after page loaded

Body:
Just use jQuery to bind the HTML returned from the action method (which should return a partial view result - e.g the output of the user control/partial):

Controller:

[HttpGet]
public PartialViewResult GetSomeData()
{
   var data = somewhere.GetSomething();
   return PartialView(data); // partial view should be typed to data.
}

jQuery:

$(document).ready(function() {
   $.get('/home/getsomedata/', function(data) {
      $('#target').html(data);
   });
});


问:
Rejecting react redux form with async/throw instead of promise
I am using react redux form to send form data to server. The form will correctly show failed if I return a promise that fails but not if I throw or use async/await with throw. I still have to return a rejected promise. Not sure what I am missing here or if that's the way of things.

Works:

```<code>export const myRequest = (data) => {
   return new Promise((resolve, reject) => {
    reject('Login failed!')
   })
}
</code>```

Does not (as well as the async/await variants):

```<code>export const myRequest = (data) => {
   throw new Error('Login failed')
}
</code>```

What I have to do:

```<code>export const myRequest = (data) => {
  try {
    ...
  } catch (err) {
     return new Promise((resolve, reject) => {
       reject(...)
   })
  }
}
</code>```

Here's some async code I am working with. I have to wrap the error message in a promise in order for the form to get the message, I am not sure why it doesn't get the message the same way when I throw.

```<code>const myRequest = async ( data) => {
  try {
    let response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    })

    if (!response.ok) {
      throw new Error(response.statusText)
    }
    return await response.json()
  } catch (err) {
    // Not working - no error message makes it - though it gets that it's an error
    throw new Error(err) // or new Error(err.message) or new Error('foo')

    // Works
    // return new Promise((resolve, reject) => {
    //   reject(err.message)
    // })
  }
}
</code>```

My React Redux Form:

```<code>import myRequest from '...'

handleSubmit (values) {
  const { dispatch } = this.props
  dispatch(actions.submit('subscribe', myRequest(values)))
}

render () {
   const { valid, pending, submitted, submitFailed } = this.props.form
  return (
    <Form model='subscribe' onSubmit={(values) => this.handleSubmit(values)}>
    { !valid && submitFailed ? <Alert>
      <Errors
        model='subscribe' // Form name as found in reducer
      /> : null
    }
    </Form>
  }
}
</code>```

答: Using an async function is the correct thing to do here. However, to get the equivalent of reject(err.message), you would need to do throw err.message. But you should never throw strings, better throw new Error(err.message). Or just throw err. Or just don't catch anything at all and let it bubble.

Body:
I am using react redux form to send form data to server. The form will correctly show failed if I return a promise that fails but not if I throw or use async/await with throw. I still have to return a rejected promise. Not sure what I am missing here or if that's the way of things.

Works:

export const myRequest = (data) => {
   return new Promise((resolve, reject) => {
    reject('Login failed!')
   })
}

Does not (as well as the async/await variants):

export const myRequest = (data) => {
   throw new Error('Login failed')
}

What I have to do:

export const myRequest = (data) => {
  try {
    ...
  } catch (err) {
     return new Promise((resolve, reject) => {
       reject(...)
   })
  }
}

Here's some async code I am working with. I have to wrap the error message in a promise in order for the form to get the message, I am not sure why it doesn't get the message the same way when I throw.

const myRequest = async ( data) => {
  try {
    let response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    })

    if (!response.ok) {
      throw new Error(response.statusText)
    }
    return await response.json()
  } catch (err) {
    // Not working - no error message makes it - though it gets that it's an error
    throw new Error(err) // or new Error(err.message) or new Error('foo')

    // Works
    // return new Promise((resolve, reject) => {
    //   reject(err.message)
    // })
  }
}

My React Redux Form:

import myRequest from '...'

handleSubmit (values) {
  const { dispatch } = this.props
  dispatch(actions.submit('subscribe', myRequest(values)))
}

render () {
   const { valid, pending, submitted, submitFailed } = this.props.form
  return (
    <Form model='subscribe' onSubmit={(values) => this.handleSubmit(values)}>
    { !valid && submitFailed ? <Alert>
      <Errors
        model='subscribe' // Form name as found in reducer
      /> : null
    }
    </Form>
  }
}


问:
Android/Firebase - Can't convert object of type java.util.ArrayList to type **my object**
I'm trying to get the values of each node under "templates."

For example, "eght" (just random test name), contains an ArrayList of ArrayLists. So, ArrayList<.ArrayList>.

I just need to get the values once, so I'm using a single event listener:

```<code>mTemplateRef.addListenerForSingleValueEvent(
     new ValueEventListener() {
     @Override
     public void onDataChange(DataSnapshot dataSnapshot) {

          for(DataSnapshot templateSnapshot : dataSnapshot.getChildren()){

               // I've tried a million different things here, but all result in the error
              // This is the error line
              MapFoo mapFoo = templateSnapshot.getValue(MapFoo.class);
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    Log.w(TAG, "getUser:onCancelled", databaseError.toException());
                    // ...
                }
            });
</code>```

I always end up with this:

```<code>Can't convert object of type java.util.ArrayList to type com.appname.template_editor.MapFoo
</code>```

The last part being any object I try.

Here's MapFoo:

By the way, I"m using a Map because when I debug, the nodes seem to be in HashMap form. I've also tried a HashMap object with the same error. I've also tried several other objects to try to make it work with no success.

```<code>public class MapFoo {
public Map<String, ArrayList> mapList;

public MapFoo(){

}

public Map getMapList(){
    return mapList;
}

public MapFoo(Map<String, ArrayList> mapList){
    this.mapList = mapList;
}
</code>```

}

Another variation I tried:

```<code>public class MasterListTemplateClass {

public String templateName;
public ArrayList<ArrayList> arrayList;

public MasterListTemplateClass() {
}

public MasterListTemplateClass(String templateName, ArrayList<ArrayList> arrayList) {
    this.templateName = templateName;
    this.arrayList = arrayList;
}

public String getName() {
    return templateName;
}

public ArrayList<ArrayList> getList() {
    return arrayList;
}
</code>```

}

I just can't get any of this to work. I simply need the values in my database!

答: Just remembered this post. Have found the answer. When you're working with maps in Firebase, if you have an int as a string (1 vs "1"), Firebase reads that as an int. Whether you inputted it as a string or not. So what I did was add "_key" to the numbers ("1_key") which forced Firebase to read it as a string and not an int. This fixed things right up</p>

Body:
I'm trying to get the values of each node under "templates."

For example, "eght" (just random test name), contains an ArrayList of ArrayLists. So, ArrayList<.ArrayList>.

I just need to get the values once, so I'm using a single event listener:

mTemplateRef.addListenerForSingleValueEvent(
     new ValueEventListener() {
     @Override
     public void onDataChange(DataSnapshot dataSnapshot) {

          for(DataSnapshot templateSnapshot : dataSnapshot.getChildren()){

               // I've tried a million different things here, but all result in the error
              // This is the error line
              MapFoo mapFoo = templateSnapshot.getValue(MapFoo.class);
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    Log.w(TAG, "getUser:onCancelled", databaseError.toException());
                    // ...
                }
            });

I always end up with this:

Can't convert object of type java.util.ArrayList to type com.appname.template_editor.MapFoo

The last part being any object I try.

Here's MapFoo:

By the way, I"m using a Map because when I debug, the nodes seem to be in HashMap form. I've also tried a HashMap object with the same error. I've also tried several other objects to try to make it work with no success.

public class MapFoo {
public Map<String, ArrayList> mapList;

public MapFoo(){

}

public Map getMapList(){
    return mapList;
}

public MapFoo(Map<String, ArrayList> mapList){
    this.mapList = mapList;
}

}

Another variation I tried:

public class MasterListTemplateClass {

public String templateName;
public ArrayList<ArrayList> arrayList;

public MasterListTemplateClass() {
}

public MasterListTemplateClass(String templateName, ArrayList<ArrayList> arrayList) {
    this.templateName = templateName;
    this.arrayList = arrayList;
}

public String getName() {
    return templateName;
}

public ArrayList<ArrayList> getList() {
    return arrayList;
}

}

I just can't get any of this to work. I simply need the values in my database!


问:
Post-Hoc Statistical Analysis for Repeated Measures ANOVA Treatment within Time Effect
I am having trouble finding a post hoc test to decipher at what "Session" or time I have a treatment within session affect.

This is my data:

```<code>TR  SESSION MAC FISHD      ID
1   1      1    3.285714286 1
2   1      2    0.571428571 2
2   1      3    3.571428571 3
1   1      4    4           4
1   2      1    4           5
2   2      2    6.571428571 6
2   2      3    3.142857143 7
1   2      4    8.857142857 8
1   3      1    0.714285714 9
2   3      2    1.714285714 10
2   3      3    4.428571429 11
1   3      4    0.714285714 12
</code>```

This is how I got repeated measures:

```<code>model.b = lme(FISHD ~ TR + SESSION + TR*SESSION,
            random = ~1|MAC,
            data=TTDall2)

> ACF(model.b)
  lag        ACF
1   0  1.0000000
2   1 -0.7547232
3   2  0.4852727

> model2 = lme(FISHD ~ TR + SESSION + TR*SESSION,
+ random = ~1|MAC,
+ correlation = corAR1(form = ~ SESSION | MAC,
+                                                                                value = -0.7547232),
+   data=TTDall2,
+  method="REML")
> Anova(model2)
Analysis of Deviance Table (Type II tests)

Response: FISHD
                     Chisq      Df Pr(>Chisq)
TR               0.2014     1     0.6536
SESSION          25.0418    1   5.61e-07 ***
TR:SESSION       103.9113   1  < 2.2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
</code>```

I am trying to decipher when there is a treatment affect. Any ideas?

答:
At the moment you are modeling session as a continuous variable and so the reported coefficient for TR:SESSION is sort of a "test of trend" across the range 1:3 for that value of SESSION in TRT=2  .... is that what you were hoping to discover? Let's do it the right way, with factors and in particular create an ordered factor:

```<code>model2 = lme(FISHD ~ factor(TR)*ordered(SESSION), # same as TRT+SESSION+TRT*ORDERED
 random = ~1|MAC,
 correlation = corAR1(form = ~ SESSION | MAC,
 value = -0.7547232),
   data=dat,
  method="REML")
 anova(model2)
 #------
                            numDF denDF  F-value p-value
(Intercept)                     1     4 37.48966  0.0036
factor(TR)                      1     2  0.20124  0.6976
ordered(SESSION)                2     4 13.94379  0.0157
factor(TR):ordered(SESSION)     2     4 52.02864  0.0014
</code>```

So this is saying that an analysis that takes into account the interaction of TRT with sequence of SESSIONs finds a significant difference for the effect of TRT. If you do not model the interaction (using formula: FISHD ~  factor(TR)+ordered(SESSION), then neither component is significant:

```<code>model1 = lme(FISHD ~  factor(TR)+ordered(SESSION),
 random = ~1|MAC,
 correlation = corAR1(form = ~ SESSION | MAC, value = -0.7547232),
   data=dat,
  method="REML")
 anova(model1)
 #-------------
                 numDF denDF  F-value p-value
(Intercept)          1     6 44.53272  0.0005
factor(TR)           1     2  0.14143  0.7430
ordered(SESSION)     2     6  2.55154  0.1578
</code>```

And:

```<code>>  anova(model1, model2)
       Model df      AIC      BIC    logLik   Test  L.Ratio p-value
model1     1  7 54.74813 55.30422 -20.37406
model2     2  9 44.04435 42.17018 -13.02217 1 vs 2 14.70378   6e-04
Warning message:
In anova.lme(model1, model2) :
  fitted objects with different fixed effects. REML comparisons are not meaningful.
</code>```

That is a warning but I do not think it applies here since the varaialbes in the model are the same and only the structure is different.

Body:
I am having trouble finding a post hoc test to decipher at what "Session" or time I have a treatment within session affect.

This is my data:

TR  SESSION MAC FISHD      ID
1   1      1    3.285714286 1
2   1      2    0.571428571 2
2   1      3    3.571428571 3
1   1      4    4           4
1   2      1    4           5
2   2      2    6.571428571 6
2   2      3    3.142857143 7
1   2      4    8.857142857 8
1   3      1    0.714285714 9
2   3      2    1.714285714 10
2   3      3    4.428571429 11
1   3      4    0.714285714 12

This is how I got repeated measures:

model.b = lme(FISHD ~ TR + SESSION + TR*SESSION,
            random = ~1|MAC,
            data=TTDall2)

> ACF(model.b)
  lag        ACF
1   0  1.0000000
2   1 -0.7547232
3   2  0.4852727

> model2 = lme(FISHD ~ TR + SESSION + TR*SESSION,
+ random = ~1|MAC,
+ correlation = corAR1(form = ~ SESSION | MAC,
+                                                                                value = -0.7547232),
+   data=TTDall2,
+  method="REML")
> Anova(model2)
Analysis of Deviance Table (Type II tests)

Response: FISHD
                     Chisq      Df Pr(>Chisq)
TR               0.2014     1     0.6536
SESSION          25.0418    1   5.61e-07 ***
TR:SESSION       103.9113   1  < 2.2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

I am trying to decipher when there is a treatment affect. Any ideas?

Body:
At the moment you are modeling session as a continuous variable and so the reported coefficient for TR:SESSION is sort of a "test of trend" across the range 1:3 for that value of SESSION in TRT=2  .... is that what you were hoping to discover? Let's do it the right way, with factors and in particular create an ordered factor:

model2 = lme(FISHD ~ factor(TR)*ordered(SESSION), # same as TRT+SESSION+TRT*ORDERED
 random = ~1|MAC,
 correlation = corAR1(form = ~ SESSION | MAC,
 value = -0.7547232),
   data=dat,
  method="REML")
 anova(model2)
 #------
                            numDF denDF  F-value p-value
(Intercept)                     1     4 37.48966  0.0036
factor(TR)                      1     2  0.20124  0.6976
ordered(SESSION)                2     4 13.94379  0.0157
factor(TR):ordered(SESSION)     2     4 52.02864  0.0014

So this is saying that an analysis that takes into account the interaction of TRT with sequence of SESSIONs finds a significant difference for the effect of TRT. If you do not model the interaction (using formula: FISHD ~  factor(TR)+ordered(SESSION), then neither component is significant:

model1 = lme(FISHD ~  factor(TR)+ordered(SESSION),
 random = ~1|MAC,
 correlation = corAR1(form = ~ SESSION | MAC, value = -0.7547232),
   data=dat,
  method="REML")
 anova(model1)
 #-------------
                 numDF denDF  F-value p-value
(Intercept)          1     6 44.53272  0.0005
factor(TR)           1     2  0.14143  0.7430
ordered(SESSION)     2     6  2.55154  0.1578

And:

>  anova(model1, model2)
       Model df      AIC      BIC    logLik   Test  L.Ratio p-value
model1     1  7 54.74813 55.30422 -20.37406
model2     2  9 44.04435 42.17018 -13.02217 1 vs 2 14.70378   6e-04
Warning message:
In anova.lme(model1, model2) :
  fitted objects with different fixed effects. REML comparisons are not meaningful.

That is a warning but I do not think it applies here since the varaialbes in the model are the same and only the structure is different.


问:
reading in a file and CryptUnprotectData in C
I have the following problem, I want to read in an encrypted file from my computer and just put to the command console what it says.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <wincrypt.h>

int main(int argc, char **argv){
    DATA_BLOB encr;
    DATA_BLOB decr;
    char c;
    int i;
    FILE *fp = fopen("some data", "rb");
    encr.cbData = 1;
    fseek(fp, 20L, SEEK_SET);
    for (i = 0; i < 60; i++){
        c = fgetc(fp);
        encr.pbData = (BYTE*)c;
        printf("%c", c);
        CryptUnprotectData(&encr, NULL, NULL, NULL, NULL, 0, &decr)
        printf("%s", decr.pbData);
        encr.pbData = NULL;
    }
    return 0;
}
</code>```

Somehow this doesn't work and I don't know how to get the output.

答:
You can't decrypt byte by byte. You have to read the whole thing into a buffer and then pass it all to CryptUnprotectData(). When you originally called CryptProtectData() it told you what the size of the output was. That's the size of the buffer you should decrypt all at once.

Assuming your buffer is actually 60 bytes and in the 20 offset, your code should look something like:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <wincrypt.h>

int main(int argc, char **argv){
  BYTE buffer[60];
  DATA_BLOB encr;
  DATA_BLOB decr;
  char c;
  int i;
  FILE *fp = fopen("some data", "rb"); // TODO check return value
  encr.cbData = 1;
  encr.pbData = buffer;
  fseek(fp, 20L, SEEK_SET); // TODO check return value
  fread(buffer, 60, 1, fp); // TODO check return value
  CryptUnprotectData(&encr, NULL, NULL, NULL, NULL, 0, &decr); // TODO check return value
  printf("%s", decr.pbData);
  return 0;
}
</code>```

Body:
I have the following problem, I want to read in an encrypted file from my computer and just put to the command console what it says.

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <wincrypt.h>

int main(int argc, char **argv){
    DATA_BLOB encr;
    DATA_BLOB decr;
    char c;
    int i;
    FILE *fp = fopen("some data", "rb");
    encr.cbData = 1;
    fseek(fp, 20L, SEEK_SET);
    for (i = 0; i < 60; i++){
        c = fgetc(fp);
        encr.pbData = (BYTE*)c;
        printf("%c", c);
        CryptUnprotectData(&encr, NULL, NULL, NULL, NULL, 0, &decr)
        printf("%s", decr.pbData);
        encr.pbData = NULL;
    }
    return 0;
}

Somehow this doesn't work and I don't know how to get the output.

Body:
You can't decrypt byte by byte. You have to read the whole thing into a buffer and then pass it all to CryptUnprotectData(). When you originally called CryptProtectData() it told you what the size of the output was. That's the size of the buffer you should decrypt all at once.

Assuming your buffer is actually 60 bytes and in the 20 offset, your code should look something like:

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <wincrypt.h>

int main(int argc, char **argv){
  BYTE buffer[60];
  DATA_BLOB encr;
  DATA_BLOB decr;
  char c;
  int i;
  FILE *fp = fopen("some data", "rb"); // TODO check return value
  encr.cbData = 1;
  encr.pbData = buffer;
  fseek(fp, 20L, SEEK_SET); // TODO check return value
  fread(buffer, 60, 1, fp); // TODO check return value
  CryptUnprotectData(&encr, NULL, NULL, NULL, NULL, 0, &decr); // TODO check return value
  printf("%s", decr.pbData);
  return 0;
}


问:
Profile picture default size
AS in facebook,orkut what should be  the profile pic settings height,width etc so that the image is clear and do not have any distortion when viewing it</p>

```<code>     <img src="image.gif"  style="height:75px;width:130px;"  />
</code>```

答:
To avoid distortion in the thumbnail image you should take the original image, and, using whatever image manipulation program or technique (php, Photoshop...) you have available, resize/crop the image to whatever size you consider appropriate:

Original image profilePicture.png, 600 x 500px, convert to:

profilePictureThumbnail.png, 200 x 240px

And then use the profilePictureThumbnail.png rather than using the img tag to resize/scale the image.

I'd still suggest using height and width attributes in the img tag, since that allows the browser to lay out the page even if the network, or image-server, is slow to respond with the actual image.

I'd definitely avoid using the browser to resize the image since it still requires the picture to be downloaded (at its full size/resolution), and browser image manipulation is not particularly sensitive (and varies from Firefox to Chrome to IE to Opera...), not to mention that people on mobile internet packages won't thank you for throwing, potentially, multi-megabyte images at them via their mobile tariff.

Title: Profile picture default size


问:
Do I need to run compaction on each node of the cluster in cassandra 3
We are having 4 node cassandra cluster . Do I need to run compact and repair on each node of the cluster ?

Cassandra Version:- Cassandra 3.0.10
No of nodes in a cluster : 4
Replication Factor :- 4
Compaction Strategy:- LeveledCompactionStrategy

Thanks

答: Yep, compaction is done automatically, but you should run a regular repair


问:
yield doesn't work in section Laravel Blade
I have the site with the structure like:

First: master.blade.php : this contain section('content')

```<code><body>
   @include('partial.header')
   @yield('content')
   @include('partial.footer')
</body>
</code>```

Second index.blade.php : contain section('content').

```<code>@extends('layouts.master')
@section('content')
<div id="container">
   <div id="news">
      @yield('news')
   </div>
   <div id="apartment">
      @yield('apartment')
   </div>
</div> <!-- ./container -->
@endsection
</code>```

Third: news.blade.php : this simple to show all news

```<code>@foreach($posts as $post)
@endforeach
</code>```

Final file: apartment.blade.php : this simple to show all apartment.

```<code>@foreach($apartments as $apartment)
@endforeach
</code>```

My route direct to master.blade.php.
My question is:

When I include news with @yield('news') in index.blade.php. It shows correct all news in my database.
But when I delete @yield('news') in index.blade.php. It also show news from my database (but it's lost css/js for that).
Why I deleted @yield('news'), it's should don't show any news on my page?

Seem Laravel Blade not support two @yield in @section. When I add only 1 row @yield('news') into index.blade.php file. It shows list news on my index page. When I continues add @yield('apartment'). Don't have any apartment shown on the index page. I certainly it has values when foreach to get data. I also test with HTML statics but don't have anything changes.

答:
My route direct to master.blade.php.

Index extends master, so point your route to index view.

If sections continue to be yielded, after @yield removal, I think the framework is loading a cached view.

Try clearing the view cache php artisan view:clear or use php artisan --help view:clear for help.

Also @yield yields a section in a parent child relationship.

Change yields to include like @include('partial.news') if news are in partial folder or to whatever the path. Rendering could be manipulated using @isset or @empty statements or even @forelse loops.

Blade Control Structures.

Body:
I have the site with the structure like:

First: master.blade.php : this contain section('content')

   @include('partial.header')
   @yield('content')
   @include('partial.footer')

Second index.blade.php : contain section('content').

@extends('layouts.master')
@section('content')

      @yield('news')

      @yield('apartment')

@endsection

Third: news.blade.php : this simple to show all news

@foreach($posts as $post)
@endforeach

Final file: apartment.blade.php : this simple to show all apartment.

@foreach($apartments as $apartment)
@endforeach

My route direct to master.blade.php.
My question is:

When I include news with @yield('news') in index.blade.php. It shows correct all news in my database.
But when I delete @yield('news') in index.blade.php. It also show news from my database (but it's lost css/js for that).
Why I deleted @yield('news'), it's should don't show any news on my page?

Seem Laravel Blade not support two @yield in @section. When I add only 1 row @yield('news') into index.blade.php file. It shows list news on my index page. When I continues add @yield('apartment'). Don't have any apartment shown on the index page. I certainly it has values when foreach to get data. I also test with HTML statics but don't have anything changes.


问:
Find the most popular element in int[] array
```<code>int[] a = new int[10]{1,2,3,4,5,6,7,7,7,7};
</code>```

how can I write a method and return 7?

I want to keep it native without the help of lists, maps or other helpers.
Only arrays[].

答:
below code can be put inside a main method</p>

```<code>    // TODO Auto-generated method stub
    Integer[] a = { 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 1, 2, 2, 2, 2, 3, 4, 2 };
    List<Integer> list = new ArrayList<Integer>(Arrays.asList(a));
    Set<Integer> set = new HashSet<Integer>(list);
    int highestSeq = 0;
    int seq = 0;
    for (int i : set) {
        int tempCount = 0;
        for (int l : list) {
            if (i == l) {
                tempCount = tempCount + 1;
            }
            if (tempCount > highestSeq) {
                highestSeq = tempCount;
                seq = i;
            }
        }

    }

    System.out.println("highest sequence is " + seq + " repeated for " + highestSeq);
</code>```

Body:
int[] a = new int[10]{1,2,3,4,5,6,7,7,7,7};

how can I write a method and return 7?

I want to keep it native without the help of lists, maps or other helpers.
Only arrays[].

Body:
below code can be put inside a main method

    // TODO Auto-generated method stub
    Integer[] a = { 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 1, 2, 2, 2, 2, 3, 4, 2 };
    List<Integer> list = new ArrayList<Integer>(Arrays.asList(a));
    Set<Integer> set = new HashSet<Integer>(list);
    int highestSeq = 0;
    int seq = 0;
    for (int i : set) {
        int tempCount = 0;
        for (int l : list) {
            if (i == l) {
                tempCount = tempCount + 1;
            }
            if (tempCount > highestSeq) {
                highestSeq = tempCount;
                seq = i;
            }
        }

    }

    System.out.println("highest sequence is " + seq + " repeated for " + highestSeq);


问:
Super class to call a function from a subclass
I have a base class with two methods, "A" and "B".

Method "B" calls "A" in the base. Then I have a subclass which overrides "A" method. When I call the method "B" from subclass the method "A" from base is called.

Is there a way the super calls the overridden method from the subclass?

```<code>export class SuperClass {
    A(param: any): string {
        return "A called from base";
    }

    B(param: any): string {
        let value = this.A(param);
        console.log(value);

        return "B called from base";
    }
}

export class SubClass extends BaseClass  {
    A(param: any): string {
        return "A called from subclass";
    }
}

// create a subclass
let bInstance = new B();
bInstance.B(someParam); // I want to call the overriden A in the subclass
</code>```

PD: "A" in the base class needs to have its own implementation, can't be abstract

答:
bInstance.B(someParam); // I want to call the overriden A in the
  subclass

It will call the overridden method A in the subclass because this will be pointing to the instance of SubClass and JS will be looking for a method A on this instance first. So this code:

```<code>B(param: any): string {
    let value = this.A(param);
    console.log(value);
</code>```

should log "A called from subclass";

Body:
I have a base class with two methods, "A" and "B".

Method "B" calls "A" in the base. Then I have a subclass which overrides "A" method. When I call the method "B" from subclass the method "A" from base is called.

Is there a way the super calls the overridden method from the subclass?

export class SuperClass {
    A(param: any): string {
        return "A called from base";
    }

    B(param: any): string {
        let value = this.A(param);
        console.log(value);

        return "B called from base";
    }
}

export class SubClass extends BaseClass  {
    A(param: any): string {
        return "A called from subclass";
    }
}

// create a subclass
let bInstance = new B();
bInstance.B(someParam); // I want to call the overriden A in the subclass

PD: "A" in the base class needs to have its own implementation, can't be abstract

Body:
bInstance.B(someParam); // I want to call the overriden A in the
  subclass

It will call the overridden method A in the subclass because this will be pointing to the instance of SubClass and JS will be looking for a method A on this instance first. So this code:

B(param: any): string {
    let value = this.A(param);
    console.log(value);

should log "A called from subclass";


问:
how to store array value in angularjs and then redirect
```<code>$scope.messagearray = {};
$scope.messagewant = function(info) {
    $scope.messagearray = info;
    $location.path("/messagewant");
}
</code>```

my code is redirecting without storing value in array

答:
The code can be modified like this. Now info is passed to new location via query parameters.</p>

```<code>$scope.messagearray = {};
$scope.messagewant = function(info) {
    $scope.messagearray = info;
    $location.path("/messagewant?info="+info);
}
</code>```

Body:
$scope.messagearray = {};
$scope.messagewant = function(info) {
    $scope.messagearray = info;
    $location.path("/messagewant");
}

my code is redirecting without storing value in array

Body:
The code can be modified like this. Now info is passed to new location via query parameters.

$scope.messagearray = {};
$scope.messagewant = function(info) {
    $scope.messagearray = info;
    $location.path("/messagewant?info="+info);
}


问:
Adding view from another class as presentViewController causes UIEvents not working
I am trying to build a simple library with working UIElements. What I am trying to do is, creating UIViewController objects from one class instances and push that new ViewController on the current VC Stack with the presentViewController method.

I can see that the UIElements has been successfully adding on the stack, but GestureRecognizer and UIButton's target does not work. When I am checking on ViewDebug, these settings are <NSNull null>.

This is my class method which I am creating the UI and putting on the current view stack.

```<code>-(void)displayAd{

    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        //Background Thread
        NSData * imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:fullpageCampaign.mainImage]];

        dispatch_async(dispatch_get_main_queue(), ^(void){
            //Run UI Updates
            fullPageView = [[UIViewController alloc] init];
            fullPageView.view.frame = CurrentVC.view.bounds;
            fullPageView.view.backgroundColor = [UIColor redColor];
            UIImageView *staticImageView = [[UIImageView alloc] init];
            staticImageView.frame = CurrentVC.view.frame;

            UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];
            singleTap.numberOfTapsRequired = 1;
            [staticImageView addGestureRecognizer:singleTap];
            staticImageView.userInteractionEnabled = YES;
            [fullPageView.view addSubview:staticImageView];

            staticImageView.image = [UIImage imageWithData:imageData];
            [CurrentVC.view addSubview:fullPageView.view];
            //[fullPageView didMoveToParentViewController:self];
            [CurrentVC presentViewController:fullPageView animated:YES completion:^{
                NSLog(@"Tagon Ads is about to showing.");
                UIButton *closeButton = [self createButtonWithAssetName:@"tagonAssets.bundle/close_button" TargetMethod:@"closeModal" andView:staticImageView];
                [staticImageView addSubview:closeButton];
                [CurrentVC.view bringSubviewToFront:closeButton];
            }];
        });
    });
}
</code>```

CurrentVC is the current viewController that I am sending as a parameter through my library's method in order to add a new viewController stack on to it.

答:
There are several problems with your code, but first of all, I would recommend a different approach to accomplish what you want. As you can see below, using an instance of UIViewController is not the recommended way. Instead, use a storyboard to set up your view controller and it's components. Your code will be much smaller and your design will be easy to understand and change.

You can read more about UIViewController here

You rarely create instances of the UIViewController class directly.
  Instead, you create instances of UIViewController subclasses and use
  those objects to provide the specific behaviors and visual appearances
  that you need.

Here is another potential. Is fullpageCampaign.mainImage residing remotely or locally? If remotely located, then you should consider changing to NSURLSession instead.

Read more about NSData:dataWithContentsOfURL here

Do not use this synchronous method to request network-based URLs. For
  network-based URLs, this method can block the current thread for tens
  of seconds on a slow network, resulting in a poor user experience, and
  in iOS, may cause your app to be terminated.

Another minor thing is that you add the button to the image view. While this is OK, and might work when you allow user interaction for the image view, a cleaner way to do it is to create a UIView container to hold the image view and the button. The container can then also be the view that you attach the tap gesture recognizer to. That way, the image view can stay as a pure image.

The storyboard approach

First, create a sub-class of UIIViewController. It should look something like this:

FullPageViewController.h

```<code>#import <UIKit/UIKit.h>

@interface FullPageViewController : UIViewController

- (void)setImage:(UIImage *)adImage;

@end
</code>```

FullPageViewController.m

```<code>#import "FullPageViewController.h"

@interface FullPageViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *adImageView;

@end

@implementation FullPageViewController

- (void)setImage:(UIImage *)adImage {
    self.adImageView.image = adImage;
}

- (IBAction)tappedOnAd:(UIGestureRecognizer *)sender {
    if (sender.state == UIGestureRecognizerStateEnded) {
        // Do your ad thing here
    }
}

- (IBAction)closeButtonPressed:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
</code>```

Second, create a storyboard and add your ad view controller to it. Then add an image view, a button, and a tap gesture recognizer to your view controller. The tap gesture recognizer should be dropped on the image view to capture taps from there. You pull all of these objects from the Object Library down right. Also remember to enable user interaction for the image view. There is a property for that on the property page.

You should now have something that looks like this:

Notice the class name top right which should be the name of your new view controller class you just created. Also notice the storyboard ID adVC which you need when instantiating the view controller from code.

The next step is to connect the objects. Select the image view, then drag from the outlet (the ring) under Referencing Outlets to the view controller icon (the yellow icon with a square in) located on top of the view controller window, and select adImageView. The gesture recognizer should already be connected, if you dropped it on the image view when you placed it previously.

Next, connect the action for the close button. Drag from the Touch Up Inside outlet to the view controller icon (the yellow one), and select the closeButtonPressed: method.

Next, connect the tap gesture recognizer to your code. Select it from the list on the left, then drag from Sent Actions to the view controller icon and select tappedOnAd:.

Finally, your code to show the ad looks something like this. This method belongs in your parent view controller.

```<code>-(void)displayAd{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        //Background Thread
        NSData * imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:fullpageCampaign.mainImage]];

        dispatch_async(dispatch_get_main_queue(), ^(void){
        //Run UI Updates
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"AdPage" bundle:nil];
            UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"adVC"];
            [vc setImage:[UIImage imageWithData:imageData]];
            [self presentViewController:vc animated:YES completion:^{}];
        });
    });
}
</code>```

Body:
I am trying to build a simple library with working UIElements. What I am trying to do is, creating UIViewController objects from one class instances and push that new ViewController on the current VC Stack with the presentViewController method.

I can see that the UIElements has been successfully adding on the stack, but GestureRecognizer and UIButton's target does not work. When I am checking on ViewDebug, these settings are <NSNull null>.

This is my class method which I am creating the UI and putting on the current view stack.

-(void)displayAd{

    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        //Background Thread
        NSData * imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:fullpageCampaign.mainImage]];

        dispatch_async(dispatch_get_main_queue(), ^(void){
            //Run UI Updates
            fullPageView = [[UIViewController alloc] init];
            fullPageView.view.frame = CurrentVC.view.bounds;
            fullPageView.view.backgroundColor = [UIColor redColor];
            UIImageView *staticImageView = [[UIImageView alloc] init];
            staticImageView.frame = CurrentVC.view.frame;

            UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];
            singleTap.numberOfTapsRequired = 1;
            [staticImageView addGestureRecognizer:singleTap];
            staticImageView.userInteractionEnabled = YES;
            [fullPageView.view addSubview:staticImageView];

            staticImageView.image = [UIImage imageWithData:imageData];
            [CurrentVC.view addSubview:fullPageView.view];
            //[fullPageView didMoveToParentViewController:self];
            [CurrentVC presentViewController:fullPageView animated:YES completion:^{
                NSLog(@"Tagon Ads is about to showing.");
                UIButton *closeButton = [self createButtonWithAssetName:@"tagonAssets.bundle/close_button" TargetMethod:@"closeModal" andView:staticImageView];
                [staticImageView addSubview:closeButton];
                [CurrentVC.view bringSubviewToFront:closeButton];
            }];
        });
    });
}

CurrentVC is the current viewController that I am sending as a parameter through my library's method in order to add a new viewController stack on to it.

Body:
There are several problems with your code, but first of all, I would recommend a different approach to accomplish what you want. As you can see below, using an instance of UIViewController is not the recommended way. Instead, use a storyboard to set up your view controller and it's components. Your code will be much smaller and your design will be easy to understand and change.

You can read more about UIViewController here

You rarely create instances of the UIViewController class directly.
  Instead, you create instances of UIViewController subclasses and use
  those objects to provide the specific behaviors and visual appearances
  that you need.

Here is another potential. Is fullpageCampaign.mainImage residing remotely or locally? If remotely located, then you should consider changing to NSURLSession instead.

Read more about NSData:dataWithContentsOfURL here

Do not use this synchronous method to request network-based URLs. For
  network-based URLs, this method can block the current thread for tens
  of seconds on a slow network, resulting in a poor user experience, and
  in iOS, may cause your app to be terminated.

Another minor thing is that you add the button to the image view. While this is OK, and might work when you allow user interaction for the image view, a cleaner way to do it is to create a UIView container to hold the image view and the button. The container can then also be the view that you attach the tap gesture recognizer to. That way, the image view can stay as a pure image.

The storyboard approach

First, create a sub-class of UIIViewController. It should look something like this:

FullPageViewController.h

#import <UIKit/UIKit.h>

@interface FullPageViewController : UIViewController

- (void)setImage:(UIImage *)adImage;

@end

FullPageViewController.m

#import "FullPageViewController.h"

@interface FullPageViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *adImageView;

@end

@implementation FullPageViewController

- (void)setImage:(UIImage *)adImage {
    self.adImageView.image = adImage;
}

- (IBAction)tappedOnAd:(UIGestureRecognizer *)sender {
    if (sender.state == UIGestureRecognizerStateEnded) {
        // Do your ad thing here
    }
}

- (IBAction)closeButtonPressed:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end

Second, create a storyboard and add your ad view controller to it. Then add an image view, a button, and a tap gesture recognizer to your view controller. The tap gesture recognizer should be dropped on the image view to capture taps from there. You pull all of these objects from the Object Library down right. Also remember to enable user interaction for the image view. There is a property for that on the property page.

You should now have something that looks like this:

Notice the class name top right which should be the name of your new view controller class you just created. Also notice the storyboard ID adVC which you need when instantiating the view controller from code.

The next step is to connect the objects. Select the image view, then drag from the outlet (the ring) under Referencing Outlets to the view controller icon (the yellow icon with a square in) located on top of the view controller window, and select adImageView. The gesture recognizer should already be connected, if you dropped it on the image view when you placed it previously.

Next, connect the action for the close button. Drag from the Touch Up Inside outlet to the view controller icon (the yellow one), and select the closeButtonPressed: method.

Next, connect the tap gesture recognizer to your code. Select it from the list on the left, then drag from Sent Actions to the view controller icon and select tappedOnAd:.

Finally, your code to show the ad looks something like this. This method belongs in your parent view controller.

-(void)displayAd{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        //Background Thread
        NSData * imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:fullpageCampaign.mainImage]];

        dispatch_async(dispatch_get_main_queue(), ^(void){
        //Run UI Updates
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"AdPage" bundle:nil];
            UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"adVC"];
            [vc setImage:[UIImage imageWithData:imageData]];
            [self presentViewController:vc animated:YES completion:^{}];
        });
    });
}


问:
Template default argument as a pointer to itself
I am trying to develop a generic tree template class, basically, representing a hierarchy of identical nodes. It takes 2 template arguments, the first one is a data, and the second - a type which would reference another node (prev,next,parent,child). By default, I want it to be a conventional pointer to the node, but for my purpose I also need it to be something different (e.g an integer index into the memory pool). The code below does not compile. Instinctively, I feel it can be done, but I don't know how. Could anyone provide an insight into this?

```<code>template <typename U, typename TPTR = TreeNode_t<U>*>
class TreeNode_t
{
public:
    TPTR    prev;
    TPTR    next;
    TPTR    parent;
    TPTR    children;
    U m;
public:
    TreeNode_t() : prev(0), next(0), parent(0){}
    ~TreeNode_t(){}
    U &data() { return m; }
    const U &data() const { return m; }
    ...
</code>```

To be specific, in general I instantiate it like this:

```<code>TreeNode_t<double> tree1;
</code>```

But, sometimes I would like it this way:

```<code>TreeNode_t<double, unsigned> tree2;
</code>```

答:
You don't need two type parameters as the pointer can be deduced from the base type. Of course TreeNode_t is not defined before the template thus it doesn't compile.</p>

```<code>template <typename U>
    class TreeNode_t
    {
    public:
        TreeNode_t<U>*    prev;
        TreeNode_t<U>*    next;
        TreeNode_t<U>*    parent;
        TreeNode_t<U>*    children;
    //...
</code>```

Body:
I am trying to develop a generic tree template class, basically, representing a hierarchy of identical nodes. It takes 2 template arguments, the first one is a data, and the second - a type which would reference another node (prev,next,parent,child). By default, I want it to be a conventional pointer to the node, but for my purpose I also need it to be something different (e.g an integer index into the memory pool). The code below does not compile. Instinctively, I feel it can be done, but I don't know how. Could anyone provide an insight into this?

template <typename U, typename TPTR = TreeNode_t*>
class TreeNode_t
{
public:
    TPTR    prev;
    TPTR    next;
    TPTR    parent;
    TPTR    children;
    U m;
public:
    TreeNode_t() : prev(0), next(0), parent(0){}
    ~TreeNode_t(){}
    U &data() { return m; }
    const U &data() const { return m; }
    ...

To be specific, in general I instantiate it like this:

TreeNode_t<double> tree1;

But, sometimes I would like it this way:

TreeNode_t<double, unsigned> tree2;

Body:
You don't need two type parameters as the pointer can be deduced from the base type. Of course TreeNode_t is not defined before the template thus it doesn't compile.

template <typename U>
    class TreeNode_t
    {
    public:
        TreeNode_t<U>*    prev;
        TreeNode_t<U>*    next;
        TreeNode_t<U>*    parent;
        TreeNode_t<U>*    children;
    //...


问:
Comparing file names
I want to compare file lying in two different folders.
I wish to compare only files which have same name in those two different folders.

What I wish to do is to compare two different versions of a software and find how many files have been changed.

答:
I have this code which compares all the files in the directory with a particular file to check if that files aleady exists in the directory,may tweak that a little as per your needs.It uses commons-io.jar </p>

```<code>import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.io.FileUtils;

public class CompareFile {

    String directory;
    File file;

    public CompareFile(String directory, File file) {
        this.directory = directory;
        this.file = file;
    }

    public boolean doesFileExist() {

        boolean indicatorFileExist = true;
        List<File> files = null;

        try {
            files = getFiles();
            files = files.stream().filter(fileMatch -> {
                try {
                    if(fileMatch.isFile()){
                        return FileUtils.contentEquals(fileMatch, file);
                    }else{
                        return false;
                    }

                } catch (Exception excep) {
                    excep.printStackTrace();
                    return false;
                }
            }).collect(Collectors.toList());

            if(files.isEmpty()){
                indicatorFileExist = false;
            }

        } catch (Exception excep) {
            excep.printStackTrace();
        } finally {
            if (files != null) {
                files = null;
            }
        }

        return indicatorFileExist;

    }

    private List<File> getFiles() {

        List<File> fileList = null;

        try {

            if(directory!=null && directory.trim().length()>0 && file!=null){

                File dir = new File(directory);
                if(dir.isDirectory() && dir.exists() && dir.canRead()){
                    fileList = Arrays.asList(dir.listFiles());
                }

            }

        } catch (Exception excep) {
            excep.printStackTrace();
        }
        return fileList;
    }

}
</code>```

Title: Comparing file names

Body:
I have this code which compares all the files in the directory with a particular file to check if that files aleady exists in the directory,may tweak that a little as per your needs.It uses commons-io.jar

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.io.FileUtils;

public class CompareFile {

    String directory;
    File file;

    public CompareFile(String directory, File file) {
        this.directory = directory;
        this.file = file;
    }

    public boolean doesFileExist() {

        boolean indicatorFileExist = true;
        List<File> files = null;

        try {
            files = getFiles();
            files = files.stream().filter(fileMatch -> {
                try {
                    if(fileMatch.isFile()){
                        return FileUtils.contentEquals(fileMatch, file);
                    }else{
                        return false;
                    }

                } catch (Exception excep) {
                    excep.printStackTrace();
                    return false;
                }
            }).collect(Collectors.toList());

            if(files.isEmpty()){
                indicatorFileExist = false;
            }

        } catch (Exception excep) {
            excep.printStackTrace();
        } finally {
            if (files != null) {
                files = null;
            }
        }

        return indicatorFileExist;

    }

    private List<File> getFiles() {

        List<File> fileList = null;

        try {

            if(directory!=null && directory.trim().length()>0 && file!=null){

                File dir = new File(directory);
                if(dir.isDirectory() && dir.exists() && dir.canRead()){
                    fileList = Arrays.asList(dir.listFiles());
                }

            }

        } catch (Exception excep) {
            excep.printStackTrace();
        }
        return fileList;
    }

}


问:
How can I use gcloud auth?
I am trying to follow the tutorial of python with google cloud sql.

When I run: ./cloud_sql_proxy -instances="My-connection-name"=tcp:3306, I get google: could not find default credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information..

Also, when I run: gcloud auth application-default login, I get www.googleapis.com%2Fauth%2Fcloud-platform&access_type=offline" doesn’t understand the “open location” message. (-1708)

I followed downloaded the json file for the credintials and set the enviromnet virable GOOGLE_APPLICATION_CREDENTIALS to link to the json file, but I still get the same error.

答:
TL;DR - You can ignore the doesn’t understand the “open location” message. (-1708) error. You should see a browser window/tab opening with the URL, if not you can follow the steps I've added below where you can manually copy-paste the URL in the browser and you should not be seeing any warnings/errors.

You will need to authorize gcloud (one-time step) to use your account credentials for Google Cloud API calls.

Run gcloud auth application-default login --no-launch-browser

You will be provided a URL. Open the URL in the browser, authorize the application using your Google account and you will be provided a verification code in the page.

Copy the verification code and paste it back in the terminal where you ran the gcloud command in Step 1.

Now gcloud as well as any Google Cloud Client libraries you use can make use of the Application Default Credentials from that machine.

Title: How can I use gcloud auth?