问:
OpenShift REST API for scaling, invalid character 's' looking for beginning of value
I'm trying to scale out my deployments using openshift rest api, but I'm encountering the error "invalid character 's' looking for beginning of value".
I can successfully get the deployment config details but it's the patch request which is troubling me.
From the documents I have tried Content-Type as below 3 but nothing works:

application/json-patch+json

application/merge-patch+json

application/strategic-merge-patch+json

Here's my code:

```<code>data = {'spec':{'replicas':2}}
headers = {"Authorization": token, "Content-Type": "application/json-patch+json"}
def updateReplicas():
   url = root + "namespaces" + namespace + "deploymentconfigs" + dc + "scale"
   resp = requests.patch(url, headers=headers, data=data, verify=False)
   print(resp.content)
</code>```

Thank you.

答:
Ok, I found out the issue. Silly thing first, data should be inside single quotes data = '{'spec':{'replicas':2}}'.

Then, we need few more info in our data, which finally looks like :

data = '{"kind":"Scale","apiVersion":"extensions/v1beta1","metadata":{"name":"deployment_name","namespace":"namespace_name"},"spec":{"replicas":1}}'

Thank you for your time.

Body:
I'm trying to scale out my deployments using openshift rest api, but I'm encountering the error "invalid character 's' looking for beginning of value".
I can successfully get the deployment config details but it's the patch request which is troubling me.
From the documents I have tried Content-Type as below 3 but nothing works:

application/json-patch+json

application/merge-patch+json

application/strategic-merge-patch+json

Here's my code:

data = {'spec':{'replicas':2}}
headers = {"Authorization": token, "Content-Type": "application/json-patch+json"}
def updateReplicas():
   url = root + "namespaces" + namespace + "deploymentconfigs" + dc + "scale"
   resp = requests.patch(url, headers=headers, data=data, verify=False)
   print(resp.content)

Thank you.


来源: stackexchange

问:
How to use node.js code inside php file/script
I am very new in node.js, I am creating a bitcoin application in php and I need to use Bitgo API for creating wallet address and bitcoin transfer.

Bitgo have there API in node.js only. Please help me to call node.js API inside my php code.

Here is the API listed.

https://www.bitgo.com/api/?javascript#create-address

On user signup I need to execute the Bitgo API for creating addresses inside wallet. Bitgo returns the wallet address in response and I have to store in my database.

Thanks in advance!

答:
The BitGo Express REST API is a lightweight service for developers that want to take advantage of BitGo but are developing in a language without a native BitGo SDK.

BitGo Express runs as a service in your own datacenter, and handles the client-side operations involving your own keys, such as partially signing transactions before submitting them to BitGo. This ensures your keys never leave your network, and are never seen by BitGo. BitGo Express can also proxy the standard BitGo REST APIs, providing a unified interface to BitGo through a single REST API.

To use BitGo Express:

Install BitGoJS
Run the following command in the bin directory:
./bitgo-express --debug --port 3080 --env test --bind localhost

Make all BitGo REST API calls to the machine on which bitgo-express is running.

ContentLicense: CC BY-SA 3.0


问:
Python to transform rows to columns with delimeter, data contain *** need to delimit according to that
```<code>**START
IB    1107518415
BI    Paperback
BC    JHBC
CO    United Kingdom
ED    Alvarez, R. Michael
**
IB   0415836662
BI   Paperback
AU   Pituch, Keenan A.
AU    Stevens, James P.
BC   JHBC
CO   United Kingdom
EI    6 Rev ed
</code>```

Please find above sample data, i need under IB->"1107518415" as first row and "0415836662" as second row and so on, please help me.

答:
You could use a regex (with txt having your example string):

```<code>>>> import re
>>> re.findall(r'^\*\*.*\s+IB\s+(\d+)', txt, re.M)
['1107518415', '0415836662']
</code>```

Explanation of regex

Update based on comment:

If you want all the fields, say in a dict, you can still use a regex and a loop:

```<code>fl=[]
for m in re.finditer(r'^\*\*.*\s+([\s\S]+?)(?=^\*\*|\Z)', txt, re.M):
    di={}
    for s in m.group(1).splitlines():
        k,v=re.split(r'\s+', s, maxsplit=1)
        di[k]=v
    fl.append(di)
>>> fl
[{'ED': 'Alvarez, R. Michael', 'IB': '1107518415', 'CO': 'United Kingdom', 'BI': 'Paperback', 'BC': 'JHBC'}, {'EI': '6 Rev ed', 'BC': 'JHBC', 'BI': 'Paperback', 'AU': 'Stevens, James P.', 'CO': 'United Kingdom', 'IB': '0415836662'}]
</code>```

Or, you can use a single compression:

```<code>>>> [{k:v for k, v in [re.split(r'\s+', s, maxsplit=1) for s in sl]}
... for sl in
... [e.splitlines() for e in re.findall(r'^\*\*.*\s+([\s\S]+?)(?=^\*\*|\Z)', txt, re.M)]]
[{'ED': 'Alvarez, R. Michael', 'IB': '1107518415', 'CO': 'United Kingdom', 'BI': 'Paperback', 'BC': 'JHBC'}, {'EI': '6 Rev ed', 'BC': 'JHBC', 'BI': 'Paperback', 'AU': 'Stevens, James P.', 'CO': 'United Kingdom', 'IB': '0415836662'}]
</code>```

Body:
**START
IB    1107518415
BI    Paperback
BC    JHBC
CO    United Kingdom
ED    Alvarez, R. Michael
**
IB   0415836662
BI   Paperback
AU   Pituch, Keenan A.
AU    Stevens, James P.
BC   JHBC
CO   United Kingdom
EI    6 Rev ed

Please find above sample data, i need under IB->"1107518415" as first row and "0415836662" as second row and so on, please help me.

Body:
You could use a regex (with txt having your example string):

>>> import re
>>> re.findall(r'^\*\*.*\s+IB\s+(\d+)', txt, re.M)
['1107518415', '0415836662']

Explanation of regex

Update based on comment:

If you want all the fields, say in a dict, you can still use a regex and a loop:

fl=[]
for m in re.finditer(r'^\*\*.*\s+([\s\S]+?)(?=^\*\*|\Z)', txt, re.M):
    di={}
    for s in m.group(1).splitlines():
        k,v=re.split(r'\s+', s, maxsplit=1)
        di[k]=v
    fl.append(di)
>>> fl
[{'ED': 'Alvarez, R. Michael', 'IB': '1107518415', 'CO': 'United Kingdom', 'BI': 'Paperback', 'BC': 'JHBC'}, {'EI': '6 Rev ed', 'BC': 'JHBC', 'BI': 'Paperback', 'AU': 'Stevens, James P.', 'CO': 'United Kingdom', 'IB': '0415836662'}]

Or, you can use a single compression:

>>> [{k:v for k, v in [re.split(r'\s+', s, maxsplit=1) for s in sl]}
... for sl in
... [e.splitlines() for e in re.findall(r'^\*\*.*\s+([\s\S]+?)(?=^\*\*|\Z)', txt, re.M)]]
[{'ED': 'Alvarez, R. Michael', 'IB': '1107518415', 'CO': 'United Kingdom', 'BI': 'Paperback', 'BC': 'JHBC'}, {'EI': '6 Rev ed', 'BC': 'JHBC', 'BI': 'Paperback', 'AU': 'Stevens, James P.', 'CO': 'United Kingdom', 'IB': '0415836662'}]


问:
gradient-background buttons with bootstrap 4
I read the documentation, and there is a flag for enabling gradients on certain components: So maybe I am just stupid, but I don't see how this flag ($enable-gradients: true;) is supposed to do anything at all, I can find only a single reference to it in Bootstraps SASS files (.scss).

So how do i get some nice looking gradients in Bootstrap 4 without having to change all the classes like .btn-info? The presence of this flag seems to indicate that there is an elegant solution - if so I am just unable to find it..

Or maybe this variable was just created "in preparation" for themes, so they can build on top of it?

答:
To answer my own question, it seems like the properties where just not used in beta1.

They are used in beta2 though, see:
https://blog.getbootstrap.com/2017/10/19/bootstrap-4-beta-2/


问:
isset($_POST['submit'] not set after submitting my form
I'm new to php and I'm trying to register a user to a database using a form.

This is the code for the form (using the bootstrap framework):

```<code><form class="form-horizontal" role="form" method="POST" action="connectivity-reserve.php">
                <div class="form-group">
                    <label class="col-sm-2 control-label">Customer's name</label>
                    <div class="col-sm-6">
                        <div class="input-group">
                        <input type="text" class="form-control" id="Customername" name="Customername" placeholder="Customer name">
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-sm-2 control-label">Password</label>
                    <div class="col-sm-6">
                        <div class="input-group">
                        <input type="password" class="form-control" id="pwd" name="pwd" placeholder="Password">
                        </div>
                    </div>
                </div>

                </div>
                 <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                    <button type="submit" name ="submit" class="btn btn-primary">Reserve</button>
                    <button type="button" class="btn btn-default btn-sm"
                   data-dismiss="modal">Cancel</button>
                    </div>
                </div>
                <div class="form-group">
                <div class="alert alert-warning alert-dismissible" role="alert">
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">×</span>
                    </button>
                    <strong>Warning:</strong>: Please <a href="tel:+85212345678" class="alert-link">
                    call</a> us to reserve for more than six guests.
                </div>
                </div>
            </form>
</code>```

Here is the file (mysqli_connect.php) for connecting to the database. This is working:

```<code><?php
// This provides the information for accessing the database.
// It also creates a connection to MySQL,
// It selects the database, and sets the encoding.
// Set the database access information as constants:
DEFINE ('DB_USER', 'xxxx');
DEFINE ('DB_PASSWORD', 'xxxx');
DEFINE ('DB_HOST', 'xxxx');
DEFINE ('DB_NAME', 'xxxx');
// Make the connection:
$dbcon = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );
// Set the encoding...
mysqli_set_charset($dbcon, 'utf8');
</code>```

The file connectivity-reserve.php is what I'm using to add the user into the database.
Here is the code:

```<code><?php
require ('mysqli_connect.php');

echo "yay";

if(isset($_POST['submit']))
{

$Customername = $_POST['Customername'];
$pwd  = $_POST['pwd'];
$q = "INSERT INTO users (user_id, cname, psword, ) VALUES (' ', '$Customername', '$pwd')";

 $result = @mysqli_query ($dbcon, $q);

 if($result)
    {
        echo "YOUR REGISTRATION IS COMPLETED...";
    }
    else
    {
        echo "nah";
    }
}

?>
</code>```

I'm able to connect to the database since the code echo "yay" is displayed on the browser. The issue is with the if(isset($_POST['submit'])) condition. I thought it should work since my button's type and name are 'submit' on the form:

```<code><button type="submit" name ="submit" class="btn btn-primary">Reserve</button>
</code>```

Help will be greatly appreciated.

Edit: Thanks guys! It was the , after psword. Also I know the code isn't secure. I'm just starting out with php so that isn't really a priority for me right now.

答:
Replace

<button type="submit" name ="submit" class="btn btn-primary">Reserve</button>

By

```<code><input type="submit" name ="submit" class="btn btn-primary" value="Reserve">
</code>```

Error in query

```<code>$q = "INSERT INTO users (user_id, cname, psword, ) VALUES (' ', '$Customername', '$pwd')";
</code>```

comma after psword

Body:
I'm new to php and I'm trying to register a user to a database using a form.

This is the code for the form (using the bootstrap framework):

<form class="form-horizontal" role="form" method="POST" action="connectivity-reserve.php">

                    Customer's name

                        <input type="text" class="form-control" id="Customername" name="Customername" placeholder="Customer name">

                    Password

                        <input type="password" class="form-control" id="pwd" name="pwd" placeholder="Password">

                    <button type="submit" name ="submit" class="btn btn-primary">Reserve</button>
                    <button type="button" class="btn btn-default btn-sm"
                   data-dismiss="modal">Cancel</button>

                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    ×
                    </button>
                    Warning:: Please
                    call us to reserve for more than six guests.

            </form>

Here is the file (mysqli_connect.php) for connecting to the database. This is working:

<?php
// This provides the information for accessing the database.
// It also creates a connection to MySQL,
// It selects the database, and sets the encoding.
// Set the database access information as constants:
DEFINE ('DB_USER', 'xxxx');
DEFINE ('DB_PASSWORD', 'xxxx');
DEFINE ('DB_HOST', 'xxxx');
DEFINE ('DB_NAME', 'xxxx');
// Make the connection:
$dbcon = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );
// Set the encoding...
mysqli_set_charset($dbcon, 'utf8');

