问:
Video to the right of the page
I am learning html, css and web development i am trying to play videos saved in my folder in the html page created. i have a problem. I am able to get header, navigation bar but my video is going to the bottom of the navigation bar, actually it should come right to the navigation bar.

Below is the code can you let me know where i need to make changes for the video to appear in the right of the navigation bar.

my html code below

```<code><!DOCTYPE HTML>
<html lang = "en">
  <head>
  <title>Videos</title>
      <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" href="videos.css">
  </head>

<body>
   <header>
  <nav>
  <h1> Main logo </h1>
   <ul id="nav">
    <li><a class="homeblack" href="index.html">Home</a></li>
    <li><a class="homered" href="videos.html">Videos</a></li>

 </ul>
 </nav>
 </header>
 <div class="divider"></div>
 <div>

<ul>
 <li><a href="#">education videos </a></li>
 <li><a href="#">film videos</a></li>
 <li><a href="#">other videos </a></li>
</ul>
 <div id="content"> Contents
<video controls width="250" height="160">
<source src="videoplayback.mp4" />
</video>
<!-- <iframe width="560" height="315" src="https://www.youtube.com/embed/mLe1pZ7w0v0" frameborder="0" allowfullscreen></iframe> -->
</div>
</div>

    <!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

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

my css code below

```<code>* {
 padding:0px;
 margin:0px;
}

body{
  margin: 0;
 }

header {
  background: green;
  color: white;
  padding: 8px 0px 6px 40px;
  height: 50px;
}

header h1 {
 display: inline;
 font-family: 'Oswald',sans-serif;
 font-weight: 400;
 font-size: 32px;
 float: left;
 margin-top: 0px;
 margin-right: 10px;
}

nav ul{
  display: inline;
 padding: 0px;
float: left;
}

nav ul li{
 display: inline-block;
 list-style-type:none;
 color: white;
 float: left;
 margin-left: 15px;
}

nav ul li a{
 color: white;
 text-decoration: none;
}

#nav {
 font-family: 'Montserrat', sans-serif;
}

.homered{
 background-color: red;
 padding: 30px 10px 25px 10px;

}

.divider{
 background-color: red;
 height: 5px;

}

.homeblack:hover{
 background-color: blue;
 padding: 30px 10px 25px 10px;
}
div{
 width:250px;
 height:666px;
 background:#1A8DA9;
}
div a{
 text-decoration:none;
 color:white;
 padding:20px;
 padding-right:100px
}
div ul li{
 list-style-type:none;
 display:block;
 padding :15px;

 border-bottom:1px solid #236D7F;
 }
 div ul li :hover{
  background:#4097AD;
  transition:linear all 0.40s;
  margin-left:10px;
 }
 div ul li a:hover{
  color:black;
 }

#content{
    display: inline-block;
    width: 100%;
    height: 50%;
    margin-left: 165px;
    position: 5px;
    float: right ;

 }
</code>```

答:
You need to wrap your navbar in container with float: left value, also video must be wrapped in container with float: left. Look here for example on js fiddle.</p>

```<code>     <body>
     <header>
    <nav>
    <h1> Main logo </h1>
   <ul id="nav">
    <li><a class="homeblack" href="index.html">Home</a></li>
    <li><a class="homered" href="videos.html">Videos</a></li>
 </ul>
 </nav>
 </header>
 <div class="divider"></div>
 <div id="navBar">

<ul>
 <li><a href="#">education videos </a></li>
 <li><a href="#">film videos</a></li>
 <li><a href="#">other videos </a></li>
</ul>
 <div id="content"> Contents

<!-- <iframe width="560" height="315" src="https://www.youtube.com/embed/mLe1pZ7w0v0" frameborder="0" allowfullscreen></iframe> -->
</div>
</div>
 <video controls width="250" height="160">
<source src="videoplayback.mp4" />
</video>

    <!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

    </body>
  </html>
* {
 padding:0px;
 margin:0px;
}

body{
  margin: 0;
 }

header {
  background: green;
  color: white;
  padding: 8px 0px 6px 40px;
  height: 50px;
}

header h1 {
 display: inline;
 font-family: 'Oswald',sans-serif;
 font-weight: 400;
 font-size: 32px;
 float: left;
 margin-top: 0px;
 margin-right: 10px;
}

nav ul{
  display: inline;
 padding: 0px;
float: left;
}

nav ul li{
 display: inline-block;
 list-style-type:none;
 color: white;
 float: left;
 margin-left: 15px;
}

nav ul li a{
 color: white;
 text-decoration: none;
}

#nav {
 font-family: 'Montserrat', sans-serif;
}

.homered{
 background-color: red;
 padding: 30px 10px 25px 10px;

}

.divider{
 background-color: red;
 height: 5px;

}

.homeblack:hover{
 background-color: blue;
 padding: 30px 10px 25px 10px;
}
div{
 width:250px;
 height:666px;
 background:#1A8DA9;
}
div a{
 text-decoration:none;
 color:white;
 padding:20px;
 padding-right:100px
}
div ul li{
 list-style-type:none;
 display:block;
 padding :15px;

 border-bottom:1px solid #236D7F;
 }
 div ul li :hover{
  background:#4097AD;
  transition:linear all 0.40s;
  margin-left:10px;
 }
 div ul li a:hover{
  color:black;
 }

#content{
    display: inline-block;
    width: 100%;
    height: 50%;
    margin-left: 165px;
    position: 5px;
    float: right ;

 }
 #navBar {
   float: left;
 }
 video {
   float: left;
 }
</code>```

Title: Video to the right of the page

Body:
I am learning html, css and web development i am trying to play videos saved in my folder in the html page created. i have a problem. I am able to get header, navigation bar but my video is going to the bottom of the navigation bar, actually it should come right to the navigation bar.

Below is the code can you let me know where i need to make changes for the video to appear in the right of the navigation bar.

my html code below

<!DOCTYPE HTML>

  <title>Videos</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" href="videos.css">

 Main logo

Home

Videos

education videos

film videos

other videos

 Contents
<video controls width="250" height="160">
<source src="videoplayback.mp4" />
</video>

my css code below

* {
 padding:0px;
 margin:0px;
}

body{
  margin: 0;
 }

header {
  background: green;
  color: white;
  padding: 8px 0px 6px 40px;
  height: 50px;
}

header h1 {
 display: inline;
 font-family: 'Oswald',sans-serif;
 font-weight: 400;
 font-size: 32px;
 float: left;
 margin-top: 0px;
 margin-right: 10px;
}

nav ul{
  display: inline;
 padding: 0px;
float: left;
}

nav ul li{
 display: inline-block;
 list-style-type:none;
 color: white;
 float: left;
 margin-left: 15px;
}

nav ul li a{
 color: white;
 text-decoration: none;
}

#nav {
 font-family: 'Montserrat', sans-serif;
}

.homered{
 background-color: red;
 padding: 30px 10px 25px 10px;

}

.divider{
 background-color: red;
 height: 5px;

}

.homeblack:hover{
 background-color: blue;
 padding: 30px 10px 25px 10px;
}
div{
 width:250px;
 height:666px;
 background:#1A8DA9;
}
div a{
 text-decoration:none;
 color:white;
 padding:20px;
 padding-right:100px
}
div ul li{
 list-style-type:none;
 display:block;
 padding :15px;

 border-bottom:1px solid #236D7F;
 }
 div ul li :hover{
  background:#4097AD;
  transition:linear all 0.40s;
  margin-left:10px;
 }
 div ul li a:hover{
  color:black;
 }

#content{
    display: inline-block;
    width: 100%;
    height: 50%;
    margin-left: 165px;
    position: 5px;
    float: right ;

 }

Body:
You need to wrap your navbar in container with float: left value, also video must be wrapped in container with float: left. Look here for example on js fiddle.

     <body>
     <header>
    <nav>
    <h1> Main logo </h1>
   <ul id="nav">
    <li><a class="homeblack" href="index.html">Home</a></li>
    <li><a class="homered" href="videos.html">Videos</a></li>
 </ul>
 </nav>
 </header>
 <div class="divider"></div>
 <div id="navBar">

<ul>
 <li><a href="#">education videos </a></li>
 <li><a href="#">film videos</a></li>
 <li><a href="#">other videos </a></li>
</ul>
 <div id="content"> Contents

<!-- <iframe width="560" height="315" src="https://www.youtube.com/embed/mLe1pZ7w0v0" frameborder="0" allowfullscreen></iframe> -->
</div>
</div>
 <video controls width="250" height="160">
<source src="videoplayback.mp4" />
</video>

    <!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

    </body>
  </html>
* {
 padding:0px;
 margin:0px;
}

body{
  margin: 0;
 }

header {
  background: green;
  color: white;
  padding: 8px 0px 6px 40px;
  height: 50px;
}

header h1 {
 display: inline;
 font-family: 'Oswald',sans-serif;
 font-weight: 400;
 font-size: 32px;
 float: left;
 margin-top: 0px;
 margin-right: 10px;
}

nav ul{
  display: inline;
 padding: 0px;
float: left;
}

nav ul li{
 display: inline-block;
 list-style-type:none;
 color: white;
 float: left;
 margin-left: 15px;
}

nav ul li a{
 color: white;
 text-decoration: none;
}

#nav {
 font-family: 'Montserrat', sans-serif;
}

.homered{
 background-color: red;
 padding: 30px 10px 25px 10px;

}

.divider{
 background-color: red;
 height: 5px;

}

.homeblack:hover{
 background-color: blue;
 padding: 30px 10px 25px 10px;
}
div{
 width:250px;
 height:666px;
 background:#1A8DA9;
}
div a{
 text-decoration:none;
 color:white;
 padding:20px;
 padding-right:100px
}
div ul li{
 list-style-type:none;
 display:block;
 padding :15px;

 border-bottom:1px solid #236D7F;
 }
 div ul li :hover{
  background:#4097AD;
  transition:linear all 0.40s;
  margin-left:10px;
 }
 div ul li a:hover{
  color:black;
 }

#content{
    display: inline-block;
    width: 100%;
    height: 50%;
    margin-left: 165px;
    position: 5px;
    float: right ;

 }
 #navBar {
   float: left;
 }
 video {
   float: left;
 }


来源: stackexchange

问:
Lodash vs JavaScript Built In for map,reduce,filter
I was wondering whether it is better to include Lodash for these 3 functions [map(),reduce(),filter()] or just to use the ES6 versions of them.

I prefer using the Lodash functions, it's a little simpler for my use case. However, I am aware there is probably a performance benefit to using the ES6 functions.

Also was wondering whether Lodash is more backwards compatible that ES6?

Suggestions on how to test performance of my implementations?

Suggestions of whether to continue using Lodash or to use ES6?

答:
Js perf can be used to test performance - as in this test from 2015 which shows lodash's Map being markedly faster than the native map function. I'm not sure to what extent this performance difference remains.

It's more common for web apps to feel slow due to loading large amounts of code, rather than that JavaScipt being too slow. If these are the only functions you plan to use from Lodash, I would suggest using Native es6 methods.

ContentLicense: CC BY-SA 3.0


问:
Can't get the browser to read my CSS
Can't work out why this code is not working:

CSS then corresponding HTML:

.intro {
  border: 5px
  border-color: rgb(0,0,255);
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="intro">
   <p>writing</p>
   <p>writing</p>
</div></code>```