The file connectivity-reserve.php is what I'm using to add the user into the database.
Here is the code:

<?php
require ('mysqli_connect.php');

echo "yay";

if(isset($_POST['submit']))
{

$Customername = $_POST['Customername'];
$pwd  = $_POST['pwd'];
$q = "INSERT INTO users (user_id, cname, psword, ) VALUES (' ', '$Customername', '$pwd')";

 $result = @mysqli_query ($dbcon, $q);

 if($result)
    {
        echo "YOUR REGISTRATION IS COMPLETED...";
    }
    else
    {
        echo "nah";
    }
}

?>

I'm able to connect to the database since the code echo "yay" is displayed on the browser. The issue is with the if(isset($_POST['submit'])) condition. I thought it should work since my button's type and name are 'submit' on the form:

<button type="submit" name ="submit" class="btn btn-primary">Reserve</button>

Help will be greatly appreciated.

Edit: Thanks guys! It was the , after psword. Also I know the code isn't secure. I'm just starting out with php so that isn't really a priority for me right now.

Body:
Replace

<button type="submit" name ="submit" class="btn btn-primary">Reserve</button>

By

<input type="submit" name ="submit" class="btn btn-primary" value="Reserve">

Error in query

$q = "INSERT INTO users (user_id, cname, psword, ) VALUES (' ', '$Customername', '$pwd')";

comma after psword


问:
Adding animation to my images with JQuery
Here is my home page:

```<code><%@ Page Language="C#" MasterPageFile="~/Views/Home/Home.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content2" ContentPlaceHolderID="IndicationContentPlaceHolder" runat="server">
<table id="home" style="margin-left: auto; margin-right:auto;">
    <td id="homeLinks">
        <div style="padding-left:35px;" id="homeListing" class="containerMid">
            <div id="homeView">
                <table style="margin-left: auto; margin-right:auto;">
                    <tr>
                        <tr>
                            <td id="btnIcOld" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Load.png")%>" />
                            </td>
                            <td id="btnIc" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Bar_Chart.png")%>" />
                            </td>
                            <td id="btnPricing" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Pie_Chart_disabled.png")%>" />
                            </td>
                            <td id="btnSheets" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Line_Chart_disabled.png")%>" />
                            </td>
                            <td id="btnPort" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Modify_disabled.png")%>" />
                            </td>
                            <td id="btnAdmin" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Profile_disabled.png")%>" />
                            </td>
                        </tr>
                        <tr>
                            <td id="Td1">
                                <b>Indications Calculator | </b>
                            </td>
                            <td id="lblIc">
                                <b>Indications Calculator - Beta | </b>
                            </td>
                            <td id="lblPricing">
                                <b>Managing Pricing Triggers | </b>
                            </td>
                            <td id="lblSheets">
                                <b>Creating Pricing Sheets | </b>
                            </td>
                            <td id="lblPort">
                                <b>Portfolio Analysis | </b>
                            </td>
                            <td id="lblAdmin">
                                <b>Administration</b>
                            </td>
                        </tr>
                    </tr>
                </table>
            </div>
        </div>
    </td>
</table>

<div id="pageMessage"></div>

<script>
    $(document).ready(function () {

        $('#btnIc').live('click', function () {
            window.location.href = "<%=Url.Action("Indications") %>";
        });

        $('#btnIcOld').live('click', function () {
            window.location.href = 'https://extranetint/swap';
        });

        $('#btnPricing').live('click', function () {
            //window.location.href = "<%=Url.Action("Triggers") %>";
        });

        $('#btnSheets').live('click', function () {
            //window.location.href = "<%=Url.Action("Sheets") %>";
        });

        $('#btnPort').live('click', function () {
            //window.location.href = "<%=Url.Action("Analysis") %>";
        });

        $('#btnAdmin').live('click', function () {
            //window.location.href = "<%=Url.Action("Admin") %>";
        });

    });
</script>
</asp:Content>
</code>```

How can I, with JQuery (or really anything), achieve a mouse-over effect on my images where they will grow a little bit as you hover over them? I tried using JQuery animate but for some reason I couldn't get it to work.

Thanks!

答: Just add a class="btnIc" attribute to your image(s) and your jQuery example will work.

ContentLicense: CC BY-SA 2.5

Body:
Here is my home page:

<%@ Page Language="C#" MasterPageFile="~/Views/Home/Home.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content2" ContentPlaceHolderID="IndicationContentPlaceHolder" runat="server">

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Load.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Bar_Chart.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Pie_Chart_disabled.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Line_Chart_disabled.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Modify_disabled.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Profile_disabled.png")%>" />

                                Indications Calculator |

                                Indications Calculator - Beta |

                                Managing Pricing Triggers |

                                Creating Pricing Sheets |

                                Portfolio Analysis |

                                Administration

</asp:Content>

How can I, with JQuery (or really anything), achieve a mouse-over effect on my images where they will grow a little bit as you hover over them? I tried using JQuery animate but for some reason I couldn't get it to work.

Thanks!


问:
Getting "Duplicate Interface Definition" error, definitely has to #import ing header files
I'm helping on an iOS project with lots of methods and definitions common to many different classes in the AppDelegate. So, in each of those classes, in the .h file, I use #import "AppDelegate.h". This works fine until I need access to one of those classes that already imports the AppDelegate into another class that imports AppDelegate. At this point, I get a Duplicate Interface Definition error for AppDelegate.

Ok, so that seems fair. I'm already importing AppDelegate into a file that I'm importing, so AppDelegate is getting imported from two different places. So I remove the AppDelegate line, and everything is fine.

But what happens when I need to import two classes that both need to import AppDelegate?

I have a very specific problem that I'm trying to wrap my head around, and I know it is being caused by something that has to do with this, but I'm not sure what. So I'm hoping if I figure out how I'm supposed to be handling this sort of importing, and sort everything else out, and hope that this solves my problem. So to put this in more concrete terms:

I have ClassA.h, ClassB.h, and ClassC.h. All have #import "AppDelegate.h". When I need to use #import "ClassB.h" in ClassA, I remove the #import "AppDelegate.h" line from ClassA. Everything works smoothly. But what happens if I also need to #import "ClassC.h" into ClassA, and but ClassB and ClassC NEED to have the #import "AppDelegate.h"?

EDIT:

I tried the exact scenario I described above in a clean project, and it built fine, so there is something else at play. But what I can say with certainty is that when this issue came up previously with this project, it was a duplicate interface definition of AppDelegate, and when I removed the #import "AppDelegate.h" line, the error went away, and I still had access to the AppDelegate.h methods and enums through other imported files.

答: For me, I forgot to include parenthesis in interface definition in m file.</p>


问:
Is it possible to receive an SMS from Android emulator?
I was wondering if there is a way to receive an SMS from Android emulator, perhaps on a TCP port.
I know it's possible to send SMS to emulator by opening a TCP socket on the emulator port and using "send sms" command, but is it also possible to receive an SMS this way?

I'll elaborate - I have a java application running on a Tomcat server. I also have an Android emulator running on the same machine. I can send SMS messages from the application to the emulator using the "sms send" command. Can I also receive SMS messages in some way?

答:
Start two emulators, first will be 5554, second will be 5556. Send a text message using the built in messaging app from 5554 to 5556 by typing '5556' as the telephone number.

(You will need to have created two different AVDs first, so that you can use one for 5554 and the other for 5556)


问:
Find polygon containing point from lat/lng table
I have a table, Regions:

```<code>| id | name     |
|----|----------|
| 1  | Jersey   |
| 2  | Scotland |
...
</code>```

and a table of RegionPoints (which define the bounding box for each region):

```<code>| id | regionid | lat   | lng   |
|----|----------|-------|-------|
| 1  | 1        | 49.27 | -2.27 |
| 2  | 1        | 49.27 | -1.99 |
| 3  | 1        | 49.15 | -2.27 |
| 4  | 1        | 49.15 | -1.99 |
...
</code>```

Given a latitude and longitude, I want to find the regions which contain the given point.

From my understanding, I need to aggregate by regionid, then
use ST_ConcaveHull, followed by ST_Contains using the latitude and longitude to query for, however my concern is that with a large number of regions, computing a concave hull for each will be very inefficient.

This is my first time using PostGIS, so a bit stuck.

答:
Yes, computing the concave hull "on the fly" can be inefficient with lots of data.

Also, you won't be able to use a spatial index, as your geometries are built at query time.

Using ST_MakeEnvelope instead of ST_ConcaveHull will mitigate the problem.

However, as JGH suggests, you should store those coordinates as polygons in the Regions table, using ST_MakeEnvelope to create them.

Than build a spatial index and use ST_Contains to get the regions that contains a point.

Body:
I have a table, Regions:

| id | name     |
|----|----------|
| 1  | Jersey   |
| 2  | Scotland |
...

and a table of RegionPoints (which define the bounding box for each region):

| id | regionid | lat   | lng   |
|----|----------|-------|-------|
| 1  | 1        | 49.27 | -2.27 |
| 2  | 1        | 49.27 | -1.99 |
| 3  | 1        | 49.15 | -2.27 |
| 4  | 1        | 49.15 | -1.99 |
...

Given a latitude and longitude, I want to find the regions which contain the given point.

From my understanding, I need to aggregate by regionid, then
use ST_ConcaveHull, followed by ST_Contains using the latitude and longitude to query for, however my concern is that with a large number of regions, computing a concave hull for each will be very inefficient.

This is my first time using PostGIS, so a bit stuck.


问:
C++ comparing Char to Strings
I'm trying to loop through a word but only vowels are working for some reason. The other type prints out the amount of words in total. Please excuse my poor choise of words mixed with Swedish and English.</p>

```<code>#include <iostream>

using namespace std;

int main()
{
    int vo = 0;
    int ko = 0;

    char vocals[7]
    {
        'A','O','U','E','I','Y'
    };

    char konsonanter[19]
    {
        'B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','V','X','Z'
    };

    string word = "Toysoldier";

    for(int i = 0; i < word.length(); i++)
    {
        for(int v = 0; v < vocals[v]; v++)
        {
            if(vocals[v] == word[i])
                vo++;
        }

        for(int k = 0; k < konsonanter[k]; k++)
        {
            if(konsonanter[k] == word[i])
                ko++;
        }
    }

    cout << "Konsonanter = " << ko << " Vokaler = " << vo << endl;
}
</code>```

答:
You conditions in the loops are flawed, you should use 'for (int v = 0; v < sizeof(vocals); v++)`.

Also, check your condition for a vocal and consonant: What happens if you consider lowercase chars? 'a' != 'A', so you don't count them correctly.
Hint: Use toupper() or tolower() so you don't need to have excessive lists of chars.

Title: C++ comparing Char to Strings

Body:
I'm trying to loop through a word but only vowels are working for some reason. The other type prints out the amount of words in total. Please excuse my poor choise of words mixed with Swedish and English.

#include <iostream>

using namespace std;

int main()
{
    int vo = 0;
    int ko = 0;

    char vocals[7]
    {
        'A','O','U','E','I','Y'
    };

    char konsonanter[19]
    {
        'B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','V','X','Z'
    };

    string word = "Toysoldier";

    for(int i = 0; i < word.length(); i++)
    {
        for(int v = 0; v < vocals[v]; v++)
        {
            if(vocals[v] == word[i])
                vo++;
        }

        for(int k = 0; k < konsonanter[k]; k++)
        {
            if(konsonanter[k] == word[i])
                ko++;
        }
    }

    cout << "Konsonanter = " << ko << " Vokaler = " << vo << endl;
}


问:
php pagination with action buttons
I have following PHP page which queries MYSQL TABLE and displays the result.

```<code>    <?php
    $host="localhost";
    $username="root";
    $password="PASSWORD"; // Mysql password
    $db_name="syslog"; // Database name
    $tbl_name="logs"; // Table name
    // Connect to server and select databse
    mysql_connect("$host", "$username", "$password")or die("cannot connect");
    mysql_select_db("$db_name")or die("cannot select DB");
    //$sql="SELECT * FROM $tbl_name ORDER BY `LOGS` datetime LIMIT 0 , 10";
    $sql = "SELECT * FROM `logs`\n"
        . "ORDER BY `logs`.`datetime` DESC LIMIT 0, 50 ";
    $result=mysql_query($sql);
    // Define $host_column=1
    echo '<table width="1400" border="1" align="left" cellpadding="1" cellspacing="1">';
    echo '<tr><th>ID</th><th>Host</th><th>Date</th><th>Info</th><th>Type</th><th>Messgae</th></tr>';
    while($rows=mysql_fetch_array($result)){
    //$host_column assign here from result
    $host_column=$rows['host'];
// show alternate colors based on colum result
    $priority_column=$rows['priority'];
    if($priority_column=='err'){
    echo "<tr bgcolor='#FFA07A'><td>".$rows['seq']."</td><td>".$rows['host']."</td><td>".$rows['datetime']."</td><td>".$rows['priority']."</td><td>".$rows['program']."</td><td>".$rows['msg']."</td></tr>";
    }else if($host_column=='10.0.0.1'){
    echo "<tr bgcolor='#bbbbbb'><td>".$rows['seq']."</td><td>".$rows['host']."</td><td>".$rows['datetime']."</td><td>".$rows['priority']."</td><td>".$rows['program']."</td><td>".$rows['msg']."</td></tr>";
    }else if($host_column=='10.0.0.2'){
    echo "<tr bgcolor='#cccccc'><td>".$rows['seq']."</td><td>".$rows['host']."</td><td>".$rows['datetime']."</td><td>".$rows['priority']."</td><td>".$rows['program']."</td><td>".$rows['msg']."</td></tr>";
    }
    }
    echo '</table>';
    mysql_close();
    ?>
</code>```

The results are in thousands, therefore I wanted to have per page result with next page option including how many pages are there , next previous. Also I would like to have an action button on each row , like DELETE , EDIT and when I click on it, it should perform an action of my choice like goto another php with action delete/edit this entry number. I done pagination with simple page, but integrating part is where I am failing plus adding action buttons (or text)

答:
Consider doing the pagination on the SQL side, by passing pageIndex and pageRecordCount.

... LIMIT {pageIndex * pageRecordCount}, {pageRecordCount}

Title: php pagination with action buttons

Body:
I have following PHP page which queries MYSQL TABLE and displays the result.

    <?php
    $host="localhost";
    $username="root";
    $password="PASSWORD"; // Mysql password
    $db_name="syslog"; // Database name
    $tbl_name="logs"; // Table name
    // Connect to server and select databse
    mysql_connect("$host", "$username", "$password")or die("cannot connect");
    mysql_select_db("$db_name")or die("cannot select DB");
    //$sql="SELECT * FROM $tbl_name ORDER BY `LOGS` datetime LIMIT 0 , 10";
    $sql = "SELECT * FROM `logs`\n"
        . "ORDER BY `logs`.`datetime` DESC LIMIT 0, 50 ";
    $result=mysql_query($sql);
    // Define $host_column=1
    echo '
';
    echo '
ID	Host	Date	Info	Type	Messgae
';
    while($rows=mysql_fetch_array($result)){
    //$host_column assign here from result
    $host_column=$rows['host'];
// show alternate colors based on colum result
    $priority_column=$rows['priority'];
    if($priority_column=='err'){
    echo "
".$rows['seq']."	".$rows['host']."	".$rows['datetime']."	".$rows['priority']."	".$rows['program']."	".$rows['msg']."
";
    }else if($host_column=='10.0.0.1'){
    echo "
".$rows['seq']."	".$rows['host']."	".$rows['datetime']."	".$rows['priority']."	".$rows['program']."	".$rows['msg']."
";
    }else if($host_column=='10.0.0.2'){
    echo "
".$rows['seq']."	".$rows['host']."	".$rows['datetime']."	".$rows['priority']."	".$rows['program']."	".$rows['msg']."
";
    }
    }
    echo '
';
    mysql_close();
    ?>

The results are in thousands, therefore I wanted to have per page result with next page option including how many pages are there , next previous. Also I would like to have an action button on each row , like DELETE , EDIT and when I click on it, it should perform an action of my choice like goto another php with action delete/edit this entry number. I done pagination with simple page, but integrating part is where I am failing plus adding action buttons (or text)


问:
Installing a new version of an ActiveX control in my web application
I've been tasked to update and install a new version of an old ActiveX control in our Aspx web application (joy!).  The actual updating is fairly straightforward, but the installing is giving me headaches. Here is what I tried:

In the VB6 editor, get the properties of the ActiveX project, and check off the "autoincrement" checkbox in the "Make" tab.

Set the version to 1.0.12

Create a new CAB with the Package&Deployment wizard.

Copy this CAB to my website.

Then in the Aspx itself, I update the version of the activeX as follows:

```<code>Me.Page.Header.Controls.Add(New LiteralControl(String.Format("<div style=DISPLAY:none'><object id='PrtLabel' codebase='{0}' classid='CLSID:AB61148E-D4B5-4D4B-8867-9E4CE8229B5E' viewastext></object></div>", "PrtLabel.CAB#version=1,0,0,12")))
</code>```

After this, I delete the prtlabel.dll and prtlabel.inf files from the "c:\windows\downloaded program files" folder.

Problem is, when I then visit the web page and it asks me to install the activeX, it doesn't actually do it (no error message appears though). When I go back to the "c:\windows\downloaded program files" folder, ONLY the prtlabel.inf file has been copied there, NOT the prtlabel.dll file.

Is there a special procedure to put a new version of an ActiveX control in your website?

Thanks

Sam

答:
Well, as always the devil is in the details.  Turned out that in the HTML markup you didn't need to only change the version, but also the classid... which could be found inside the new CAB file.</p>

```<code>Me.Page.Header.Controls.Add(New LiteralControl(String.Format("<div style=DISPLAY:none'><object id='PrtLabel' codebase='{0}' classid='**CLSID:AB61148E-D4B5-4D4B-8867-9E4CE8229B5E**' viewastext></object></div>", "PrtLabel.CAB#version=1,0,0,12")))
</code>```

Body:
I've been tasked to update and install a new version of an old ActiveX control in our Aspx web application (joy!).  The actual updating is fairly straightforward, but the installing is giving me headaches. Here is what I tried:

In the VB6 editor, get the properties of the ActiveX project, and check off the "autoincrement" checkbox in the "Make" tab.

Set the version to 1.0.12

Create a new CAB with the Package&Deployment wizard.

Copy this CAB to my website.

Then in the Aspx itself, I update the version of the activeX as follows:

Me.Page.Header.Controls.Add(New LiteralControl(String.Format("
<object id='PrtLabel' codebase='{0}' classid='CLSID:AB61148E-D4B5-4D4B-8867-9E4CE8229B5E' viewastext></object>
", "PrtLabel.CAB#version=1,0,0,12")))

After this, I delete the prtlabel.dll and prtlabel.inf files from the "c:\windows\downloaded program files" folder.

Problem is, when I then visit the web page and it asks me to install the activeX, it doesn't actually do it (no error message appears though). When I go back to the "c:\windows\downloaded program files" folder, ONLY the prtlabel.inf file has been copied there, NOT the prtlabel.dll file.

Is there a special procedure to put a new version of an ActiveX control in your website?

Thanks

Sam

Body:
Well, as always the devil is in the details.  Turned out that in the HTML markup you didn't need to only change the version, but also the classid... which could be found inside the new CAB file.

Me.Page.Header.Controls.Add(New LiteralControl(String.Format("<div style=DISPLAY:none'><object id='PrtLabel' codebase='{0}' classid='**CLSID:AB61148E-D4B5-4D4B-8867-9E4CE8229B5E**' viewastext></object></div>", "PrtLabel.CAB#version=1,0,0,12")))


问:
Error_Line() is not printing correct line number
I was trying to implement exception handling mechanism in one of my procedure. Its seems like when the sql statement is single line , error_line() in CATCH block return the correct line number but when its a big sql statement, it just does not print the actual line number.

If anyone has come across similar situation, could you please share your thoughts.

Thanks,
Shankar

答: The function ERROR_LINE() returns the first line number of SQL-statement which throw an exception. To get more information about the error you can use functions ERROR_MESSAGE() or ERROR_NUMBER() in current CATCH-block.


问:
How to find class name from inspected code
When I inspected my web page I got this code

```<code><li id="SR_R1_tab" class="t-Tabs-item a-Tabs-before a-Tabs-selected is-active" aria-controls="SR_R1" role="tab" aria-selected="true">
</code>```

It is an oracle apex tabular region's sub region. I want to perform some css modifications and javascript actions in this class(sub regions of tabular region). How to find the exact class from this inspected code?. Should I use the class 't-Tabs-item' or 't-Tabs-item a-Tabs-before a-Tabs-selected is-active' ?

答:
This element has 4 css classes:

t-Tabs-item

a-Tabs-before

a-Tabs-selected

is-active

In the debugger, you need to observe what each class does to your UI and you can decide which class to override.

Example: if you want to change the styling for each element, you will probably have to override t-Tabs-item:

```<code>.t-Tabs-item {
  background: red;
}
</code>```

But if you only want to change the appearance of the selected item, then you will  probably have to override a-Tabs-selected. In that case you should also add the more generic .t-Tabs-item class in order to avoid side effects.

```<code>.t-Tabs-item.a-Tabs-selected {
  background: green;
}
</code>```

Body:
When I inspected my web page I got this code

It is an oracle apex tabular region's sub region. I want to perform some css modifications and javascript actions in this class(sub regions of tabular region). How to find the exact class from this inspected code?. Should I use the class 't-Tabs-item' or 't-Tabs-item a-Tabs-before a-Tabs-selected is-active' ?

Body:
This element has 4 css classes:

t-Tabs-item

a-Tabs-before

a-Tabs-selected

is-active

In the debugger, you need to observe what each class does to your UI and you can decide which class to override.

Example: if you want to change the styling for each element, you will probably have to override t-Tabs-item:

.t-Tabs-item {
  background: red;
}

But if you only want to change the appearance of the selected item, then you will  probably have to override a-Tabs-selected. In that case you should also add the more generic .t-Tabs-item class in order to avoid side effects.

.t-Tabs-item.a-Tabs-selected {
  background: green;
}


问:
Android Studio - Enable VT-x in your bios setting
When ever I try to run an emulator I see this error
"Intel HAXM is required to run this avd
/dev/KVM is not found.
Enable VT-x in your BIOS security setting, ensure that your Linux distro has working KVM module'

I have already installed haxm through SDK successfully , Also I have enabled virtualization in the security tab. The thing that is confusing me now is why does it say Linux distro in the error message when I'm running windows 7 on a HAXM and VT supported PC?

答:
I too had the same problem. Today (13-11-17) I solved it.

These are the steps to solve the problem-

1)Go to Android Studio Preferences.

2)Appearance and Behavior --> System Settings --> Android SDK.

3)Copy the Android SDK location Path.