No variation seems to work, and I have checked this site, W3C, and seem to be writing the code correctly in the CSS file, but it just is not translating to the browser (Chrome).

答:
1) If you do not assign a value,The default value is defined for it. default value for border-style is none, so you can't see result.

2) A CSS declaration always ends with a semicolon(;).

Change :

```<code> .intro {
     border: 5px   <-------------------
     border-color: rgb(0,0,255);
     text-align: center;
    }
</code>```

To :

```<code>.intro {
     border: 5px solid;   <-------------------
     border-color: rgb(0,0,255);
     text-align: center;
    }
</code>```

or

```<code>.intro {
     border: 5px;
     border-style: solid;   <----------- Or other Value.
     border-color: rgb(0,0,255);
     text-align: center;
    }
</code>```

Title: Can't get the browser to read my CSS

Body:
Can't work out why this code is not working:

CSS then corresponding HTML:

.intro {
  border: 5px
  border-color: rgb(0,0,255);
  text-align: center;
}

writing

writing

No variation seems to work, and I have checked this site, W3C, and seem to be writing the code correctly in the CSS file, but it just is not translating to the browser (Chrome).

Body:
1) If you do not assign a value,The default value is defined for it. default value for border-style is none, so you can't see result.

2) A CSS declaration always ends with a semicolon(;).

Change :

 .intro {
     border: 5px   <-------------------
     border-color: rgb(0,0,255);
     text-align: center;
    }

To :

.intro {
     border: 5px solid;   <-------------------
     border-color: rgb(0,0,255);
     text-align: center;
    }

or

.intro {
     border: 5px;
     border-style: solid;   <----------- Or other Value.
     border-color: rgb(0,0,255);
     text-align: center;
    }


问:
chart x-axis numbering
I am using WinForms chart to visualize some data. I want x-axis gridlines at points specified by me. Please take a look at the following example.

```<code>public partial class Form1: Form
{
    public Form1()
    {
        InitializeComponent();
        AddPoints();
    }

    public void AddPoints()
    {
        for (int i = 0; i <= 100; i++)
            chart1.Series[0].Points.AddXY(i, i);
    }
}
</code>```

In the chart you can see the grid lines for X-Axis appears at 19,39,59,79 and 99. But I want it in 0,15,45,65,90,100. You can clearly see the interval is not the same. So setting the interval is of no use. Is it possible to have grid lines in my own specified point?

答:
This is not possible with GridLines as they will always be drawn at the fixed Interval spacing. Here is an example of working around by drawing the lines in an xxxPaint event..

First we declare a list of stop values for the GridLines we want:

```<code>List<double> stops = new List<double>();
</code>```

Then we prepare the chart:

```<code>AddPoints();

ChartArea ca = chart1.ChartAreas[0];
ca.AxisX.Minimum = 0;  // optional
ca.AxisX.MajorGrid.Enabled = false;
ca.AxisX.MajorTickMark.Enabled = false;
ca.AxisX.LabelStyle.Enabled = false;

stops.AddRange(new[] { 0, 15, 45, 50.5, 65, 90, 100 });
</code>```

Note that I have added one extra value (50.5) to show how we can draw GridLines even where not DataPoints are!

Then we code the PostPaint event:

```<code>private void chart1_PostPaint(object sender, ChartPaintEventArgs e)
{
    Graphics g = e.ChartGraphics.Graphics;
    g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;

    ChartArea ca = chart1.ChartAreas[0];

    Font font = ca.AxisX.LabelStyle.Font;
    Color col = ca.AxisX.MajorGrid.LineColor;
    int padding = 10; // pad the labels from the axis

    int y0 = (int)ca.AxisY.ValueToPixelPosition(ca.AxisY.Minimum);
    int y1 = (int)ca.AxisY.ValueToPixelPosition(ca.AxisY.Maximum);

    foreach (int sx  in stops)
    {
        int x = (int)ca.AxisX.ValueToPixelPosition(sx);

        using (Pen pen = new Pen(col))
            g.DrawLine(pen, x, y0, x, y1);

        string s =  sx + "";
        if (ca.AxisX.LabelStyle.Format != "")
            s = string.Format(ca.AxisX.LabelStyle.Format, s);

        SizeF sz = g.MeasureString(s, font, 999);
        g.DrawString(s, font, Brushes.Black, (int)(x - sz.Width / 2) , y0 + padding);
}
</code>```

This is the result:

Note that most of the code in the PostPaint event is just preparation; the two actual drawing calls for the lines and the labels are ordinary GDI+ methods..

Note that I have added DataPoint labels to every 10th point in the loop to show where we are:

```<code>chart1.Series[0].Points.AddXY(i, i);
if (i%10 == 0) chart1.Series[0].Points[i].Label = "#VAL / #VALY";
</code>```

Title: chart x-axis numbering

Body:
I am using WinForms chart to visualize some data. I want x-axis gridlines at points specified by me. Please take a look at the following example.

public partial class Form1: Form
{
    public Form1()
    {
        InitializeComponent();
        AddPoints();
    }

    public void AddPoints()
    {
        for (int i = 0; i <= 100; i++)
            chart1.Series[0].Points.AddXY(i, i);
    }
}

In the chart you can see the grid lines for X-Axis appears at 19,39,59,79 and 99. But I want it in 0,15,45,65,90,100. You can clearly see the interval is not the same. So setting the interval is of no use. Is it possible to have grid lines in my own specified point?

Body:
This is not possible with GridLines as they will always be drawn at the fixed Interval spacing. Here is an example of working around by drawing the lines in an xxxPaint event..

First we declare a list of stop values for the GridLines we want:

List<double> stops = new List<double>();

Then we prepare the chart:

AddPoints();

ChartArea ca = chart1.ChartAreas[0];
ca.AxisX.Minimum = 0;  // optional
ca.AxisX.MajorGrid.Enabled = false;
ca.AxisX.MajorTickMark.Enabled = false;
ca.AxisX.LabelStyle.Enabled = false;

stops.AddRange(new[] { 0, 15, 45, 50.5, 65, 90, 100 });

Note that I have added one extra value (50.5) to show how we can draw GridLines even where not DataPoints are!

Then we code the PostPaint event:

private void chart1_PostPaint(object sender, ChartPaintEventArgs e)
{
    Graphics g = e.ChartGraphics.Graphics;
    g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;

    ChartArea ca = chart1.ChartAreas[0];

    Font font = ca.AxisX.LabelStyle.Font;
    Color col = ca.AxisX.MajorGrid.LineColor;
    int padding = 10; // pad the labels from the axis

    int y0 = (int)ca.AxisY.ValueToPixelPosition(ca.AxisY.Minimum);
    int y1 = (int)ca.AxisY.ValueToPixelPosition(ca.AxisY.Maximum);

    foreach (int sx  in stops)
    {
        int x = (int)ca.AxisX.ValueToPixelPosition(sx);

        using (Pen pen = new Pen(col))
            g.DrawLine(pen, x, y0, x, y1);

        string s =  sx + "";
        if (ca.AxisX.LabelStyle.Format != "")
            s = string.Format(ca.AxisX.LabelStyle.Format, s);

        SizeF sz = g.MeasureString(s, font, 999);
        g.DrawString(s, font, Brushes.Black, (int)(x - sz.Width / 2) , y0 + padding);
}

This is the result:

Note that most of the code in the PostPaint event is just preparation; the two actual drawing calls for the lines and the labels are ordinary GDI+ methods..

Note that I have added DataPoint labels to every 10th point in the loop to show where we are:

chart1.Series[0].Points.AddXY(i, i);
if (i%10 == 0) chart1.Series[0].Points[i].Label = "#VAL / #VALY";


问:
A* Search Algorithm gets stuck
I am trying to implement an A* Search algorithm. For now I am just trying to find a good path through an environment littered with walls. The walls are randomly generated, and in some cases my path gets "stuck". If the search encounters a wall in front of it, and to all of its sides (except the one that led it into this mess), it stops.
Is there something I can do to prevent this? I am using a "as the crow flies" point system for my H value, which ignores the walls and just estimates how far it will take to get to the destination. This sometimes leads it into this trap.

Thanks.

答:
Underestimating the distance is 'proper' for A*.

But it sounds like you have a depth/breadth problem.

When evaluating options from a given position, you should add them to a list of options to check and sort them by score. There should be no reason why you would check the options available from a given position immediately after you've evaluated that position - i.e. all options from each position should go into the same list. This way, when you hit a dead end, it simply does not generate further options and you proceed by taking the next highest scored option off the list and evaluating that.

ContentLicense: CC BY-SA 2.5

Title: A* Search Algorithm gets stuck


问:
Failed to find provider info error
I am trying to have a contentprovider  , but I am having trouble because I am getting an error of "Failed to find provider info for com.example.alex.hopefulyworks"

Here is the manifest and the contentprovider

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.alex.hopefulythisworks" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider android:name=".ColorContentProvider"
            android:authorities="com.example.alex.hopefulythisworks.ColorContentProvider"
            android:enabled="true"
            android:exported="true" >
        </provider>

    </application>

</manifest>

    package com.example.alex.hopefulythisworks;
     ....
    public class ColorContentProvider extends ContentProvider {

    private ColorHelper database;

    private static final String AUTHORITY
            = "com.example.alex.hopefulythisworks";

    private static final String BASE_PATH
            = "tasks";

    public static final Uri CONTENT_URI
            = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);
    public static final String CONTENT_URI_PREFIX
            = "content://" + AUTHORITY + "/" + BASE_PATH + "/";

    private static final UriMatcher sURIMatcher =
            new UriMatcher(UriMatcher.NO_MATCH);

    private static final int COLOR = 1;
    private static final int COLOR_ROW = 2;

    static {
        sURIMatcher.addURI(AUTHORITY, BASE_PATH, COLOR);
        sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/#", COLOR_ROW);
    }

    @Override
    public boolean onCreate() {
        database = new ColorHelper(getContext());
       Log.d("contentprovider" , "inside content provider oncreate ");
        return false;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        int uriType = sURIMatcher.match(uri);

        SQLiteDatabase sqlDB = database.getWritableDatabase();

        long id = 0;
        switch (uriType) {
            case COLOR:
                id = sqlDB.insert(ColorTable.TABLE_TASK,
                        null, values);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: "
                        + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return Uri.parse( CONTENT_URI_PREFIX + id);
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {

        // check if the caller has requested a column which does not exists
        ColorTable.validateProjection( projection );

        // Using SQLiteQueryBuilder instead of query() method
        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

        queryBuilder.setTables( ColorTable.TABLE_TASK );

        switch ( sURIMatcher.match(uri) ) {
            case COLOR:
                break;
            case COLOR_ROW:
                // add the task ID to the original query
                queryBuilder.appendWhere( ColorTable.COLUMN_ID + "=" + uri.getLastPathSegment() );
                break;
            default:
                throw new IllegalArgumentException("Invalid URI: " + uri);
        }

        System.out.println("before null check");
        if(database == null){
            System.out.println("database is null");
            database = new ColorHelper(getContext());
        }
        System.out.println("after null check");

        SQLiteDatabase db = database.getWritableDatabase();
        Cursor cursor = queryBuilder.query( db, projection, selection,
                selectionArgs, null, null, sortOrder);

        // notify listeners
        cursor.setNotificationUri(getContext().getContentResolver(), uri);

        return cursor;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase sqlDB = database.getWritableDatabase();
        int rowsDeleted = 0;
        switch ( sURIMatcher.match(uri) ) {
            case COLOR:
                rowsDeleted = sqlDB.delete(ColorTable.TABLE_TASK, selection, selectionArgs);
                break;
            case COLOR_ROW:
                String id = uri.getLastPathSegment();
                if (TextUtils.isEmpty(selection)) {
                    rowsDeleted = sqlDB.delete( ColorTable.TABLE_TASK,
                            ColorTable.COLUMN_ID + "=" + id,
                            null);
                } else {
                    rowsDeleted = sqlDB.delete( ColorTable.TABLE_TASK,
                            ColorTable.COLUMN_ID + "=" + id
                                    + " and " + selection,
                            selectionArgs);
                }
                break;
            default:
                throw new IllegalArgumentException("Invalid URI: " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return rowsDeleted;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection , String[] selectionArgs) {

        SQLiteDatabase sqlDB = database.getWritableDatabase();
        int rowsUpdated = 0;
        switch ( sURIMatcher.match(uri) ) {
            case COLOR:
                rowsUpdated = sqlDB.update( ColorTable.TABLE_TASK,
                        values,
                        selection,
                        selectionArgs);
                break;
            case COLOR_ROW:
                String id = uri.getLastPathSegment();
                if (TextUtils.isEmpty(selection)) {
                    rowsUpdated = sqlDB.update( ColorTable.TABLE_TASK,
                            values,
                            ColorTable .COLUMN_ID + "=" + id,
                            null );
                } else {
                    rowsUpdated = sqlDB.update( ColorTable.TABLE_TASK,
                            values,
                            ColorTable.COLUMN_ID + "=" + id
                                    + " and " + selection,
                            selectionArgs);
                }
                break;
            default:
                throw new IllegalArgumentException("Invalid URI: " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return rowsUpdated;
    }

}
</code>```

答:
```<code><provider
      android:name="com.example.absolutelysaurabh.todoapp.ColorContentProvider"
      android:authorities="com.example.absolutelysaurabh.todoapp"
      android:enabled="true"
      android:exported="false" >
</provider>
</code>```

IMPORTANT : Make sure in the "Contract" class u've also used the same AUTHORITY as used here i.e. "com.example.absolutelysaurabh.todoapp"

Title: Failed to find provider info error

Body:
I am trying to have a contentprovider  , but I am having trouble because I am getting an error of "Failed to find provider info for com.example.alex.hopefulyworks"

Here is the manifest and the contentprovider

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.alex.hopefulythisworks" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider android:name=".ColorContentProvider"
            android:authorities="com.example.alex.hopefulythisworks.ColorContentProvider"
            android:enabled="true"
            android:exported="true" >
        </provider>

    </application>

</manifest>

    package com.example.alex.hopefulythisworks;
     ....
    public class ColorContentProvider extends ContentProvider {

    private ColorHelper database;

    private static final String AUTHORITY
            = "com.example.alex.hopefulythisworks";

    private static final String BASE_PATH
            = "tasks";

    public static final Uri CONTENT_URI
            = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);
    public static final String CONTENT_URI_PREFIX
            = "content://" + AUTHORITY + "/" + BASE_PATH + "/";

    private static final UriMatcher sURIMatcher =
            new UriMatcher(UriMatcher.NO_MATCH);

    private static final int COLOR = 1;
    private static final int COLOR_ROW = 2;

    static {
        sURIMatcher.addURI(AUTHORITY, BASE_PATH, COLOR);
        sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/#", COLOR_ROW);
    }

    @Override
    public boolean onCreate() {
        database = new ColorHelper(getContext());
       Log.d("contentprovider" , "inside content provider oncreate ");
        return false;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        int uriType = sURIMatcher.match(uri);

        SQLiteDatabase sqlDB = database.getWritableDatabase();

        long id = 0;
        switch (uriType) {
            case COLOR:
                id = sqlDB.insert(ColorTable.TABLE_TASK,
                        null, values);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: "
                        + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return Uri.parse( CONTENT_URI_PREFIX + id);
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {

        // check if the caller has requested a column which does not exists
        ColorTable.validateProjection( projection );

        // Using SQLiteQueryBuilder instead of query() method
        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

        queryBuilder.setTables( ColorTable.TABLE_TASK );

        switch ( sURIMatcher.match(uri) ) {
            case COLOR:
                break;
            case COLOR_ROW:
                // add the task ID to the original query
                queryBuilder.appendWhere( ColorTable.COLUMN_ID + "=" + uri.getLastPathSegment() );
                break;
            default:
                throw new IllegalArgumentException("Invalid URI: " + uri);
        }

        System.out.println("before null check");
        if(database == null){
            System.out.println("database is null");
            database = new ColorHelper(getContext());
        }
        System.out.println("after null check");

        SQLiteDatabase db = database.getWritableDatabase();
        Cursor cursor = queryBuilder.query( db, projection, selection,
                selectionArgs, null, null, sortOrder);

        // notify listeners
        cursor.setNotificationUri(getContext().getContentResolver(), uri);

        return cursor;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase sqlDB = database.getWritableDatabase();
        int rowsDeleted = 0;
        switch ( sURIMatcher.match(uri) ) {
            case COLOR:
                rowsDeleted = sqlDB.delete(ColorTable.TABLE_TASK, selection, selectionArgs);
                break;
            case COLOR_ROW:
                String id = uri.getLastPathSegment();
                if (TextUtils.isEmpty(selection)) {
                    rowsDeleted = sqlDB.delete( ColorTable.TABLE_TASK,
                            ColorTable.COLUMN_ID + "=" + id,
                            null);
                } else {
                    rowsDeleted = sqlDB.delete( ColorTable.TABLE_TASK,
                            ColorTable.COLUMN_ID + "=" + id
                                    + " and " + selection,
                            selectionArgs);
                }
                break;
            default:
                throw new IllegalArgumentException("Invalid URI: " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return rowsDeleted;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection , String[] selectionArgs) {

        SQLiteDatabase sqlDB = database.getWritableDatabase();
        int rowsUpdated = 0;
        switch ( sURIMatcher.match(uri) ) {
            case COLOR:
                rowsUpdated = sqlDB.update( ColorTable.TABLE_TASK,
                        values,
                        selection,
                        selectionArgs);
                break;
            case COLOR_ROW:
                String id = uri.getLastPathSegment();
                if (TextUtils.isEmpty(selection)) {
                    rowsUpdated = sqlDB.update( ColorTable.TABLE_TASK,
                            values,
                            ColorTable .COLUMN_ID + "=" + id,
                            null );
                } else {
                    rowsUpdated = sqlDB.update( ColorTable.TABLE_TASK,
                            values,
                            ColorTable.COLUMN_ID + "=" + id
                                    + " and " + selection,
                            selectionArgs);
                }
                break;
            default:
                throw new IllegalArgumentException("Invalid URI: " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return rowsUpdated;
    }

}

Body:
<provider
      android:name="com.example.absolutelysaurabh.todoapp.ColorContentProvider"
      android:authorities="com.example.absolutelysaurabh.todoapp"
      android:enabled="true"
      android:exported="false" >
</provider>

IMPORTANT : Make sure in the "Contract" class u've also used the same AUTHORITY as used here i.e. "com.example.absolutelysaurabh.todoapp"

ContentLicense: CC BY-SA 4.0


问:
Setup flag in Javascript
Below is a script I am using for a Google Docs Spreadsheet.

These links show what I am doing:

http://i.stack.imgur.com/uGik7.png

http://i.stack.imgur.com/AbKnQ.png

How can I set up a "flag" so that when I run this script a second time, it doesn't add the perviously added stock items?

```<code>function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss.getSheetByName("Purchase Orders");
  var sheet2 = ss.getSheetByName("Inventory");
  var data = sheet1.getDataRange();
  var i_data = sheet2.getDataRange();
  var lastRow = data.getLastRow();
  var iLastRow = i_data.getLastRow();

  for (i=1;i<=lastRow;i++) {
    if (data.getCell(i, 5).getValue() == "stock"){
      for (n=1;n<=iLastRow;n++){
        if (data.getCell(i,3).getValue() == i_data.getCell(n,3).getValue()) {
        i_data.getCell(n, 1).setValue(i_data.getCell(n,1).getValue() + data.getCell(i,2).getValue());
       }
      }
    }

  }
}
</code>```

I guess I'm trying to do this: Once the item has been added to inventory, the script adds an x to column i of that line. Then when the script is run again, it skips over the lines with an x in column i

答: Designate a cell to hold the flag value, and have the script check that particular cell for the flag value.</p>

Title: Setup flag in Javascript

Body:
Below is a script I am using for a Google Docs Spreadsheet.

These links show what I am doing:

http://i.stack.imgur.com/uGik7.png

http://i.stack.imgur.com/AbKnQ.png

How can I set up a "flag" so that when I run this script a second time, it doesn't add the perviously added stock items?

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss.getSheetByName("Purchase Orders");
  var sheet2 = ss.getSheetByName("Inventory");
  var data = sheet1.getDataRange();
  var i_data = sheet2.getDataRange();
  var lastRow = data.getLastRow();
  var iLastRow = i_data.getLastRow();

  for (i=1;i<=lastRow;i++) {
    if (data.getCell(i, 5).getValue() == "stock"){
      for (n=1;n<=iLastRow;n++){
        if (data.getCell(i,3).getValue() == i_data.getCell(n,3).getValue()) {
        i_data.getCell(n, 1).setValue(i_data.getCell(n,1).getValue() + data.getCell(i,2).getValue());
       }
      }
    }

  }
}

I guess I'm trying to do this: Once the item has been added to inventory, the script adds an x to column i of that line. Then when the script is run again, it skips over the lines with an x in column i


问:
NetSuite User Event or Workflow on Work Order Close
I looked all over and I can't see to find how to connect a script to the "close" event of the Work Order. Basically, I need to send an email to the Sales Rep for the order that is being fulfilled when the Work Order is "closed" what approach would be better? A workflow or a UserEvent, I looked at workflow as the Close button is a non-standard event. When I went to set up the workflow I didn't see Work Order as a record to attach it to. Any help would be great, thanks  </p>

答: What I came to find out is that the Work Order Close status is from a Work Order Close form, in that case just the after submit event takes care of this. Thanks for all your help and sorry I took so long to post this answer </p>


问:
Launching Chrome and passing the url with selenium
I am using selenium for the first time:
below is my basic Code to launch the chrome and pass the google url:

```<code>public class first {
    public static void main(String args[]){
        System.setProperty("webdriver.chrome.driver","C://Program Files (x86)//Google//Chrome//Application//chrome.exe");
        WebDriver dr1= new ChromeDriver(); ;
        String baseurl = "http://www.google.com/";
        dr1.get(baseurl);

    }
}
</code>```

After executing it is launching the browser but not sending the url to it.
below is the error i got in console output:

```<code>Exception in thread "main" org.openqa.selenium.WebDriverException: Timed out waiting for driver server to start.
Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
System info: host: 'D-113091507', ip: '172.16.195.19', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_131'
Driver info: driver.version: ChromeDriver
    at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:193)
    at org.openqa.selenium.remote.service.DriverService.start(DriverService.java:181)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:78)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:637)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:250)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:236)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:137)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:184)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:171)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:124)
    at first.first.main(first.java:12)