4)Go to the path.

5)In the path folder open "extras" folder then open "intel" then open "Hardware_Accelerated_Execution_Manager"

6)The double-click on IntelHAXM_[version number here].

7)The Re-Install IntelHAXM.

8) Open Emulator.

It should work fine.(It worked for me)


问:
Undefined property: GuzzleHttp\Exception\ConnectException::$status
I keep getting this error when trying to get the status of the request.

This is my code

```<code>ExpenseRepository.php

<?php

namespace Expensetrim\Api\v1\Repositories;

use Auth;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Expensetrim\Models\Company;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ExpenseRepository
{
    private $api_url;

    const API_GET = 'GET';
    const API_POST = 'POST';
    const API_PUT = 'PUT';

    function __construct()
    {
        $this->api_url = "http://xxx-xxx-xxx/api/v1/";
    }

    public function api_call($method, $uri, $request = NULL)
{
    try {

        $url=$this->api_url.$uri;
        $client = new Client(['base_uri' => $this->api_url]);
        $response = ($request) ? $client->request($method, $uri, $request) : $client->request($method, $uri);
    }
    catch (RequestException $e) {
        return $e;
    }
    return $this->formatResponseBody($response);
}

public static function formatResponseBody($response)
{
    $body = $response->getBody(true)->getContents();
    return json_decode($body);
}

public function addExpenseType($data)
{
    $uri = 'expense/types/add';
    $response = $this->api_call(self::API_POST, $uri, ['form_params' => $data]);
    return $response;

}
</code>```

Also CompanyRepository.php

```<code>public function addExpenseType($company_id, $data)
    {
        $data['company_id'] = $company_id;
        $expense = new ExpenseRepository;
        $done = $expense->addExpenseType($data);
        if($done->status == 'success') {
          return true;
        }

        return true;
    }
</code>```

I need to check if the status is a success or not but keep getting this error: Undefined property: GuzzleHttp\Exception\ConnectException::$status.
Please what am i doing wrong?

答:
Change your formatResponseBody function to add $response->getBody()->rewind();

```<code>public static function formatResponseBody($response)
{
    $response->getBody()->rewind();
    $body = $response->getBody(true)->getContents();
    return json_decode($body);
}
</code>```

In the old version of guzzle, it read the full body without resetting the pointer after. Using rewind() will reset the pointer. If this is the source of your issue rewind() will resolve this. It has aleady been resolved in newer versions.

Body:
I keep getting this error when trying to get the status of the request.

This is my code

ExpenseRepository.php

<?php

namespace Expensetrim\Api\v1\Repositories;