</code>```

Can someone please help me out with this?

答:
Here is the Answer to your Question:

When you work with Selenium 3.x you have to download chromedriver.exe from here and save it in your machine. Next you have to mention the absolute path of the chromedriver.exe through System.setProperty. While you mention the absolute path of the chromedriver.exe through System.setProperty you have either provide front slashes "/" or esacpe the back slases "\\". Here is your own working code with some simple tweaks:

```<code>public class first
{
    public static void main(String args[])
    {
        System.setProperty("webdriver.chrome.driver","C:/your_directory/chromedriver.exe");
        WebDriver dr1= new ChromeDriver(); ;
        String baseurl = "http://www.google.com/";
        dr1.get(baseurl);
    }
}
</code>```

Let me know if this Answers your Question

Body:
I am using selenium for the first time:
below is my basic Code to launch the chrome and pass the google url:

public class first {
    public static void main(String args[]){
        System.setProperty("webdriver.chrome.driver","C://Program Files (x86)//Google//Chrome//Application//chrome.exe");
        WebDriver dr1= new ChromeDriver(); ;
        String baseurl = "http://www.google.com/";
        dr1.get(baseurl);

    }
}

After executing it is launching the browser but not sending the url to it.
below is the error i got in console output:

Exception in thread "main" org.openqa.selenium.WebDriverException: Timed out waiting for driver server to start.
Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
System info: host: 'D-113091507', ip: '172.16.195.19', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_131'
Driver info: driver.version: ChromeDriver
    at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:193)
    at org.openqa.selenium.remote.service.DriverService.start(DriverService.java:181)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:78)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:637)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:250)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:236)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:137)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:184)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:171)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:124)
    at first.first.main(first.java:12)

Can someone please help me out with this?

Body:
Here is the Answer to your Question:

When you work with Selenium 3.x you have to download chromedriver.exe from here and save it in your machine. Next you have to mention the absolute path of the chromedriver.exe through System.setProperty. While you mention the absolute path of the chromedriver.exe through System.setProperty you have either provide front slashes "/" or esacpe the back slases "\\". Here is your own working code with some simple tweaks:

public class first
{
    public static void main(String args[])
    {
        System.setProperty("webdriver.chrome.driver","C:/your_directory/chromedriver.exe");
        WebDriver dr1= new ChromeDriver(); ;
        String baseurl = "http://www.google.com/";
        dr1.get(baseurl);
    }
}

Let me know if this Answers your Question


问:
characters in for loop printing out too far away from values
I am very new to java and for loops. I would like my code to print out this

```<code>Andy      **
Kristy    **********
Amy       ***** `
</code>```

But my I am getting this instead

```<code>Andy          **
Kristy          **********
Amy          *****
</code>```

How do I change my for loop to stop the spacing from the names being this way? Thank you.

```<code>public static void drawChart(String name, int age) {
    System.out.print(name);
    for(int j = 1; j <= 10; j++) {
        System.out.print(" ");
    }

    for (int i=0; i<age; i++) {
        System.out.print("*");
    }

    System.out.println(" ");
}
</code>```

答:
The above answers are good, but they do not consider the situation when you call the function with the longest name and then you call the function again with the next longest name. In that case the spacing would be different.
Here is the solution with due respect to that issue:

```<code>import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import java.util.Map;
import java.util.Set;

public class Search {

    public static void drawChart(Multimap<String, Integer> persons){
        //we use Multimap because we may have more than one person with the same name
        Set<String> names = persons.keySet();
        int maxLength = 0;
        for (String name : names) {
            if (name.length() > maxLength) {
                maxLength = name.length(); //define the longest name
            }
        }

        for (Map.Entry<String, Integer> entry : persons.entries()) {
            String name = entry.getKey();
            System.out.print(name);
            if (name.length() < maxLength) {
                //adjusting the number of spaces required to be on the same level
                //with the longest name
                int diff = maxLength - name.length();
                for (int i = 0; i < diff; i++) {
                    System.out.print(" ");
                }
            }
            Integer age = entry.getValue();
            for (int i = 0; i < age; i++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        Multimap<String, Integer> map = ArrayListMultimap.create();
        map.put("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 2);
        map.put("ffffffffffffffffffffffffffffffffffffffffffffffffff" +
            "fffffffffffffffffffffffff", 3);
        map.put("zz", 3);
        map.put("zz", 6);
        map.put("ffff", 9);
        drawChart(map);
    }
}
</code>```

The output:

```<code>zz                                                                                ***
zz                                                                                ******
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff           ***
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa**
ffff                                                                                *********
</code>```

Body:
I am very new to java and for loops. I would like my code to print out this

Andy      **
Kristy    **********
Amy       ***** `

But my I am getting this instead

Andy          **
Kristy          **********
Amy          *****

How do I change my for loop to stop the spacing from the names being this way? Thank you.

public static void drawChart(String name, int age) {
    System.out.print(name);
    for(int j = 1; j <= 10; j++) {
        System.out.print(" ");
    }

    for (int i=0; i<age; i++) {
        System.out.print("*");
    }

    System.out.println(" ");
}

Body:
The above answers are good, but they do not consider the situation when you call the function with the longest name and then you call the function again with the next longest name. In that case the spacing would be different.
Here is the solution with due respect to that issue:

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import java.util.Map;
import java.util.Set;

public class Search {

    public static void drawChart(Multimap<String, Integer> persons){
        //we use Multimap because we may have more than one person with the same name
        Set<String> names = persons.keySet();
        int maxLength = 0;
        for (String name : names) {
            if (name.length() > maxLength) {
                maxLength = name.length(); //define the longest name
            }
        }

        for (Map.Entry<String, Integer> entry : persons.entries()) {
            String name = entry.getKey();
            System.out.print(name);
            if (name.length() < maxLength) {
                //adjusting the number of spaces required to be on the same level
                //with the longest name
                int diff = maxLength - name.length();
                for (int i = 0; i < diff; i++) {
                    System.out.print(" ");
                }
            }
            Integer age = entry.getValue();
            for (int i = 0; i < age; i++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        Multimap<String, Integer> map = ArrayListMultimap.create();
        map.put("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 2);
        map.put("ffffffffffffffffffffffffffffffffffffffffffffffffff" +
            "fffffffffffffffffffffffff", 3);
        map.put("zz", 3);
        map.put("zz", 6);
        map.put("ffff", 9);
        drawChart(map);
    }
}

The output:

zz                                                                                ***
zz                                                                                ******
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff           ***
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa**
ffff                                                                                *********


问:
Docker passing in a variable into an shell script running git clone
I am creating a Dockerfile and as part of this file, I am wanting to give the end user the option to pass in their git repo.

I looked at this SO post, and a few other sites but am stuck on the git clone syntax.

The git clone command returns an error as the variable that is part of it does not contain a value at the docker build stage.

I have this bash script called gitclone.sh

```<code>#!/bin/bash
git clone $1 /app
</code>```

and in my Dockerfile I have this line:

RUN ./gitclone.sh $LOCATION

The shell script has the right permissions to run and it works when running it from within the container since I am passing an actual repository to it.

During the Docker build phase I get the following error:

fatal: repository '/app' does not exist

The directory is there, but the $1 is empty to the command doesn't work.

Question
How do I make the Dockerfile work? The desired output I want it:

docker run -e LOCATION=https://github.com/something.git -d jwknz/pg02

UPDATE
Changing my Dockerfile to contain
CMD ["../gitclone.sh","$LOCATION"] instead of RUN ./gitclone.sh $LOCATION doesn't fix it.

The Dockerfile will build, but the container stops after running the docker run command.

答:
First off, you have to notice that the Dockerfile is used to build your image (with the docker build command) and docker run is used to start a container from the already build docker image.

You have to define an entrypoint script. This is a script that is executed every time a container is started from the image you've build with the Dockerfile.

Assuming you want to clone a git repo and run apache httpd afterwards you can create a script like this in the same folder where your Dockerfile is. Name it, e.g. gitCloneAndRunHttpd.sh

```<code>#!/bin/bash

git clone $LOCATION /app
/usr/local/apache2/bin/apachectl -f /usr/local/apache2/conf/httpd.conf
</code>```

Then you have to modify your Dockerfile telling docker to copy the script file to your docker image, make it executable, en tell it to run it at container creation:

```<code>[...]

COPY ["gitCloneAndRunHttpd.sh", "/gitCloneAndRunHttpd.sh"]
RUN chmod +x /gitCloneAndRunHttpd.sh
ENTRYPOINT ["/gitCloneAndRunHttpd.sh"]
</code>```

After this you build your docker image with the docker build command and then you can start creating containers from your image.

Every time you start a container from it with docker run -e LOCATION=https://github.com/some-git-repo.url -d your/image, the repo https://github.com/some-git-repo.url will be cloned from within the container to the /app folder and apache httpd will be started.

Note: If you are wondering what is going on in the SO post you mentioned, there the default entrypoint is used (/bin/sh), and /file.sh abc is the argument passed to that entrypoint, therefore the file.sh script is executed.

Body:
I am creating a Dockerfile and as part of this file, I am wanting to give the end user the option to pass in their git repo.

I looked at this SO post, and a few other sites but am stuck on the git clone syntax.

The git clone command returns an error as the variable that is part of it does not contain a value at the docker build stage.

I have this bash script called gitclone.sh

#!/bin/bash
git clone $1 /app

and in my Dockerfile I have this line:

RUN ./gitclone.sh $LOCATION

The shell script has the right permissions to run and it works when running it from within the container since I am passing an actual repository to it.

During the Docker build phase I get the following error:

fatal: repository '/app' does not exist

The directory is there, but the $1 is empty to the command doesn't work.

Question
How do I make the Dockerfile work? The desired output I want it:

docker run -e LOCATION=https://github.com/something.git -d jwknz/pg02

UPDATE
Changing my Dockerfile to contain
CMD ["../gitclone.sh","$LOCATION"] instead of RUN ./gitclone.sh $LOCATION doesn't fix it.

The Dockerfile will build, but the container stops after running the docker run command.

Body:
First off, you have to notice that the Dockerfile is used to build your image (with the docker build command) and docker run is used to start a container from the already build docker image.

You have to define an entrypoint script. This is a script that is executed every time a container is started from the image you've build with the Dockerfile.

Assuming you want to clone a git repo and run apache httpd afterwards you can create a script like this in the same folder where your Dockerfile is. Name it, e.g. gitCloneAndRunHttpd.sh

#!/bin/bash

git clone $LOCATION /app
/usr/local/apache2/bin/apachectl -f /usr/local/apache2/conf/httpd.conf

Then you have to modify your Dockerfile telling docker to copy the script file to your docker image, make it executable, en tell it to run it at container creation:

[...]

COPY ["gitCloneAndRunHttpd.sh", "/gitCloneAndRunHttpd.sh"]
RUN chmod +x /gitCloneAndRunHttpd.sh
ENTRYPOINT ["/gitCloneAndRunHttpd.sh"]

After this you build your docker image with the docker build command and then you can start creating containers from your image.

Every time you start a container from it with docker run -e LOCATION=https://github.com/some-git-repo.url -d your/image, the repo https://github.com/some-git-repo.url will be cloned from within the container to the /app folder and apache httpd will be started.

Note: If you are wondering what is going on in the SO post you mentioned, there the default entrypoint is used (/bin/sh), and /file.sh abc is the argument passed to that entrypoint, therefore the file.sh script is executed.


问:
How to remove a list of accidently deleted databases from Sql Server Management Studio's tree-like list?
I have accidently deleted my database files using Windows Explorer.

Now I want to remove these databases from SQL Server Management Studio' tree-like list.

The following screenshot shows the database names (musics and silverlight) I want to remove.

I attempted to delete them one by one but I got an error for each attempt. The following screenshot just shows my attempt to delete musics:

These orphan names really upsets my eyes and can produce misunderstanding in the future.
Is there any way to remove these?

答: Looks like they are already deleted but just still showing in the Databases tree - did you try to right-click on Databases node and select Refresh?</p>


问:
escape single quotes inside onclick method JSP generated text
I have the following link

${note.getRequiredInfoFieldValue('note-text')} will sometimes have single quotes or double quotes in the text causing errors.
I need to be able to escape the text.

I have the following

which works in escaping the characters but simply putting the text variable into the method does't work. It is empty.

答:
Use

${fn:replace(note.getRequiredInfoFieldValue('note-text'), /\"/g,'\"')}

inside onclick directly.

So that it will replace the single or double quotes with a escape sequence character.

Obviously you need to import jstl lib using:

```<code><%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %>
</code>```

Use

<c:out value="${note.getRequiredInfoFieldValue('note-text')}"/> directly inside onclick.

Use ${fn:escapeXml(note.getRequiredInfoFieldValue('note-text'))}

Third approach is most recommended because you need not to put manual efforts to escape particular symbols.

Body:
Use

${fn:replace(note.getRequiredInfoFieldValue('note-text'), /\"/g,'\"')}

inside onclick directly.

So that it will replace the single or double quotes with a escape sequence character.

Obviously you need to import jstl lib using:

<%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %>

Use

<c:out value="${note.getRequiredInfoFieldValue('note-text')}"/> directly inside onclick.

Use ${fn:escapeXml(note.getRequiredInfoFieldValue('note-text'))}

Third approach is most recommended because you need not to put manual efforts to escape particular symbols.


问:
best way to include header and footer on HTML using any client side framework
Having HTML project want to include header and footer , so it will reduce rework.
Please suggest any good way.

I tried AngularJS with ng-include and below code

```<code>var app = angular.module("arstlApp", []);
app.controller("arstlCtrl", function($scope, $rootScope,$timeout) {
  $rootScope.$on('$includeContentLoaded', function() {
    $timeout(function(){
         _autoload();
    });
  });
});
</code>```

but <ng-include increase number of call JS function.

答:
You specify "any client side framework" but every framework has it's own way of doing this. For angular you could for example look into having a layout page and changing the body content via <ui-view/>.

Or you could handle this via the stateProvider:

```<code>$stateProvider
        .state('test', {
            url: '/test',
            templateUrl: 'views/test.html',
            header: {
                template: '<h1>Header</h1>',
                controller: function($scope) {}
            },
            footer:  {
                template: '<p>Footer</p>',
                controller: function($scope) {}
            }
        })