use Auth;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Expensetrim\Models\Company;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ExpenseRepository
{
    private $api_url;

    const API_GET = 'GET';
    const API_POST = 'POST';
    const API_PUT = 'PUT';

    function __construct()
    {
        $this->api_url = "http://xxx-xxx-xxx/api/v1/";
    }

    public function api_call($method, $uri, $request = NULL)
{
    try {

        $url=$this->api_url.$uri;
        $client = new Client(['base_uri' => $this->api_url]);
        $response = ($request) ? $client->request($method, $uri, $request) : $client->request($method, $uri);
    }
    catch (RequestException $e) {
        return $e;
    }
    return $this->formatResponseBody($response);
}

public static function formatResponseBody($response)
{
    $body = $response->getBody(true)->getContents();
    return json_decode($body);
}

public function addExpenseType($data)
{
    $uri = 'expense/types/add';
    $response = $this->api_call(self::API_POST, $uri, ['form_params' => $data]);
    return $response;

}

Also CompanyRepository.php

public function addExpenseType($company_id, $data)
    {
        $data['company_id'] = $company_id;
        $expense = new ExpenseRepository;
        $done = $expense->addExpenseType($data);
        if($done->status == 'success') {
          return true;
        }

        return true;
    }

I need to check if the status is a success or not but keep getting this error: Undefined property: GuzzleHttp\Exception\ConnectException::$status.
Please what am i doing wrong?

Body:
Change your formatResponseBody function to add $response->getBody()->rewind();

public static function formatResponseBody($response)
{
    $response->getBody()->rewind();
    $body = $response->getBody(true)->getContents();
    return json_decode($body);
}

In the old version of guzzle, it read the full body without resetting the pointer after. Using rewind() will reset the pointer. If this is the source of your issue rewind() will resolve this. It has aleady been resolved in newer versions.


问:
How can I split a string with occurrence of "users/" from a URL?
I Am using this method, this is my URL "https://www.youtube.com/user/myYoutubeChennal". and i want to get "myYoutubeChennal" from this.</p>

```<code>func splitVideoUrl(videoUrl:String) -> String {

    //let token = videoUrl.split(separator: "user/")
    let ttstr:String = " https://www.youtube.com/user/myYoutubeChennal"
    if let range = ttstr.range(of: "user/") {
        let firstPart = String(describing: ttstr.startIndex..<range.lowerBound)
        print(firstPart) // print Hello
        return firstPart
    }
    return ""
}
</code>```

答:
Assuming the desired string is always the path component after user split the string by slashes, get the index of user and then the item index + 1

```<code>let string = "https://www.youtube.com/user/myYoutubeChennal"
let components = string.components(separatedBy: "/")
if let index = components.index(of: "user"), index < components.count - 1 {
    let user = components[index + 1]
} else {
   print("user not found")
}
</code>```

Body:
I Am using this method, this is my URL "https://www.youtube.com/user/myYoutubeChennal". and i want to get "myYoutubeChennal" from this.

func splitVideoUrl(videoUrl:String) -> String {

    //let token = videoUrl.split(separator: "user/")
    let ttstr:String = " https://www.youtube.com/user/myYoutubeChennal"
    if let range = ttstr.range(of: "user/") {
        let firstPart = String(describing: ttstr.startIndex..<range.lowerBound)
        print(firstPart) // print Hello
        return firstPart
    }
    return ""
}

Body:
Assuming the desired string is always the path component after user split the string by slashes, get the index of user and then the item index + 1

let string = "https://www.youtube.com/user/myYoutubeChennal"
let components = string.components(separatedBy: "/")
if let index = components.index(of: "user"), index < components.count - 1 {
    let user = components[index + 1]
} else {
   print("user not found")
}


问:
Could not find the file and upload
I trying to do multiple image upload to the system but it won't able to found the images after upload.
When i try to var_dump the total number of item uploaded it keep showing 0 item uploaded.

Need some help here, Thank You.

This is my HTML code:

```<code><form id="login-form" action="" method="post" enctype="multipart/form-data" >
    <input type="file" name="file[]" multiple="multiple"  />
<input type="submit" name="submit-scam" value="Submit">
</form>
</code>```

This is my PHP code:

```<code><?php
//Check Error
error_reporting(E_ALL);
//Start Session
session_start();
//Include Database
include_once('dbConnect.php');

if (isset($_POST['submit-scam'])){
    echo "button clicked";

if(isset($_FILES['file'])){

            /*This Function is to loop multiple upload file into DB*/

    $total = count($_FILES['file']['name']);

    for ($i=0; $i<$total; $i++) {

    $file = rand(1000,100000)."-".$_FILES['file']['name'][$i];
    $file_loc = $_FILES['file']['tmp_name'][$i];
    $file_size = $_FILES['file']['size'][$i];
    $file_type = $_FILES['file']['type'][$i];
    $folder="uploads/";
    $today = date('Y-m-d');

    // new file size in KB
    $new_size = $file_size/1024;
    // new file size in KB

    // make file name in lower case
    $new_file_name = strtolower($file);
    // make file name in lower case

    $final_file=str_replace(' ','-',$new_file_name);

    if(move_uploaded_file($file_loc,$folder.$final_file))
    {

                    //To Insert Latest base to SQL Latest submit ec_claim id

                    $sql="INSERT INTO db_evidence(db_evidence_name,db_evidence_type,db_evidence_scam_id,db_evidence_users_id)
                    VALUES('$final_file','$file_type','1','1')";
                    $result = mysqli_query($connection, $sql) or die(mysqli_error($connection));
                    echo "success upload";
                    // header("Location:index.php");
                }
                else
                {
                    echo "failed to upload";
                }
                }
            } else {
                echo "error no file is found";
            }
}
?>
</code>```

答:
Add enctype="multipart/form-data" to the form

```<code><form id="login-form" action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file[]" multiple="multiple"  />
    <input type="submit" name="submit-scam" value="Submit">
</form>
</code>```

That should let you read from type="file"

Title: Could not find the file and upload

Body:
I trying to do multiple image upload to the system but it won't able to found the images after upload.
When i try to var_dump the total number of item uploaded it keep showing 0 item uploaded.

Need some help here, Thank You.

This is my HTML code:

<form id="login-form" action="" method="post" enctype="multipart/form-data" >
    <input type="file" name="file[]" multiple="multiple"  />
<input type="submit" name="submit-scam" value="Submit">
</form>

This is my PHP code:

<?php
//Check Error
error_reporting(E_ALL);
//Start Session
session_start();
//Include Database
include_once('dbConnect.php');

if (isset($_POST['submit-scam'])){
    echo "button clicked";

if(isset($_FILES['file'])){

            /*This Function is to loop multiple upload file into DB*/

    $total = count($_FILES['file']['name']);

    for ($i=0; $i<$total; $i++) {

    $file = rand(1000,100000)."-".$_FILES['file']['name'][$i];
    $file_loc = $_FILES['file']['tmp_name'][$i];
    $file_size = $_FILES['file']['size'][$i];
    $file_type = $_FILES['file']['type'][$i];
    $folder="uploads/";
    $today = date('Y-m-d');

    // new file size in KB
    $new_size = $file_size/1024;
    // new file size in KB

    // make file name in lower case
    $new_file_name = strtolower($file);
    // make file name in lower case

    $final_file=str_replace(' ','-',$new_file_name);

    if(move_uploaded_file($file_loc,$folder.$final_file))
    {

                    //To Insert Latest base to SQL Latest submit ec_claim id

                    $sql="INSERT INTO db_evidence(db_evidence_name,db_evidence_type,db_evidence_scam_id,db_evidence_users_id)
                    VALUES('$final_file','$file_type','1','1')";
                    $result = mysqli_query($connection, $sql) or die(mysqli_error($connection));
                    echo "success upload";
                    // header("Location:index.php");
                }
                else
                {
                    echo "failed to upload";
                }
                }
            } else {
                echo "error no file is found";
            }
}
?>

Body:
Add enctype="multipart/form-data" to the form

<form id="login-form" action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file[]" multiple="multiple"  />
    <input type="submit" name="submit-scam" value="Submit">
</form>

That should let you read from type="file"


问:
How to rotate text 90 degrees inline
How do I rotate text 90 degrees without using the style sheet? I have placed the following instruction in the header area of the page:

```<code><style>
div.rotate-text {
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
}
</style>
</code>```

Then I placed the following around the paragraph in question.

```<code><div id="rotate-text">
<p>My paragraph</p>
</div>
</code>```

But its not working and hence my question.

答:
you use of id in html code, so you must use of # in css.

Change:

```<code>div.rotate-text {
</code>```

To:

```<code>div#rotate-text {
</code>```

div#rotate-text {
  -webkit-transform: rotate(90deg);
  -moz-transform: rotate(90deg);
  -o-transform: rotate(90deg);
  -ms-transform: rotate(90deg);
  transform: rotate(90deg);
  width: 100px;
  transform-origin: top left;
  margin: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="rotate-text">
  <p>My paragraph</p>
</div></code>```

Title: How to rotate text 90 degrees inline

Body:
How do I rotate text 90 degrees without using the style sheet? I have placed the following instruction in the header area of the page:

Then I placed the following around the paragraph in question.

My paragraph

But its not working and hence my question.

Body:
you use of id in html code, so you must use of # in css.

Change:

div.rotate-text {

To:

div#rotate-text {

div#rotate-text {
  -webkit-transform: rotate(90deg);
  -moz-transform: rotate(90deg);
  -o-transform: rotate(90deg);
  -ms-transform: rotate(90deg);
  transform: rotate(90deg);
  width: 100px;
  transform-origin: top left;
  margin: 50px;
}

<div id="rotate-text">
  <p>My paragraph</p>
</div>


问:
Is there a name for this type of popular footer?
Screenshot of a footer:

I'm unsure if there is a particular name for that kind of footer or if it's a widget for a certain framework. That particular example was taken from buffalonews.com

After I know the name I can refine my searching for implementing it. Thank you for your input.

答:
I believe the name you're looking for is a Site Map Footer. This is common now-a-days to display the contents of the site to the user while also offering crawlers direct links to content pages.

The key here is to display pages that are relevant/important to the user without inundating them so many links they can't figure out where to go.


问:
Linux Script to check if process is running and restart if not
I am having this script which looks for the process filebeat and restarts it if is not running. Cron runs this script every 5 minutes. Most of the time this works fine except sometime it creates multiple filebeat process. Can someone please point out what is the issue in my script.

```<code>#!/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
service=filebeat
servicex=/usr/share/filebeat/bin/filebeat
pid=`pgrep -x "filebeat"`
if [ $pid > /dev/null ]
then
echo "$(date) $service is running!!!"
else
echo "$(date) starting $service"
cd /home/hpov/beats/filebeat
./filebeat -c filebeat.yml &
fi
</code>```

答:
```<code>#!/bin/bash
pidof  script.x86 >/dev/null
if [[ $? -ne 0 ]] ; then
        echo "Restarting script:     $(date)" >> /var/log/script.txt
        /etc/script/script.x86 &
fi
</code>```

Super easy :D

Body:
I am having this script which looks for the process filebeat and restarts it if is not running. Cron runs this script every 5 minutes. Most of the time this works fine except sometime it creates multiple filebeat process. Can someone please point out what is the issue in my script.

#!/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
service=filebeat
servicex=/usr/share/filebeat/bin/filebeat
pid=`pgrep -x "filebeat"`
if [ $pid > /dev/null ]
then
echo "$(date) $service is running!!!"
else
echo "$(date) starting $service"
cd /home/hpov/beats/filebeat
./filebeat -c filebeat.yml &
fi

Body:
#!/bin/bash
pidof  script.x86 >/dev/null
if [[ $? -ne 0 ]] ; then
        echo "Restarting script:     $(date)" >> /var/log/script.txt
        /etc/script/script.x86 &
fi

Super easy :D


问:
Make div expand outside of scrolling parent
I have a table with some cloumns that can be hovered over to show some items inside a div. This table is inside a container with max height and overflow: auto. The problem is that when I hover over a column, I want the items to expand outside the parent div aswell as position itself to the column that is hovered.

```<code>    <div class="table-container">
  <table>
    <tbody>
      <tr>
        <td>
          <div class="dropdown">
            <a class="dropbtn">Hover here</a>
            <div class="dropdown-content">
              <p>Item 1</p>
              <p>Item 2</p>
              <p>Item 3</p>
              <p>Item 4</p>
            </div>
          </div>
        </td>
         </tr>
...
</code>```

css:

```<code>.dropdown {
    position: static;
    display: inline-block;
}

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

.dropdown:hover .dropdown-content {
    display: block;
}

.table-container {
    margin-left: 20px;
    max-height: 50px;
    width: 150px;
    overflow: auto;
    box-shadow: 1px 1px 4px 0 rgba(0, 0, 0, 0.1), 0 2px 14px 0px rgba(0, 0, 0, 0.1);
}
</code>```

I have played around with the position property of the divs, but it seems I can only choose from either:

make the items expand outside parent, but the position is wrong
when the table is scrolled

make the items position itself to the column, but the items does not expand outside of parent.

Here is a fiddle of my problem: (try to scroll down and hover an item)
https://jsfiddle.net/wuj9fd5c/3/

Edit:
Updated fiddle to explain both cases

答:
I ended up writing some js code to set top and left for dropdown-content.

First I had to set the position for the parent to static:

```<code>.dropdown {
  position: static;
  display: inline-block;
}
</code>```

JS:

```<code>    $(document).on('mouseenter', '.dropbtn', function () {
    var $posTop = $(this).position().top;
    var $posLeft = $(this).position().left + 20;
    $(this).parent().children(".dropdown-content").css({ top: $posTop, left: $posLeft });
});
</code>```

Body:
I have a table with some cloumns that can be hovered over to show some items inside a div. This table is inside a container with max height and overflow: auto. The problem is that when I hover over a column, I want the items to expand outside the parent div aswell as position itself to the column that is hovered.

            Hover here

Item 1

Item 2

Item 3

Item 4

...

css:

.dropdown {
    position: static;
    display: inline-block;
}

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

.dropdown:hover .dropdown-content {
    display: block;
}

.table-container {
    margin-left: 20px;
    max-height: 50px;
    width: 150px;
    overflow: auto;
    box-shadow: 1px 1px 4px 0 rgba(0, 0, 0, 0.1), 0 2px 14px 0px rgba(0, 0, 0, 0.1);
}

I have played around with the position property of the divs, but it seems I can only choose from either:

make the items expand outside parent, but the position is wrong
when the table is scrolled

make the items position itself to the column, but the items does not expand outside of parent.

Here is a fiddle of my problem: (try to scroll down and hover an item)
https://jsfiddle.net/wuj9fd5c/3/

Edit:
Updated fiddle to explain both cases

Body:
I ended up writing some js code to set top and left for dropdown-content.

First I had to set the position for the parent to static:

.dropdown {
  position: static;
  display: inline-block;
}

JS:

    $(document).on('mouseenter', '.dropbtn', function () {
    var $posTop = $(this).position().top;
    var $posLeft = $(this).position().left + 20;
    $(this).parent().children(".dropdown-content").css({ top: $posTop, left: $posLeft });
});


问:
Git fails with "fatal: protocol error: bad line length character: Pass"
All git commands requiring access to the remote repository fail with the error message:

```<code>fatal: protocol error: bad line length character: Pass
</code>```

They used to work a few days ago.

答:
1. Add private key

2. Start Pageant.exe

Body:
All git commands requiring access to the remote repository fail with the error message:

fatal: protocol error: bad line length character: Pass

They used to work a few days ago.

Body:
1. Add private key

2. Start Pageant.exe

ContentLicense: CC BY-SA 4.0


问:
Reindexing elastic search index which have parent-child types
Description of problem :
I have a index(sourceIndex) which have two types(Type A & Type B), Type A is a child type and Type B is parent of Type A , i happened to update analyzers for documents in sourceIndex so i created "destinatedIndex" with new analyzers and now i want to move documents to destinationIndex , biut when i use 'ReIndex' Api i am getting below error ,

```<code>{
   "error": {
      "root_cause": [
         {
            "type": "illegal_argument_exception",
            "reason": "Can't specify parent if no parent field has been configured"
         }
      ],
      "type": "illegal_argument_exception",
      "reason": "Can't specify parent if no parent field has been configured"
   },
   "status": 400
}
</code>```

How do i proceed to reindex documents from one index to another when when the source index ahve parent child relation types , also please let me know if i miss anything.

Thanks,
K

答:
I figured out a way to re-index in the above mentioned scenarios.

I created destination index with analyzers and parent child mappings(created parent and child types at a time) , and then used reindex query to reindex from source to destination(new index) indices.Doing so i was able to eliminate parent-child relation complexities.

Thanks,
K.

Body:
Description of problem :
I have a index(sourceIndex) which have two types(Type A & Type B), Type A is a child type and Type B is parent of Type A , i happened to update analyzers for documents in sourceIndex so i created "destinatedIndex" with new analyzers and now i want to move documents to destinationIndex , biut when i use 'ReIndex' Api i am getting below error ,

{
   "error": {
      "root_cause": [
         {
            "type": "illegal_argument_exception",
            "reason": "Can't specify parent if no parent field has been configured"
         }
      ],
      "type": "illegal_argument_exception",
      "reason": "Can't specify parent if no parent field has been configured"
   },
   "status": 400
}

How do i proceed to reindex documents from one index to another when when the source index ahve parent child relation types , also please let me know if i miss anything.

Thanks,
K


问:
Angular: How to set parameters of dialog-component in .open()?
Dialog-Component:

```<code>constructor(@Inject(MAT_DIALOG_DATA)
  public data: any,
  public dialogRef: MatDialogRef<MyDialogComponent>,
  @Optional() public dialogtitle: string ) {}
</code>```

Calling part:

```<code>openMyDialog(somedata: string){
    const myDialogRef = this.dialog.open(MyDialogComponent, {data: somedata});
   }
</code>```

How can I put data for optional parameter "dialogtitle" in there?

答:
I guess you are using angular material?</p>

```<code>constructor(public dialogRef: MatDialogRef<MyDialogComponent>,
  @Optional() @Inject(MAT_DIALOG_DATA) public dialogtitle: string ) {}
</code>```

Body:
Dialog-Component:

constructor(@Inject(MAT_DIALOG_DATA)
  public data: any,
  public dialogRef: MatDialogRef<MyDialogComponent>,
  @Optional() public dialogtitle: string ) {}

Calling part:

openMyDialog(somedata: string){
    const myDialogRef = this.dialog.open(MyDialogComponent, {data: somedata});
   }

How can I put data for optional parameter "dialogtitle" in there?

Body:
I guess you are using angular material?

constructor(public dialogRef: MatDialogRef<MyDialogComponent>,
  @Optional() @Inject(MAT_DIALOG_DATA) public dialogtitle: string ) {}


问:
Is there a Selenium WebDriver available for the Microsoft Edge browser?
As of the date of this post the name "Microsoft Edge" has just been officially announced as the default browser for the new Windows 10.

It may be premature to ask but I would like to know if a new Selenium WebDriver is available for it and if not, if there is any telling how long we might expect to wait until we see one developed?

(A technical preview of Windows 10 has already been out so this doesn't seem like a foolish question to me.)

答:
Prerequisite: Windows 10 is installed on your machine

Download the specified Microsoft WebDriver server version for your build (In my case it is MicrosoftWebDriver.exe for the Operating System: Windows 10 Pro 64-bit (10.0, Build 14393))

Selenium WD Java code for MS Edge is as follows:

System.setProperty("webdriver.edge.driver", "D:\Ripon\MicrosoftWebDriver.exe");

driver = new EdgeDriver();


问:
Ant Design. How to set form field error message dynamically?
A form field has many asynchronous check rules, since a composited api can check these rules one time by return different result, i do not want to fire so many api request.</p>

答:
Use form.setFields

Syntax

Function({ fieldName: { value: any, errors: Error } })
```

<p>Example from here -</p>

<pre class="lang-jsx prettyprint-override"><code>this.props.form.setFields({
  user: {
    value: values.user,
    errors: [new Error('forbid ha')],
  },
});
</code>```

Body:
Use form.setFields

Syntax

Function({ fieldName: { value: any, errors: Error } })

Example from here -

this.props.form.setFields({
  user: {
    value: values.user,
    errors: [new Error('forbid ha')],
  },
});


答:
Here is a small visual example:

#rotate-text {
   width: 25px;
   transform: rotate(90deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="rotate-text">
  <p>My paragraph</p>
</div></code>```

Title: How to rotate text 90 degrees inline

Body:
Here is a small visual example:

#rotate-text {
   width: 25px;
   transform: rotate(90deg);
}