</code>```

Body:
Having HTML project want to include header and footer , so it will reduce rework.
Please suggest any good way.

I tried AngularJS with ng-include and below code

var app = angular.module("arstlApp", []);
app.controller("arstlCtrl", function($scope, $rootScope,$timeout) {
  $rootScope.$on('$includeContentLoaded', function() {
    $timeout(function(){
         _autoload();
    });
  });
});

but <ng-include increase number of call JS function.

Body:
You specify "any client side framework" but every framework has it's own way of doing this. For angular you could for example look into having a layout page and changing the body content via <ui-view/>.

Or you could handle this via the stateProvider:

$stateProvider
        .state('test', {
            url: '/test',
            templateUrl: 'views/test.html',
            header: {
                template: '<h1>Header</h1>',
                controller: function($scope) {}
            },
            footer:  {
                template: '<p>Footer</p>',
                controller: function($scope) {}
            }
        })


问:
SQL multiple insert with sleep
Is it possible to insert multiple data with delay kind of thing/sleep for a few second?
for example here, Im going to insert the values (1,2) into my user table. Then after 5 seconds, it will proceed to insert value (3,4) into the same table, wait for 5 seconds and finally insert (5,6) into the table.

```<code>INSERT INTO User (col1, col2)
VALUES (1, 2), (3, 4), (5, 6)
</code>```

Any suggestions are really appreciated!

答:
So what I do is create the query by concatenating it like this. But if you want to have multiple inserts you can call that function in a loop and remove this sleep put it in the loop outside the function or you can leave it there if the call is not a thread.

```<code><?php
static function insert_table_db($anArra){
        $dbconn = mysqli_connect(DB_HOST, DB_USER,DB_PASSWORD, DB_DATABASE) or die('MySQL connection failed!' . mysqli_connect_error());
        mysqli_set_charset($dbconn, "utf8");

        $query = "INSERT INTO `table`(`col1`, `col2`, `col3`, `col4`, `col5`) VALUES ";
        $i = 1;
        foreach ($anArray as $item) {
            $query = $query . "(" . $item[0]. "," . $item[1]. "," . $item[2] . "," . $item[3] . ",'" . $item[4] . "')";

            if (count($anArray) == $i){
                $query = $query . ";";
            } else {
                $query = $query . ",";
            }
            $i++;
        }

        // Run query
        if($dbconn->query($query) === true) {
            $dbconn->close();
        } else {
            echo "Database Error: " . $dbconn->error;
            $dbconn->close();
        }
    sleep(5);
}
?>
</code>```

UPDATE: Sorry if some variables don't make sense I stripped it out of a library I have built and there are some extra things that I didn't delete ;D.

Title: SQL multiple insert with sleep

Body:
Is it possible to insert multiple data with delay kind of thing/sleep for a few second?
for example here, Im going to insert the values (1,2) into my user table. Then after 5 seconds, it will proceed to insert value (3,4) into the same table, wait for 5 seconds and finally insert (5,6) into the table.

INSERT INTO User (col1, col2)
VALUES (1, 2), (3, 4), (5, 6)

Any suggestions are really appreciated!

Body:
So what I do is create the query by concatenating it like this. But if you want to have multiple inserts you can call that function in a loop and remove this sleep put it in the loop outside the function or you can leave it there if the call is not a thread.

<?php
static function insert_table_db($anArra){
        $dbconn = mysqli_connect(DB_HOST, DB_USER,DB_PASSWORD, DB_DATABASE) or die('MySQL connection failed!' . mysqli_connect_error());
        mysqli_set_charset($dbconn, "utf8");

        $query = "INSERT INTO `table`(`col1`, `col2`, `col3`, `col4`, `col5`) VALUES ";
        $i = 1;
        foreach ($anArray as $item) {
            $query = $query . "(" . $item[0]. "," . $item[1]. "," . $item[2] . "," . $item[3] . ",'" . $item[4] . "')";

            if (count($anArray) == $i){
                $query = $query . ";";
            } else {
                $query = $query . ",";
            }
            $i++;
        }

        // Run query
        if($dbconn->query($query) === true) {
            $dbconn->close();
        } else {
            echo "Database Error: " . $dbconn->error;
            $dbconn->close();
        }
    sleep(5);
}
?>

UPDATE: Sorry if some variables don't make sense I stripped it out of a library I have built and there are some extra things that I didn't delete ;D.


问:
Python's requests "Missing dependencies for SOCKS support" when using SOCKS5 from Terminal
I'm trying to interact with an API from my Python 2.7 shell using a package that relies on Python's requests. Thing is the remote address is blocked by my network (university library).

So to speak to the API I do the following:

```<code>~$ ssh -D 8080 name@myserver.com
</code>```

And then, in new terminal, in local computer:

```<code>~$ export http_proxy=socks5://127.0.0.1:8080 https_proxy=socks5://127.0.0.1:8080
</code>```

Then I run the program in Python console but fails:

```<code>~$ python
>>> import myscript
>>> id = '1213'
>>> token = 'jd87jd9'
>>> connect(id,token)

File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/sessions.py", line 518, in post
    return self.request('POST', url, data=data, json=json, **kwargs)
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/sessions.py", line 475, in request
    resp = self.send(prep, **send_kwargs)
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/sessions.py", line 585, in send
    r = adapter.send(request, **kwargs)
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/adapters.py", line 370, in send
    conn = self.get_connection(request.url, proxies)
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/adapters.py", line 273, in get_connection
    proxy_manager = self.proxy_manager_for(proxy)
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/adapters.py", line 169, in proxy_manager_for
    **proxy_kwargs
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/adapters.py", line 43, in SOCKSProxyManager
    raise InvalidSchema("Missing dependencies for SOCKS support.")
requests.exceptions.InvalidSchema: Missing dependencies for SOCKS support.
</code>```

This excerpt is from the adapters.py requests module:

```<code>> try:
>     from .packages.urllib3.contrib.socks import SOCKSProxyManager except ImportError:
>     def SOCKSProxyManager(*args, **kwargs):
>         raise InvalidSchema("Missing dependencies for SOCKS support.")
</code>```

Now problem seems to be originated in urllib3's SOCKSProxyManager.

So I read you can use SOCKSProxyManager with SOCKS5 if you have install PySocks or you do a pip install urllib3[socks]

Alas, I tried both PySocks and urllib3 with Socks without any success.

Any idea of another workaround?

EDIT:

I also tried pip install requests[socks] (that's requests 2.10.0 with Socks support) and I am getting this:

```<code>  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/adapters.py", line 467, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: SOCKSHTTPSConnectionPool(host='api-server.com', port=443): Max retries exceeded with url: /auth (Caused by NewConnectionError('<requests.packages.urllib3.contrib.socks.SOCKSHTTPSConnection object at 0x95c7ccc>: Failed to establish a new connection: SOCKS5 proxy server sent invalid data',))
</code>```

答:
This means that requests is using socks as a proxy and that socks is not installed.

Just run
pip install pysocks

Body:
I'm trying to interact with an API from my Python 2.7 shell using a package that relies on Python's requests. Thing is the remote address is blocked by my network (university library).

So to speak to the API I do the following:

~$ ssh -D 8080 name@myserver.com

And then, in new terminal, in local computer:

~$ export http_proxy=socks5://127.0.0.1:8080 https_proxy=socks5://127.0.0.1:8080

Then I run the program in Python console but fails:

~$ python
>>> import myscript
>>> id = '1213'
>>> token = 'jd87jd9'
>>> connect(id,token)

File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/sessions.py", line 518, in post
    return self.request('POST', url, data=data, json=json, **kwargs)
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/sessions.py", line 475, in request
    resp = self.send(prep, **send_kwargs)
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/sessions.py", line 585, in send
    r = adapter.send(request, **kwargs)
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/adapters.py", line 370, in send
    conn = self.get_connection(request.url, proxies)
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/adapters.py", line 273, in get_connection
    proxy_manager = self.proxy_manager_for(proxy)
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/adapters.py", line 169, in proxy_manager_for
    **proxy_kwargs
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/adapters.py", line 43, in SOCKSProxyManager
    raise InvalidSchema("Missing dependencies for SOCKS support.")
requests.exceptions.InvalidSchema: Missing dependencies for SOCKS support.

This excerpt is from the adapters.py requests module:

> try:
>     from .packages.urllib3.contrib.socks import SOCKSProxyManager except ImportError:
>     def SOCKSProxyManager(*args, **kwargs):
>         raise InvalidSchema("Missing dependencies for SOCKS support.")

Now problem seems to be originated in urllib3's SOCKSProxyManager.

So I read you can use SOCKSProxyManager with SOCKS5 if you have install PySocks or you do a pip install urllib3[socks]

Alas, I tried both PySocks and urllib3 with Socks without any success.

Any idea of another workaround?

EDIT:

I also tried pip install requests[socks] (that's requests 2.10.0 with Socks support) and I am getting this:

  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/adapters.py", line 467, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: SOCKSHTTPSConnectionPool(host='api-server.com', port=443): Max retries exceeded with url: /auth (Caused by NewConnectionError('<requests.packages.urllib3.contrib.socks.SOCKSHTTPSConnection object at 0x95c7ccc>: Failed to establish a new connection: SOCKS5 proxy server sent invalid data',))


问:
Is there a quick way to compare two equally formatted tables in SQL?
I would like to make an SQL query to compare two tables with identical columns, both names and types. Each table has a unique key. I want the query to return any rows that contain unequal values. I know could do something like this

```<code>select *
from table_1, table_2
where
table_1.key = table_2.key
and (
 table_1.col1 != table_2.col1 OR
 table_1.col2 != table_2.col2 OR
 ...

)
</code>```

but this would be tedious since there are a large and potentially variable number of columns.

edit

If it helps, I'm using a tsql system.

答:
Verified with SQL Server:

```<code>(select * from table1 except select * from table2)
    union
(select * from table2 except select * from table1);
</code>```

Verified with Oracle:

```<code>(select * from table1 minus (select * from table2))
    union
(select * from table2 minus (select * from table1))
</code>```

Body:
I would like to make an SQL query to compare two tables with identical columns, both names and types. Each table has a unique key. I want the query to return any rows that contain unequal values. I know could do something like this

select *
from table_1, table_2
where
table_1.key = table_2.key
and (
 table_1.col1 != table_2.col1 OR
 table_1.col2 != table_2.col2 OR
 ...

)

but this would be tedious since there are a large and potentially variable number of columns.

edit

If it helps, I'm using a tsql system.

Body:
Verified with SQL Server:

(select * from table1 except select * from table2)
    union
(select * from table2 except select * from table1);

Verified with Oracle:

(select * from table1 minus (select * from table2))
    union
(select * from table2 minus (select * from table1))


问:
PickerView - open the last selected row
I have 2 pickerViews. One of them has his own customPickerViewClass and both aren't in the ViewController.
I've done it to make them talk with the ViewController.
But what I want to do now is, when a row was selected and the title saved in a variable, how can I make it select this row automatically when opening the pickerView again?</p>

答:
So if you save a variable with the selected value you can do the following:

```<code>if let index = array.index(where: { $0 == variable }) {
    picker.selectRow(index, inComponent: 0, animated: false)
}
</code>```

You search for the index in your array source which you use to populate your picker, then you find the the index by searching for the variable which is the one you have saved. Then you select that row in your  picker.

Title: PickerView - open the last selected row

Body:
So if you save a variable with the selected value you can do the following:

if let index = array.index(where: { $0 == variable }) {
    picker.selectRow(index, inComponent: 0, animated: false)
}

You search for the index in your array source which you use to populate your picker, then you find the the index by searching for the variable which is the one you have saved. Then you select that row in your  picker.


问:
Table drops not actually done by Firebird until application closed
I have a .net test application which creates table, uses them, then drops them, many times.

When I run this application against a Firebird 3.0.2 database with Firebird ADO.Net Data Provider 5.9.1, it fails at soon as it has to create a table with the same name than a previously dropped one: table does already exist!

Restarting the application dodge the trouble, but I do not want to restart it after each test.

This question is very similar but is hanging at the drop instead, and use directly the Firebird isql tool instead of a .Net application.

Is there a way to actually drop the tables in Firebird without restarting the application?

This application tests many other databases, without this issue: SQL-Server, SQL-Server Compact Edition, MySql, SQLite, Oracle, PostgreSQL.

Here is a MCVE failing for Firebird. Replace the two first lines with suitable code for having a connection string. All other code is just Firebird ADO.Net data provider and NUnit. It does not fail exactly as my actual application, but I think it is the same underlying trouble.

```<code>[Test]
public void CreateSelectDrop()
{
    var cfg = TestConfigurationHelper.GetDefaultConfiguration();
    var cnxStr = cfg.Properties[Environment.ConnectionString];
    using (var cnx = new FbConnection(cnxStr))
    {
        cnx.Open();
        using (var tran = cnx.BeginTransaction())
        {
            using (var cmd = cnx.CreateCommand())
            {
                cmd.Transaction = tran;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "create table test (id int not null primary key)";
                cmd.ExecuteNonQuery();
            }
            tran.Commit();
        }
    }

    using (var cnx = new FbConnection(cnxStr))
    {
        cnx.Open();
        using (var tran = cnx.BeginTransaction())
        {
            using (var cmd = cnx.CreateCommand())
            {
                cmd.Transaction = tran;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "insert into test (id) values (1)";
                cmd.ExecuteNonQuery();
            }
            tran.Commit();
        }
    }

    using (var cnx = new FbConnection(cnxStr))
    {
        cnx.Open();
        using (var tran = cnx.BeginTransaction())
        {
            using (var cmd = cnx.CreateCommand())
            {
                cmd.Transaction = tran;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "select id from test";
                using (var reader = cmd.ExecuteReader())
                {
                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(1, reader.GetInt32(0));
                    Assert.IsFalse(reader.Read());
                }
            }
            tran.Commit();
        }
    }

    using (var cnx = new FbConnection(cnxStr))
    {
        cnx.Open();
        using (var tran = cnx.BeginTransaction())
        {
            using (var cmd = cnx.CreateCommand())
            {
                cmd.Transaction = tran;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "delete from test";
                cmd.ExecuteNonQuery();
            }
            tran.Commit();
        }
    }

    using (var cnx = new FbConnection(cnxStr))
    {
        cnx.Open();
        using (var tran = cnx.BeginTransaction())
        {
            using (var cmd = cnx.CreateCommand())
            {
                cmd.Transaction = tran;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "drop table test";
                cmd.ExecuteNonQuery();
            }
            tran.Commit();
        }
    }
}
</code>```

Only selecting from the table was not enough. The trouble appeared only after I have added the delete to the test. It fails at the last transaction commit, the one of the drop, with message:

```<code>FirebirdSql.Data.FirebirdClient.FbException : lock conflict on no wait transaction
unsuccessful metadata update
object TABLE "TEST" is in use
  ----> FirebirdSql.Data.Common.IscException : lock conflict on no wait transaction
unsuccessful metadata update
object TABLE "TEST" is in use
   at FirebirdSql.Data.FirebirdClient.FbTransaction.Commit()
   at NHibernate.Test.DialectTest.FirebirdDialectFixture.CreateSelectDrop()
</code>```

According to Nathan Brown in a Github discussion, this trouble seems bounded to Firebird ADO.Net Data provider only. He has narrowed it to switching from its 2.7.7 version to 3.0.0.

答:
It appears the table drops are delayed until the connections having used them are actually closed, not only returned to the pool. Clearing the connection pool causes those delayed drops to be actually done.

So adding something like following code before table drops solves this issue in my case:

```<code>using (var connection = GetConnection())
{
    FbConnection.ClearPool(connection);
}
</code>```

This solution was found here in an isolated test among more than 5 000.

It looks like there is another option, calling FbConnection.ClearAllPool() instead. Although I have not checked it, the former is likely to clear only the connection pool for supplied connection connection-string, while the later clears the pool of all connections, regardless of their connection string.

Since it is a test application with some generic logic and also some specificity, the code I will actually use as a solution will be:

```<code>// Firebird will pool each connection created during the test and will
// marked as used any table referenced by queries. It will delays those
// tables drop until connections are actually closed.
// This results in other tests failing when they try to create tables with
// same name.
// By clearing the connection pool the tables will get dropped. This is done
// by the following code.
// Moved from NH1908 test case, contributed by Amro El-Fakharany.
var clearConnection = Sfi.ConnectionProvider.GetConnection();
try
{
    var fbConnectionType = clearConnection.GetType();
    var clearPool = fbConnectionType.GetMethod("ClearPool");
    clearPool.Invoke(null, new object[] {clearConnection});
}
finally
{
    Sfi.ConnectionProvider.CloseConnection(clearConnection);
}
</code>```

Body:
I have a .net test application which creates table, uses them, then drops them, many times.

When I run this application against a Firebird 3.0.2 database with Firebird ADO.Net Data Provider 5.9.1, it fails at soon as it has to create a table with the same name than a previously dropped one: table does already exist!

Restarting the application dodge the trouble, but I do not want to restart it after each test.

This question is very similar but is hanging at the drop instead, and use directly the Firebird isql tool instead of a .Net application.

Is there a way to actually drop the tables in Firebird without restarting the application?

This application tests many other databases, without this issue: SQL-Server, SQL-Server Compact Edition, MySql, SQLite, Oracle, PostgreSQL.

Here is a MCVE failing for Firebird. Replace the two first lines with suitable code for having a connection string. All other code is just Firebird ADO.Net data provider and NUnit. It does not fail exactly as my actual application, but I think it is the same underlying trouble.

[Test]
public void CreateSelectDrop()
{
    var cfg = TestConfigurationHelper.GetDefaultConfiguration();
    var cnxStr = cfg.Properties[Environment.ConnectionString];
    using (var cnx = new FbConnection(cnxStr))
    {
        cnx.Open();
        using (var tran = cnx.BeginTransaction())
        {
            using (var cmd = cnx.CreateCommand())
            {
                cmd.Transaction = tran;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "create table test (id int not null primary key)";
                cmd.ExecuteNonQuery();
            }
            tran.Commit();
        }
    }

    using (var cnx = new FbConnection(cnxStr))
    {
        cnx.Open();
        using (var tran = cnx.BeginTransaction())
        {
            using (var cmd = cnx.CreateCommand())
            {
                cmd.Transaction = tran;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "insert into test (id) values (1)";
                cmd.ExecuteNonQuery();
            }
            tran.Commit();
        }
    }

    using (var cnx = new FbConnection(cnxStr))
    {
        cnx.Open();
        using (var tran = cnx.BeginTransaction())
        {
            using (var cmd = cnx.CreateCommand())
            {
                cmd.Transaction = tran;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "select id from test";
                using (var reader = cmd.ExecuteReader())
                {
                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(1, reader.GetInt32(0));
                    Assert.IsFalse(reader.Read());
                }
            }
            tran.Commit();
        }
    }

    using (var cnx = new FbConnection(cnxStr))
    {
        cnx.Open();
        using (var tran = cnx.BeginTransaction())
        {
            using (var cmd = cnx.CreateCommand())
            {
                cmd.Transaction = tran;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "delete from test";
                cmd.ExecuteNonQuery();
            }
            tran.Commit();
        }
    }

    using (var cnx = new FbConnection(cnxStr))
    {
        cnx.Open();
        using (var tran = cnx.BeginTransaction())
        {
            using (var cmd = cnx.CreateCommand())
            {
                cmd.Transaction = tran;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "drop table test";
                cmd.ExecuteNonQuery();
            }
            tran.Commit();
        }
    }
}

Only selecting from the table was not enough. The trouble appeared only after I have added the delete to the test. It fails at the last transaction commit, the one of the drop, with message:

FirebirdSql.Data.FirebirdClient.FbException : lock conflict on no wait transaction
unsuccessful metadata update
object TABLE "TEST" is in use
  ----> FirebirdSql.Data.Common.IscException : lock conflict on no wait transaction
unsuccessful metadata update
object TABLE "TEST" is in use
   at FirebirdSql.Data.FirebirdClient.FbTransaction.Commit()
   at NHibernate.Test.DialectTest.FirebirdDialectFixture.CreateSelectDrop()

According to Nathan Brown in a Github discussion, this trouble seems bounded to Firebird ADO.Net Data provider only. He has narrowed it to switching from its 2.7.7 version to 3.0.0.

Body:
It appears the table drops are delayed until the connections having used them are actually closed, not only returned to the pool. Clearing the connection pool causes those delayed drops to be actually done.

So adding something like following code before table drops solves this issue in my case:

using (var connection = GetConnection())
{
    FbConnection.ClearPool(connection);
}

This solution was found here in an isolated test among more than 5 000.

It looks like there is another option, calling FbConnection.ClearAllPool() instead. Although I have not checked it, the former is likely to clear only the connection pool for supplied connection connection-string, while the later clears the pool of all connections, regardless of their connection string.

Since it is a test application with some generic logic and also some specificity, the code I will actually use as a solution will be:

// Firebird will pool each connection created during the test and will
// marked as used any table referenced by queries. It will delays those
// tables drop until connections are actually closed.
// This results in other tests failing when they try to create tables with
// same name.
// By clearing the connection pool the tables will get dropped. This is done
// by the following code.
// Moved from NH1908 test case, contributed by Amro El-Fakharany.
var clearConnection = Sfi.ConnectionProvider.GetConnection();
try
{
    var fbConnectionType = clearConnection.GetType();
    var clearPool = fbConnectionType.GetMethod("ClearPool");
    clearPool.Invoke(null, new object[] {clearConnection});
}
finally
{
    Sfi.ConnectionProvider.CloseConnection(clearConnection);
}


问:
in python is there a better way to apply a list of functions to a dictionary
Is there a better way to iteratively apply a list of functions to a dictionary? Here is an example of what I want to do.  But this uses recursion.

```<code>def func1(h: dict):
    h['foo']=10
    return(h)