<div id="rotate-text">
  <p>My paragraph</p>
</div>


问:
how to "sort" polygons 3d?
I am still working on my "javascript 3d engine" (link inside stackoverflow).
at First, all my polygons were faces of cubes, so sorting them by average Z was working fine.
but now I've "evolved" and I want to draw my polygons (which may contain more than 4 vertices)
in the right order, namely, those who are close to the camera will be drawn last.

basically,
I know how to rotate them and "perspective"-ize them into 2D,
but don't know how to draw them in the right order.

just to clarify:

```<code>//my 3d shape = array of polygons
//polygon = array of vertices
//vertex = point with x,y,z
//rotation is around (0,0,0) and my view point is (0,0,something) I guess.
</code>```

can anyone help?

p.s: some "catch phrases" I came up with, looking for the solution: z-buffering, ray casting (?!), plane equations, view vector, and so on - guess I need a simple to understand answer so that's why I asked this one. thanks.

p.s2: i don't mind too much about overlapping or intersecting polygons... so maybe the painter's algorthm indeed might be good. but: what is it exactly? how do I decide the distance of a polygon?? a polygon has many points.

答:
The approach of sorting polygons and then drawing them bottom-to-top is called the "Painter's algorithm".  Unfortunately the sorting step is in general an unsolvable problem, because it's possible for 3 polygons to overlap each other:

Thus there is not necessarily any polygon that is "on top".  Alternate approaches such as using a Z buffer or BSP tree (which involves splitting polygons) don't suffer from this problem.

Title: how to "sort" polygons 3d?

Body:
I am still working on my "javascript 3d engine" (link inside stackoverflow).
at First, all my polygons were faces of cubes, so sorting them by average Z was working fine.
but now I've "evolved" and I want to draw my polygons (which may contain more than 4 vertices)
in the right order, namely, those who are close to the camera will be drawn last.

basically,
I know how to rotate them and "perspective"-ize them into 2D,
but don't know how to draw them in the right order.

just to clarify:

//my 3d shape = array of polygons
//polygon = array of vertices
//vertex = point with x,y,z
//rotation is around (0,0,0) and my view point is (0,0,something) I guess.

can anyone help?

p.s: some "catch phrases" I came up with, looking for the solution: z-buffering, ray casting (?!), plane equations, view vector, and so on - guess I need a simple to understand answer so that's why I asked this one. thanks.

p.s2: i don't mind too much about overlapping or intersecting polygons... so maybe the painter's algorthm indeed might be good. but: what is it exactly? how do I decide the distance of a polygon?? a polygon has many points.


问:
$.ajax does not delete multiple table rows with checkbox
I'm currently struggling as to why my code does not do the following multiple table row deletion php code:

```<code>incude("dbconnect.php");

if (isset($_POST["id"])) {

    foreach ($_POST["id"] as $id) {

        $sql = "DELETE FROM doctor WHERE DOC_LICENSE_NUM='.$id.'";

        if ($mydatabase->mysqli_query($sql) === TRUE) {
            echo "<div>Record deleted successfully</div>";
        } else {
            echo "Error deleting record: " . $mydatabase->error;
        }
        //$sql="DELETE from DOCTOR where DOC_LICENSE_NUM='".$id."'";
        //mysqli->query($connect, $sql);
    }
    //mysqli->close();
}
</code>```

whereas dbconnect links $mydatabase to the sql. Now, I created a button with the id btn_delete in order to use javascript click function in handling multiple rows to delete in my sql.

```<code><div style="float: right; margin: 0px 10px 10px 0px;"><button type="button" name="btn_delete" class="btn" id="btn_delete" ><span class="fa fa-trash" style="font-size:16px; margin-right:5px;"></span>Delete Multiple</button></div>
</code>```

What I did is that I used $.ajax in order to gather the checked checkboxes in an array and using the url for my php for deleting rows in the table and if it has entered the php it will proceed to fade the rows out of the table.

```<code>$('#btn_delete').click(function(){
    if(confirm("Are you sure you want to delete these?")){
        var id=[];
        $(':checkbox:checked').each(function(i){
            id[i]=$(this).val();
            //alert(id);
        });

        if(id.length===0){
            alert("Please select at least two checkboxes");
        }else{
            $.ajax({
                url:'muldel.php',
                method: 'POST',
                data: {id:id},
                success: function(){
                    for (var i=0; i<id.length; i++){
                        $('tr#'+id[i]+'').css('background-color', '#ccc');
                        $('tr#'+id[i]+'').fadeOut('slow');
                    }
                    //location.reload();
                }

            });
        }
    }else{
        return false;
    }
});
</code>```

However, when it proceeds to fade the row out of my tables, after I refresh it, it does not delete the rows like how I expected it to. What am I missing out here? (I forgot to mention that I used a unique entity key as my id)

答:
From your jquery you are posting id as coma separated ie. 1,2,3,4 etc. This should convert to array in php side array(1,2,3,4) using explode(); or make array($_POST["id"]) then put this in your foreach loop.

```<code>foreach ($array as $id) {

}
</code>```

Hope this helps

or alternate way without foreach in php, you can use  IN() in mysql.
Check complete code if intersted. http://www.phpzag.com/delete-multiple-rows-with-checkbox-using-jquery-php-mysql/

Body:
I'm currently struggling as to why my code does not do the following multiple table row deletion php code:

incude("dbconnect.php");

if (isset($_POST["id"])) {

    foreach ($_POST["id"] as $id) {

        $sql = "DELETE FROM doctor WHERE DOC_LICENSE_NUM='.$id.'";

        if ($mydatabase->mysqli_query($sql) === TRUE) {
            echo "
Record deleted successfully
";
        } else {
            echo "Error deleting record: " . $mydatabase->error;
        }
        //$sql="DELETE from DOCTOR where DOC_LICENSE_NUM='".$id."'";
        //mysqli->query($connect, $sql);
    }
    //mysqli->close();
}

whereas dbconnect links $mydatabase to the sql. Now, I created a button with the id btn_delete in order to use javascript click function in handling multiple rows to delete in my sql.

<button type="button" name="btn_delete" class="btn" id="btn_delete" >Delete Multiple</button>

What I did is that I used $.ajax in order to gather the checked checkboxes in an array and using the url for my php for deleting rows in the table and if it has entered the php it will proceed to fade the rows out of the table.

$('#btn_delete').click(function(){
    if(confirm("Are you sure you want to delete these?")){
        var id=[];
        $(':checkbox:checked').each(function(i){
            id[i]=$(this).val();
            //alert(id);
        });

        if(id.length===0){
            alert("Please select at least two checkboxes");
        }else{
            $.ajax({
                url:'muldel.php',
                method: 'POST',
                data: {id:id},
                success: function(){
                    for (var i=0; i<id.length; i++){
                        $('tr#'+id[i]+'').css('background-color', '#ccc');
                        $('tr#'+id[i]+'').fadeOut('slow');
                    }
                    //location.reload();
                }

            });
        }
    }else{
        return false;
    }
});

However, when it proceeds to fade the row out of my tables, after I refresh it, it does not delete the rows like how I expected it to. What am I missing out here? (I forgot to mention that I used a unique entity key as my id)

Body:
From your jquery you are posting id as coma separated ie. 1,2,3,4 etc. This should convert to array in php side array(1,2,3,4) using explode(); or make array($_POST["id"]) then put this in your foreach loop.

foreach ($array as $id) {

}

Hope this helps

or alternate way without foreach in php, you can use  IN() in mysql.
Check complete code if intersted. http://www.phpzag.com/delete-multiple-rows-with-checkbox-using-jquery-php-mysql/


问:
Angular, setInterval cause component to non-stop update its UI
I need to have a setInterval in one of my child components to check one of my DIV height. Problem is I found out that this setInterval cause my component UI non-stop update itself. Event the parent component also non-stop update itself.