def func2(h: dict):
    h['bar']=100
    return(h)

def func3(h: dict):
    h['baz']=h['foo']+h['bar']
    return(h)

func3(func2(func1({'firstElement':'good'})))
</code>```

Produces expected output:

```<code>{'bar': 100, 'baz': 110, 'firstElement': 'good', 'foo': 10}
</code>```

I want to provide the functions as a array and produce the same output.  Here is what I have tried and works:

```<code>def recApply(flist, h=None):
    """
    Helper Apply the list of functions iteratively over the dictionary passed
    :obj: function list each will be applied to the dictionary sequentially.
    """
    #if no dictionary passed, then set the dictionary.
    if(h == None):
        h = {}

    #iteratively call functions with dictionary as a passed parameter and returning a derived dictionary
    for f in flist:
        h = f(h)

    return(h)

flist = [func1,func2,func3]
recApply(flist,{'firstElement':'good'})
</code>```

This produces the desired output:

```<code>{'bar': 100, 'baz': 110, 'firstElement': 'good', 'foo': 10}
</code>```

Is there a way to do this that is more readable, removes the recApply function and hopefully minimizes dictionary copies?

答:
You don't need to return your dictionaries and re-assign references - mutable types are passed by reference so:

```<code>def func1(h):
    h['foo'] = 10

def func2(h):
    h['bar'] = 100

def func3(h):
    h['baz'] = h['foo'] + h['bar']

start_dict = {'firstElement': 'good'}

for f in (func1, func2, func3):
    f(start_dict)

print(start_dict)
# {'firstElement': 'good', 'baz': 110, 'bar': 100, 'foo': 10}
</code>```

would to perfectly fine.

Body:
Is there a better way to iteratively apply a list of functions to a dictionary? Here is an example of what I want to do.  But this uses recursion.

def func1(h: dict):
    h['foo']=10
    return(h)

def func2(h: dict):
    h['bar']=100
    return(h)

def func3(h: dict):
    h['baz']=h['foo']+h['bar']
    return(h)

func3(func2(func1({'firstElement':'good'})))

Produces expected output:

{'bar': 100, 'baz': 110, 'firstElement': 'good', 'foo': 10}

I want to provide the functions as a array and produce the same output.  Here is what I have tried and works:

def recApply(flist, h=None):
    """
    Helper Apply the list of functions iteratively over the dictionary passed
    :obj: function list each will be applied to the dictionary sequentially.
    """
    #if no dictionary passed, then set the dictionary.
    if(h == None):
        h = {}

    #iteratively call functions with dictionary as a passed parameter and returning a derived dictionary
    for f in flist:
        h = f(h)

    return(h)

flist = [func1,func2,func3]
recApply(flist,{'firstElement':'good'})

This produces the desired output:

{'bar': 100, 'baz': 110, 'firstElement': 'good', 'foo': 10}

Is there a way to do this that is more readable, removes the recApply function and hopefully minimizes dictionary copies?

Body:
You don't need to return your dictionaries and re-assign references - mutable types are passed by reference so:

def func1(h):
    h['foo'] = 10

def func2(h):
    h['bar'] = 100

def func3(h):
    h['baz'] = h['foo'] + h['bar']

start_dict = {'firstElement': 'good'}

for f in (func1, func2, func3):
    f(start_dict)

print(start_dict)
# {'firstElement': 'good', 'baz': 110, 'bar': 100, 'foo': 10}

would to perfectly fine.


答: If it's led into a dead-end, it shouldn't be a problem. Your A* algorithm should simply find the next non-blocked node with the lowest heuristic and start over.

Title: A* Search Algorithm gets stuck

Body:
I am trying to implement an A* Search algorithm. For now I am just trying to find a good path through an environment littered with walls. The walls are randomly generated, and in some cases my path gets "stuck". If the search encounters a wall in front of it, and to all of its sides (except the one that led it into this mess), it stops.
Is there something I can do to prevent this? I am using a "as the crow flies" point system for my H value, which ignores the walls and just estimates how far it will take to get to the destination. This sometimes leads it into this trap.

Thanks.


答:
Your results are correct.  Think of a FULL OUTER JOIN like this:

It returns all rows from an INNER JOIN on the two tables.

It returns all rows from the first table with no matches in the second.

It returns all rows from the second table with no matches in the first.

In your data example, all rows in the second table have matches in the first (that is, Customer_Id always matches a valid customer).  Only the first two bullet points describe the result set.

I have no idea where their result set is coming from.  My best guess is that it comes from the MySQL code.  That code is not correct and does not approximate a FULL OUTER JOIN in any way.

Besides the obvious recommendation of finding a better tutorial, this is also a really bad example.  In a properly created database, FULL OUTER JOIN is almost never necessary.  The keys in one table should match the keys in the reference table.  That is, you should never have a non-NULL Customer_Id that is not valid in the Customers table.

Title: how FULL JOIN works?

Body:
Customer table:

+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
+----+----------+-----+-----------+----------+

Orders table:

+-----+---------------------+-------------+--------+
|OID  | DATE                | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 |           3 |   3000 |
| 100 | 2009-10-08 00:00:00 |           3 |   1500 |
| 101 | 2009-11-20 00:00:00 |           2 |   1560 |
| 103 | 2008-05-20 00:00:00 |           4 |   2060 |
+-----+---------------------+-------------+--------+

Query:

   SELECT  ID, NAME, AMOUNT, DATE
   FROM CUSTOMERS
   FULL OUTER JOIN ORDERS
   ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

According to TutorialsPoint, the output should be this:

+------+----------+--------+---------------------+
| ID   | NAME     | AMOUNT | DATE                |
+------+----------+--------+---------------------+
|    1 | Ramesh   |   NULL | NULL                |
|    2 | Khilan   |   1560 | 2009-11-20 00:00:00 |
|    3 | kaushik  |   3000 | 2009-10-08 00:00:00 |
|    3 | kaushik  |   1500 | 2009-10-08 00:00:00 |
|    4 | Chaitali |   2060 | 2008-05-20 00:00:00 |
|    5 | Hardik   |   NULL | NULL                |
|    6 | Komal    |   NULL | NULL                |
|    7 | Muffy    |   NULL | NULL                |
|    3 | kaushik  |   3000 | 2009-10-08 00:00:00 |
|    3 | kaushik  |   1500 | 2009-10-08 00:00:00 |
|    2 | Khilan   |   1560 | 2009-11-20 00:00:00 |
|    4 | Chaitali |   2060 | 2008-05-20 00:00:00 |
+------+----------+--------+---------------------+

This is my real output instead:

╔════╦══════════╦════════╦═════════════════════════╗
║ ID ║   NAME   ║ AMOUNT ║          DATE           ║
╠════╬══════════╬════════╬═════════════════════════╣
║  1 ║ Ramesh   ║ NULL   ║ NULL                    ║
║  2 ║ Khilan   ║ 1560   ║ 2009-11-20 00:00:00.000 ║
║  3 ║ kaushik  ║ 1500   ║ 2009-10-08 00:00:00.000 ║
║  3 ║ kaushik  ║ 3000   ║ 2009-10-08 00:00:00.000 ║
║  4 ║ Chaitali ║ 2060   ║ 2008-05-20 00:00:00.000 ║
║  5 ║ Hardik   ║ NULL   ║ NULL                    ║
║  6 ║ Komal    ║ NULL   ║ NULL                    ║
║  7 ║ Muffy    ║ NULL   ║ NULL                    ║
╚════╩══════════╩════════╩═════════════════════════╝

So, I want to understand how the Full join exactly works as I'm not getting the same results as Tutorilaspoint site. I also want to know why the Full join query I posted above will have the exact same results as a LEFT JOIN.


答:
try this i may <Menu-Header></Menu-Header> on the every page for header

Or

also this for footer

Title: best way to include header and footer on HTML using any client side framework

Body:
try this i may <Menu-Header></Menu-Header> on the every page for header

Or

<header ng-include="'includes/header.html'"></header>

also this for footer


问:
how to query key Angularfire2
How can i query the users node. i tried using

```<code>            return this.db.list('groups/', {
              query: {
                orderByChild: 'users',
                equalTo: uid
              }
            });
</code>```

答:
Your query is definitely not going to work. There are a few solutions that come to mind:

1 - if you have the groupUid:

```<code>groupUid = "asdasdafd";
return this.db.list('groups/'+this.groupUid+'/users', {
          query: {
            equalTo: uid
          }
        });
</code>```

or something like this:

```<code>// import 'rxjs/add/operator/filter';
groupUid = "asdasdafd";
return this.db.list('groups/'+this.groupUid+'/users')
    .filter(item => item==uid);
</code>```

2 - if you don't have the groupUid:

you need to receive the this.db.object('groups/') object , and after that iterate with simple loop(over all users) inside loop(over all groups) to search for uid you need.

something like:

```<code>for(var prop in groups){
  for(var j=0;j<prop.users.length;j++){
    //search the uid you need
  }
}
</code>```

hope its helped you.

Title: how to query key Angularfire2

Body:
How can i query the users node. i tried using

            return this.db.list('groups/', {
              query: {
                orderByChild: 'users',
                equalTo: uid
              }
            });

Body:
Your query is definitely not going to work. There are a few solutions that come to mind:

1 - if you have the groupUid:

groupUid = "asdasdafd";
return this.db.list('groups/'+this.groupUid+'/users', {
          query: {
            equalTo: uid
          }
        });

or something like this:

// import 'rxjs/add/operator/filter';
groupUid = "asdasdafd";
return this.db.list('groups/'+this.groupUid+'/users')
    .filter(item => item==uid);

2 - if you don't have the groupUid:

you need to receive the this.db.object('groups/') object , and after that iterate with simple loop(over all users) inside loop(over all groups) to search for uid you need.

something like:

for(var prop in groups){
  for(var j=0;j<prop.users.length;j++){
    //search the uid you need
  }
}

hope its helped you.