```<code>@Component({
  selector: 'app-test-comp',
  template: `
    <ul>
      <li *ngFor="let num of [1,2,3]">
        {{ print(num) }}
      </li>
    </ul>
  `,
})
class TestComponent {
  private attr: Date;
  constructor() {
    setInterval(() => {}, 1000)
  }
  print(num) {
    return num + ' ' + new Date();
  }
}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <ul>
      <li *ngFor="let num of [1,2,3,4]">{{ test(num) }}</li>
      </ul>
      <app-test-comp></app-test-comp>
    </div>
  `,
})
export class App {
  name:string;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }
  test(num) {
    return num + ' ' + new Date()
  }
}
</code>```

PlunkerLink

Refer to plunker link above, it clearly shows that root component and its child component keep on updating its UI. If I remove that setInterval in app.ts line 18, it will behave as normal.

I wish to know what causes the non-stop update UI problem and how to prevent that.

答:
Angular depends on zone.js and zone monkey patches native methods like setTimeout and setInterval, therefore if you're using setInterval you're actually using the patched version, therefore angular is updating the UI.

To prevent this angular has a service called NgZone which implements a way to run methods outside the angular zone.

For example:

```<code>import { NgZone } from '@angular/core';

constructor(private _zone: NgZone) {
  this._zone.runOutsideAngular(() => {
    setInterval(() => {}, 1000); // this runs outside of the angular zone
    this._zone.run(() => {
      // this runs inside the angular zone
    });

  });
}
</code>```

A more detailed explanation about zones in angular can be found in this article.

Body:
I need to have a setInterval in one of my child components to check one of my DIV height. Problem is I found out that this setInterval cause my component UI non-stop update itself. Event the parent component also non-stop update itself.

@Component({
  selector: 'app-test-comp',
  template: `

        {{ print(num) }}

  `,
})
class TestComponent {
  private attr: Date;
  constructor() {
    setInterval(() => {}, 1000)
  }
  print(num) {
    return num + ' ' + new Date();
  }
}

@Component({
  selector: 'my-app',
  template: `

Hello {{name}}

{{ test(num) }}

      <app-test-comp></app-test-comp>

  `,
})
export class App {
  name:string;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }
  test(num) {
    return num + ' ' + new Date()
  }
}

PlunkerLink

Refer to plunker link above, it clearly shows that root component and its child component keep on updating its UI. If I remove that setInterval in app.ts line 18, it will behave as normal.

I wish to know what causes the non-stop update UI problem and how to prevent that.

Body:
Angular depends on zone.js and zone monkey patches native methods like setTimeout and setInterval, therefore if you're using setInterval you're actually using the patched version, therefore angular is updating the UI.

To prevent this angular has a service called NgZone which implements a way to run methods outside the angular zone.

For example:

import { NgZone } from '@angular/core';

constructor(private _zone: NgZone) {
  this._zone.runOutsideAngular(() => {
    setInterval(() => {}, 1000); // this runs outside of the angular zone
    this._zone.run(() => {
      // this runs inside the angular zone
    });

  });
}

A more detailed explanation about zones in angular can be found in this article.


问:
Host key verification failed on dockerfile build
I have created a ssh key using ssh-keygen and added id-rsa.pub content to my github>settings>SSH & GPG keys.
I am able to clone the repo from my terminal with git clone git@github:myname/myrepo.git

But the same is giving the following error while building the docker file.

```<code>Cloning into 'Project-Jenkins'...
Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

This is how I added the command in dockerfile

```<code>RUN git clone git@github.com:myname/myrepo.git
</code>```

What went wrong here?

here is my dockerfile

```<code>FROM ubuntu
COPY script.sh /script.sh
CMD ["/script.sh"]
FROM python:2.7
RUN apt-get update
RUN apt-get install libmysqlclient-dev
RUN apt-get install -y cssmin
RUN apt-get install -y python-psycopg2
RUN pip install --upgrade setuptools
RUN pip install ez_setup
RUN apt install -y libpq-dev python-dev
RUN apt install -y postgresql-server-dev-all
COPY requirements.txt ./
CMD ["apt-get","install","pip"]
RUN apt-get install -y git
RUN git clone git@github.com:myname/myrepo.git
WORKDIR ./myrepo/LIMA
RUN pip install -r requirements.txt
CMD ["python","manage.py","migrate"]
CMD ["python","manage.py","collectstatic","--noinput"]
CMD ["python","manage.py","runserver"]
EXPOSE 8000
</code>```

答:
The syntax you have used finally ends up using SSH to clone, and inside the docker container, your github private key is not available which leads to error that you are getting. So instead try using,

```<code>RUN git clone https://{myusername}:{mypassword}@github.com/{myusername}/myrepo.git
</code>```

Also remember if your password has '@' symbol use '%40' instead.

If you want to still go with private key approach, refer this question, How to access GIT repo with my private key from Dockerfile

Body:
I have created a ssh key using ssh-keygen and added id-rsa.pub content to my github>settings>SSH & GPG keys.
I am able to clone the repo from my terminal with git clone git@github:myname/myrepo.git

But the same is giving the following error while building the docker file.

Cloning into 'Project-Jenkins'...
Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

This is how I added the command in dockerfile

RUN git clone git@github.com:myname/myrepo.git

What went wrong here?

here is my dockerfile

FROM ubuntu
COPY script.sh /script.sh
CMD ["/script.sh"]
FROM python:2.7
RUN apt-get update
RUN apt-get install libmysqlclient-dev
RUN apt-get install -y cssmin
RUN apt-get install -y python-psycopg2
RUN pip install --upgrade setuptools
RUN pip install ez_setup
RUN apt install -y libpq-dev python-dev
RUN apt install -y postgresql-server-dev-all
COPY requirements.txt ./
CMD ["apt-get","install","pip"]
RUN apt-get install -y git
RUN git clone git@github.com:myname/myrepo.git
WORKDIR ./myrepo/LIMA
RUN pip install -r requirements.txt
CMD ["python","manage.py","migrate"]
CMD ["python","manage.py","collectstatic","--noinput"]
CMD ["python","manage.py","runserver"]
EXPOSE 8000

Body:
The syntax you have used finally ends up using SSH to clone, and inside the docker container, your github private key is not available which leads to error that you are getting. So instead try using,

RUN git clone https://{myusername}:{mypassword}@github.com/{myusername}/myrepo.git

Also remember if your password has '@' symbol use '%40' instead.

If you want to still go with private key approach, refer this question, How to access GIT repo with my private key from Dockerfile


问:
How can I center a text and keep being left align?
Here is a simplified of my code:

.wrapper{
  border: 1px solid gray;
  width: 30%;
  margin: 20px auto;
}
.icon{
  text-align: center;
}

.icon i{
  font-size: 100px;
  color: gray;
}
.text{
  text-align: center;
}
.text span{
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<div class="wrapper">

  <div class="icon">
    <i class="fa fa-home" aria-hidden="true"></i>
  </div>
  <div class="text">
    <span><i class="fa fa-check-square" aria-hidden="true"></i> Something </span>
    <span><i class="fa fa-check-square" aria-hidden="true"></i> Something Else </span>
    <span><i class="fa fa-check-square" aria-hidden="true"></i> Some </span>
  </div>

</div></code>```

All I want to do is putting all check icons exactly under each other vertically. How can I do that?

答:
I use ul/li for your list, I think it's more appropriate in your case
You can check this version:

.wrapper{
  border: 1px solid gray;
  width: 30%;
  margin: 20px auto;
}
.icon{
  text-align: center;
}

.icon i{
  font-size: 100px;
  color: gray;
}
.text{
  list-style-type: none;
  text-align: center;
}
.text li i{
  float: left;
}
.text span{
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<div class="wrapper">

  <div class="icon">
    <i class="fa fa-home" aria-hidden="true"></i>
  </div>
  <ul class="text">
    <li><i class="fa fa-check-square" aria-hidden="true"></i> <span>Something </span></li>
    <li><i class="fa fa-check-square" aria-hidden="true"></i> <span>Something Else </span></li>
    <li><i class="fa fa-check-square" aria-hidden="true"></i> <span>Some </span></li>
  </ul>

</div></code>```

Body:
Here is a simplified of my code:

.wrapper{
  border: 1px solid gray;
  width: 30%;
  margin: 20px auto;
}
.icon{
  text-align: center;
}

.icon i{
  font-size: 100px;
  color: gray;
}
.text{
  text-align: center;
}
.text span{
  display: block;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

     Something
     Something Else
     Some

All I want to do is putting all check icons exactly under each other vertically. How can I do that?

Body:
I use ul/li for your list, I think it's more appropriate in your case
You can check this version:

.wrapper{
  border: 1px solid gray;
  width: 30%;
  margin: 20px auto;
}
.icon{
  text-align: center;
}

.icon i{
  font-size: 100px;
  color: gray;
}
.text{
  list-style-type: none;
  text-align: center;
}
.text li i{
  float: left;
}
.text span{
  display: block;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<div class="wrapper">

  <div class="icon">
    <i class="fa fa-home" aria-hidden="true"></i>
  </div>
  <ul class="text">
    <li><i class="fa fa-check-square" aria-hidden="true"></i> <span>Something </span></li>
    <li><i class="fa fa-check-square" aria-hidden="true"></i> <span>Something Else </span></li>
    <li><i class="fa fa-check-square" aria-hidden="true"></i> <span>Some </span></li>
  </ul>

</div>


问:
Prefix filename with LasWriteTime based on filetype
Trying to append the lastwrite time (last file content modification time) timestamp into the filename of select media filetypes only, from different camera models. The pattern would be: YYYYMMDD_HHMMSS__origfilename.ext.

For example, before and after the rename:

```<code>origfilename.jpg             >   20011231_235959__origfilename.jpg
origfilename2.png            >   origfilename2.png     #.txt is not a "media_file"
</code>```

The filetypes to timestamp are defined in a nested dictionary and called with config[camID]["media_file"] for each camera type :

Code (last line gives syntax error):

```<code>config = {
    'nd5': {},
    'g7': {},
    'alpha9': {},
}
config['nd5']['media_file'] = ('nef', 'jpg', 'avi')
config['g7']['media_file'] = ('cr2', 'jpg', 'mp4')
config['alpha9']['media_file'] = ('jpg')

root = "."
def get_last_write_time(filename):
    st = os.stat(filename)
    convert_time_to_human_readable = time.strftime("%Y%m%d_%H%M%S", time.localtime(st.st_mtime))
    return convert_time_to_human_readable

timestr = convert_time_to_human_readable

for camID in config:
    for dir in next(os.walk(root))[1]:
        if dir.endswith(camID):
            for path, dirs, files in os.walk(os.path.join(root, dir)):
                for f in files:
                    if any([f.lower().endswith(x) for x in config[camID]["media_file"]]):
                        os.rename(os.path.join(path, f)
                        os.path.join(path, "%s" % timestr+'_'+f))
</code>```

Tree showing the =camID (=key1, the string after the last = in the directory name) and the filetypes to append timestamp:

```<code>└───CWD
    ├───001=nd5
    │   └───DCIM
    │       ├───125NCD5     ('nef', 'jpg', 'avi')
    │       ├───126NCD5     ('nef', 'jpg', 'avi')
    │       └───127NCD5     ('nef', 'jpg', 'avi')
    ├───002=nd5
    │   └───DCIM
    │       ├───201NCD5     ('nef', 'jpg', 'avi')
    │       ├───202NCD5     ('nef', 'jpg', 'avi')
    │       └───203NCD5     ('nef', 'jpg', 'avi')
    ├───003=g7
    │   └───DCIM
    │       ├───112___09    ('cr2', 'jpg', 'mp4')
    │       └───112___10    ('cr2', 'jpg', 'mp4')
    └───004=alpha9
        ├───DCIM
        │   └───101MSDCF    ('jpg')
        └───PRIVATE
            ├───AVCHD
            │   └───BDMV
            │       ├───CLIPINF
            │       ├───PLAYLIST
            │       └───STREAM
            └───SONY
</code>```

答:
You have small typos in your code

1. In line 5 it should be 'g7' instead of 'ng7'

2. convert_time_to_human_readable is only defined in get_last_write_time(filename) and cannot be used outside it.

3. You are missing a , in second last line.

4. Instead of using timestr in last line you should use get_last_write_time(f)

```<code>import os

config = {
    'nd5': {},
    'g7': {},
    'alpha9': {},
}
config['nd5']['media_file'] = ('nef', 'jpg', 'avi')
config['g7']['media_file'] = ('cr2', 'jpg', 'mp4')
config['alpha9']['media_file'] = ('jpg')

root = "."
def get_last_write_time(filename):
    st = os.stat(filename)
    convert_time_to_human_readable = time.strftime("%Y%m%d_%H%M%S", time.localtime(st.st_mtime))
    return convert_time_to_human_readable

for camID in config:
    for dir in next(os.walk(root))[1]:
        if dir.endswith(camID):
            for path, dirs, files in os.walk(os.path.join(root, dir)):
                for f in files:
                    if any([f.lower().endswith(x) for x in config[camID]["media_file"]]):
                        os.rename(os.path.join(path, f),os.path.join(path, "%s" % get_last_write_time(os.path.join(path, f))+'_'+f))
</code>```

Body:
Trying to append the lastwrite time (last file content modification time) timestamp into the filename of select media filetypes only, from different camera models. The pattern would be: YYYYMMDD_HHMMSS__origfilename.ext.

For example, before and after the rename:

origfilename.jpg             >   20011231_235959__origfilename.jpg
origfilename2.png            >   origfilename2.png     #.txt is not a "media_file"

The filetypes to timestamp are defined in a nested dictionary and called with config[camID]["media_file"] for each camera type :

Code (last line gives syntax error):

config = {
    'nd5': {},
    'g7': {},
    'alpha9': {},
}
config['nd5']['media_file'] = ('nef', 'jpg', 'avi')
config['g7']['media_file'] = ('cr2', 'jpg', 'mp4')
config['alpha9']['media_file'] = ('jpg')

root = "."
def get_last_write_time(filename):
    st = os.stat(filename)
    convert_time_to_human_readable = time.strftime("%Y%m%d_%H%M%S", time.localtime(st.st_mtime))
    return convert_time_to_human_readable

timestr = convert_time_to_human_readable

for camID in config:
    for dir in next(os.walk(root))[1]:
        if dir.endswith(camID):
            for path, dirs, files in os.walk(os.path.join(root, dir)):
                for f in files:
                    if any([f.lower().endswith(x) for x in config[camID]["media_file"]]):
                        os.rename(os.path.join(path, f)
                        os.path.join(path, "%s" % timestr+'_'+f))

Tree showing the =camID (=key1, the string after the last = in the directory name) and the filetypes to append timestamp:

└───CWD
    ├───001=nd5
    │   └───DCIM
    │       ├───125NCD5     ('nef', 'jpg', 'avi')
    │       ├───126NCD5     ('nef', 'jpg', 'avi')
    │       └───127NCD5     ('nef', 'jpg', 'avi')
    ├───002=nd5
    │   └───DCIM
    │       ├───201NCD5     ('nef', 'jpg', 'avi')
    │       ├───202NCD5     ('nef', 'jpg', 'avi')
    │       └───203NCD5     ('nef', 'jpg', 'avi')
    ├───003=g7
    │   └───DCIM
    │       ├───112___09    ('cr2', 'jpg', 'mp4')
    │       └───112___10    ('cr2', 'jpg', 'mp4')
    └───004=alpha9
        ├───DCIM
        │   └───101MSDCF    ('jpg')
        └───PRIVATE
            ├───AVCHD
            │   └───BDMV
            │       ├───CLIPINF
            │       ├───PLAYLIST
            │       └───STREAM
            └───SONY

Body:
You have small typos in your code

1. In line 5 it should be 'g7' instead of 'ng7'

2. convert_time_to_human_readable is only defined in get_last_write_time(filename) and cannot be used outside it.

3. You are missing a , in second last line.

4. Instead of using timestr in last line you should use get_last_write_time(f)

import os

config = {
    'nd5': {},
    'g7': {},
    'alpha9': {},
}
config['nd5']['media_file'] = ('nef', 'jpg', 'avi')
config['g7']['media_file'] = ('cr2', 'jpg', 'mp4')
config['alpha9']['media_file'] = ('jpg')

root = "."
def get_last_write_time(filename):
    st = os.stat(filename)
    convert_time_to_human_readable = time.strftime("%Y%m%d_%H%M%S", time.localtime(st.st_mtime))
    return convert_time_to_human_readable

for camID in config:
    for dir in next(os.walk(root))[1]:
        if dir.endswith(camID):
            for path, dirs, files in os.walk(os.path.join(root, dir)):
                for f in files:
                    if any([f.lower().endswith(x) for x in config[camID]["media_file"]]):
                        os.rename(os.path.join(path, f),os.path.join(path, "%s" % get_last_write_time(os.path.join(path, f))+'_'+f))


问:
ReactJs - Function in Render doesn't Show Up
**

Update: This questions has an answer that worked. It is important to
  note that even though you have a return statement in your function
  called within render(), it is still important to wrap the entire loop
  in a parent "return" in order for it to render properly on state
  change. This is a different common issue where state is not updated
  properly.

I have the following ClientList component, which shows a list of customers retrieved from database.

Below in the Render() function, i am calling the showList function which will display a list once this.props.clientList Reducer is populated.

Problem is... if I were to call the showList codes directly inside the Render() method, it will show.

IF i were to put it in a showList function, and call {this.showList} it doesn't shows up in the render.

I have the screen shot of the console as well, showing that the list is populated already.

Is this method disallowed? I see many tutorials teaching us to do this but it's not working for me. What are the restrictions to use this method to return the codes for render?

```<code>class ClientList extends Component {

    constructor(props) {
        super(props);

        this.state = {
            clientId : ''

        }
        this.getClientList = this.getClientList.bind(this);
        this.showList = this.showList.bind(this);
        console.log('initializing', this.props);
    }

    componentDidMount(){
        this.getClientList();
    }

    getClientList() {
        if (this.props.actions) {
        this.props.actions.getClientList(); //This is an ajax action to retrieve from Api
        }

    }

    showList() {

            //If i put all the codes below directly in Render, it will show.
            console.log('props from showList', this.props.clientList);

                        this.props.clientList && Object.keys(this.props.clientList).reverse().map((index,key) => {

                     return (

                     <div key={key}>
                     <div><a onClick={() => this.showProfileBox(this.props.clientList[index].customerId)}>Name: {this.props.clientList[index].firstname} {this.props.clientList[index].lastname}</a><span className="pull-right"><Link to={"/client/" + this.props.clientList[index].customerId}>Edit</Link></span></div>

                     </div>
                    );
                })
        }

    render() {
        console.log('rendering', this.props);
        return (

                <div>

                <Col xs={12} md={8}>
                <h1>Client List</h1>

                { this.showList() }  // <= This function doesn't print
                </Col>

                </div>
            )
    }

}

function mapStateToProps(state) {

    return {
        clientList: state.clientList,

    };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(clientActions, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(ClientList);
</code>```

答:
Your should return the value from showList() method.  As of now you were returning the value for map method, but not for the entire showList() method.  Thats y it is painting nothing in the page
`

```<code>showList() {
    return (
 //removed unnecessary {}
       this.props.clientList && Object.keys(this.props.clientList).reverse().map((index,key) => {
          return (
             <div key={key}>
               <div><a onClick={() => this.showProfileBox(this.props.clientList[index].customerId)}>Name: {this.props.clientList[index].firstname} {this.props.clientList[index].lastname}</a><span className="pull-right"><Link to={"/client/" + this.props.clientList[index].customerId}>Edit</Link></span></div>
             </div>
             );
      })
  );
}
</code>```

`

Body:
**

Update: This questions has an answer that worked. It is important to
  note that even though you have a return statement in your function
  called within render(), it is still important to wrap the entire loop
  in a parent "return" in order for it to render properly on state
  change. This is a different common issue where state is not updated
  properly.

I have the following ClientList component, which shows a list of customers retrieved from database.

Below in the Render() function, i am calling the showList function which will display a list once this.props.clientList Reducer is populated.

Problem is... if I were to call the showList codes directly inside the Render() method, it will show.

IF i were to put it in a showList function, and call {this.showList} it doesn't shows up in the render.

I have the screen shot of the console as well, showing that the list is populated already.

Is this method disallowed? I see many tutorials teaching us to do this but it's not working for me. What are the restrictions to use this method to return the codes for render?

class ClientList extends Component {

    constructor(props) {
        super(props);

        this.state = {
            clientId : ''

        }
        this.getClientList = this.getClientList.bind(this);
        this.showList = this.showList.bind(this);
        console.log('initializing', this.props);
    }

    componentDidMount(){
        this.getClientList();
    }

    getClientList() {
        if (this.props.actions) {
        this.props.actions.getClientList(); //This is an ajax action to retrieve from Api
        }

    }

    showList() {

            //If i put all the codes below directly in Render, it will show.
            console.log('props from showList', this.props.clientList);

                        this.props.clientList && Object.keys(this.props.clientList).reverse().map((index,key) => {

                     return (

 this.showProfileBox(this.props.clientList[index].customerId)}>Name: {this.props.clientList[index].firstname} {this.props.clientList[index].lastname}<Link to={"/client/" + this.props.clientList[index].customerId}>Edit</Link>

                    );
                })
        }

    render() {
        console.log('rendering', this.props);
        return (

                <Col xs={12} md={8}>

Client List

                { this.showList() }  // <= This function doesn't print
                </Col>

            )
    }

}

function mapStateToProps(state) {

    return {
        clientList: state.clientList,

    };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(clientActions, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(ClientList);

Body:
Your should return the value from showList() method.  As of now you were returning the value for map method, but not for the entire showList() method.  Thats y it is painting nothing in the page
`

showList() {
    return (
 //removed unnecessary {}
       this.props.clientList && Object.keys(this.props.clientList).reverse().map((index,key) => {
          return (
             <div key={key}>
               <div><a onClick={() => this.showProfileBox(this.props.clientList[index].customerId)}>Name: {this.props.clientList[index].firstname} {this.props.clientList[index].lastname}</a><span className="pull-right"><Link to={"/client/" + this.props.clientList[index].customerId}>Edit</Link></span></div>
             </div>
             );
      })
  );
}

`