问:
Controls not aligning correctly even after setting width via bootstrap
I am creating a UI that would contain four controls on each row. It would have a label and control followed by another label and control. If you see in my markup i have set col-md-2 for label and col-md-4 for the control but the second control seems to wrap and go on the next line. I am not sure why it is doing this because in total it is width 12. If you click the Edit button on the top right corner , you could toggle to see the controls

I have also created a stackblitz to replicate the issue

https://angular-lmck2c.stackblitz.io

Markup

```<code><style>
    label {
        margin-left: 0.5rem;
        vertical-align: middle
    }

    .panel-heading {
        color: black;
        /* background-color: #F5F7F7; */
        border-color: #ddd;
        overflow: hidden;
        padding-top: 5px !important;
        padding-bottom: 5px !important;
    }

    .panel-heading .left-label {
        display: inline-block;
        padding-top: 5px !important;

    }
    .panel-heading label {
        margin-bottom: 0px !important;
    }
</style>

<div class="card" style="height: 100%; width: 100%;">
    <div class="card-header panel-heading">
        <span class="left-label" style="font-size: 18px; font-weight: bold; ">Fund Terms</span>
        <div class="pull-right" style="padding-right:10px; display: inline-block; vertical-align:middle">
            <label style="text-align: center; vertical-align:middle" class="btn btn-primary"
                [ngClass]="{'btn-primary': EditMode, 'btn-default': !EditMode }"><input type="checkbox"
                    [(ngModel)]="EditMode" class="hidden" />Edit Mode</label>

        </div>
    </div>

    <div class="card-body">

            <div class="form-group row" style="width: 100%;">

                <label for="inputName" class="col-md-2  col-form-label modal-label">Name</label>
                <div class="col-md-4">
                    <div *ngIf="!EditMode">Test Name</div>
                    <input *ngIf="EditMode" kendoTextBox [readonly]="false" class="form-control form-control-sm"
                        />
                </div>

                <label for="inputOffice" class="col-md-2 col-form-label ">Side Letter Agreement</label>
                <div class="col-md-4">
                    <div *ngIf="!EditMode">Test</div>
                    <label *ngIf="EditMode" style="font-size: 13px;font-weight: normal;cursor: pointer">
                        <input type="checkbox" style="width: 13px; height: 13px;" />
                        Yes </label>

                </div>

            </div>

            <div class="form-group row">
                <label for="inputTitle" class="col-md-2  col-form-label ">Vehicle Type</label>
                <div class="col-md-4">
                    <div *ngIf="!EditMode">Test Vehicle Type</div>
                    <kendo-dropdownlist *ngIf="EditMode" style="width:100%" class="form-control form-control-sm"
                        [filterable]="false" textField="NAME" [valuePrimitive]="true" valueField="ID">
                    </kendo-dropdownlist>
                </div>

                <label for="inputEmail" class="col-md-2  col-form-label ">Side Letter Details</label>
                <div class="col-md-4">
                    <div *ngIf="!EditMode">Test</div>
                    <textarea *ngIf="EditMode" kendoTextArea></textarea>
                </div>
                <div class="col-md-4">

                </div>
            </div>

            <div class="form-group row">

                <label for="inputEmail" class="col-md-2  col-form-label ">Investment Manager (Firm)</label>
                <div class="col-md-4">
                    <div *ngIf="!EditMode">Test</div>
                    <input *ngIf="EditMode" kendoTextBox [readonly]="false" class="form-control form-control-sm" />
                </div>

                <label for="inputTitle" class="col-md-2  col-form-label ">Plan Asset Fund</label>
                <div class="col-md-4">
                    <div *ngIf="!EditMode">Test Asset Fund</div>
                    <label style="font-size: 13px;font-weight: normal;cursor: pointer">
                        <input type="checkbox" style="width: 13px; height: 13px;" />
                        Yes </label>
                </div>

            </div>

            <div class="form-group row">

                <label for="inputEmail" class="col-md-2  col-form-label ">Investment Manager (Firm)</label>
                <div class="col-md-4">
                    <div *ngIf="!EditMode">Test</div>
                    <input *ngIf="EditMode" kendoTextBox [readonly]="false" class="form-control form-control-sm" />
                </div>

            </div>

            <div class="form-group row">

                <label for="inputEmail" class="col-md-2  col-form-label ">NAV Reporting Cycle</label>
                <div class="col-md-4">
                    <div *ngIf="!EditMode">Test</div>
                    <kendo-dropdownlist *ngIf="EditMode" style="width:100%" class="form-control form-control-sm"
                        [filterable]="false" textField="NAME" [valuePrimitive]="true" valueField="ID">
                    </kendo-dropdownlist>
                </div>

            </div>

            <div class="form-group row">

                <label for="inputName" class="col-md-2  col-form-label ">Fund Currency</label>
                <div class="col-sm-4">
                    <div>Test</div>
                </div>

            </div>

            <div class="form-group row">

                <label for="inputName" class="col-md-2  col-form-label ">Audit Year End</label>
                <div class="col-sm-4">
                    <div>Test</div>
                </div>

            </div>

        <div class="btn-toolbar" style="padding-top:40px;">

            <span *ngIf="EditMode"><button type="button" class="btn btn-primary btn-view-all btn mr-3"
                    (click)="saveManager()">Save</button>

            </span>

        </div>
    </div>
</div>
</code>```

Body:
I am creating a UI that would contain four controls on each row. It would have a label and control followed by another label and control. If you see in my markup i have set col-md-2 for label and col-md-4 for the control but the second control seems to wrap and go on the next line. I am not sure why it is doing this because in total it is width 12. If you click the Edit button on the top right corner , you could toggle to see the controls

I have also created a stackblitz to replicate the issue

https://angular-lmck2c.stackblitz.io

Markup

        Fund Terms

            <input type="checkbox"
                    [(ngModel)]="EditMode" class="hidden" />Edit Mode

                Name

Test Name

                    <input *ngIf="EditMode" kendoTextBox [readonly]="false" class="form-control form-control-sm"
                        />

                Side Letter Agreement

Test

                        <input type="checkbox" style="width: 13px; height: 13px;" />
                        Yes

                Vehicle Type

Test Vehicle Type

                    <kendo-dropdownlist *ngIf="EditMode" style="width:100%" class="form-control form-control-sm"
                        [filterable]="false" textField="NAME" [valuePrimitive]="true" valueField="ID">
                    </kendo-dropdownlist>

                Side Letter Details

Test

                    <textarea *ngIf="EditMode" kendoTextArea></textarea>

                Investment Manager (Firm)

Test

                    <input *ngIf="EditMode" kendoTextBox [readonly]="false" class="form-control form-control-sm" />

                Plan Asset Fund

Test Asset Fund

                        <input type="checkbox" style="width: 13px; height: 13px;" />
                        Yes

                Investment Manager (Firm)

Test

                    <input *ngIf="EditMode" kendoTextBox [readonly]="false" class="form-control form-control-sm" />

                NAV Reporting Cycle

Test

                    <kendo-dropdownlist *ngIf="EditMode" style="width:100%" class="form-control form-control-sm"
                        [filterable]="false" textField="NAME" [valuePrimitive]="true" valueField="ID">
                    </kendo-dropdownlist>

                Fund Currency

Test

                Audit Year End

Test

            <button type="button" class="btn btn-primary btn-view-all btn mr-3"
                    (click)="saveManager()">Save</button>

Body:
I think the answer is because your labels have a margin-left. If you take that out, the elements should all fit on one row.

Generally, when items don't fit in the Bootstrap rows, my first check is always to see if there's extra margins or padding somewhere there shouldn't be.

If you do need that extra spacing before the labels, try wrapping them in a containing div, and adding the .col-* class on that wrap instead. Then you can try adding the extra spacing to the label.

<div class="col-md-4">
    <label></label>
</div>


来源: stackexchange

问:
Create a text file based on the folder and the file name
```<code>I have 10 folders (C:\Import)
Folder1
Folder2
.
.
Folder10
</code>```

Each folder have some .txt and .html files.

```<code>Let me take example of Folder1 having 3 documents

file.txt
file2.html
file3.txt

files in it.
</code>```

I need script to read the folder and create a txt file in below format.

Folder name 'separator' file name without extension 'separator' filename with extension

```<code>So output text file should be :

Folder1:file:file.txt
Folder1:file2:file2.html
Folder1:file3:file3.txt
</code>```

and Move html, txt files and newly create text file too C:\Output.

This has to be repeated for all the 10 folders and all the corresponding files and created text file should be dropped to same C:\Output

Tried below :

1:

```<code>  foreach (string file in Directory.GetFiles("C:\\Import\\", "*.html", SearchOption.AllDirectories))
    {
        string contents = File.ReadAllText(file);
    }
</code>```

2:

```<code> public static List<string> AllFilesInFolder(string folder)
        {
            var result = new List<string>();

            foreach (string f in Directory.GetFiles(folder))
            {
                result.Add(f);
            }

            foreach (string d in Directory.GetDirectories(folder))
            {
                result.AddRange(AllFilesInFolder(d));
            }

            return result;
        }
</code>```

答:
I would suggest you to write PowerShell script. The file manipulation is much easier in powershell, and you can always use .NET libriaries.

Please, take a look at this link, it's Microsoft doc about "Working with Files and Folders" using PowerShell.

But if you don't want to use PowerShell, you can do something like that:

```<code>using System;
using System.IO;
using System.Text;

namespace ConsoleApp1
{
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("APP START");

        string inputDirectory = @"C:\Import\";
        string outputDirectory = @"C:\Output\";

        FileStream stream = File.Create(outputDirectory + "report.txt");

        string [] folders = Directory.GetDirectories(inputDirectory);

        foreach(String path in folders)
        {
            Directory.CreateDirectory(path.Replace(inputDirectory, outputDirectory));
            string[] files = Directory.GetFiles(path);

            foreach (String file in files)
            {
                String record = ConvertPathToReportFormat(file);
                stream.Write(Encoding.UTF8.GetBytes(record), 0, record.Length);
                File.Copy(file, file.Replace(inputDirectory, outputDirectory));
            }
        }
        stream.Close();

        Console.WriteLine("DONE");
        Console.ReadKey();
    }

    private static String ConvertPathToReportFormat(string path)
    {
        string [] splitedPath = path.Split('\\');
        string[] splitedName = splitedPath[splitedPath.Length - 1].Split('.');

        String folder = splitedPath[splitedPath.Length - 2];
        String name = splitedName[0];
        String extension = splitedName[1];

        return String.Format("{0}:{1}:{2}.{3}\n", folder, name, name, extension);
    }
}
}
</code>```

This little program copy files from one directory to another, and generates report file (report.txt) in following format:

```<code>Folder1:File:File.html
Folder1:File:File.txt
Folder1:File2:File2.html
Folder1:File2:File2.txt
Folder1:File3:File3.html
Folder1:File3:File3.txt
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have 10 folders (C:\Import)
Folder1
Folder2
.
.
Folder10

Each folder have some .txt and .html files.

Let me take example of Folder1 having 3 documents

file.txt
file2.html
file3.txt

files in it.

I need script to read the folder and create a txt file in below format.

Folder name 'separator' file name without extension 'separator' filename with extension

So output text file should be :

Folder1:file:file.txt
Folder1:file2:file2.html
Folder1:file3:file3.txt

and Move html, txt files and newly create text file too C:\Output.

This has to be repeated for all the 10 folders and all the corresponding files and created text file should be dropped to same C:\Output

Tried below :

1:

  foreach (string file in Directory.GetFiles("C:\\Import\\", "*.html", SearchOption.AllDirectories))
    {
        string contents = File.ReadAllText(file);
    }

2:

 public static List<string> AllFilesInFolder(string folder)
        {
            var result = new List<string>();

            foreach (string f in Directory.GetFiles(folder))
            {
                result.Add(f);
            }

            foreach (string d in Directory.GetDirectories(folder))
            {
                result.AddRange(AllFilesInFolder(d));
            }

            return result;
        }

Body:
I would suggest you to write PowerShell script. The file manipulation is much easier in powershell, and you can always use .NET libriaries.

Please, take a look at this link, it's Microsoft doc about "Working with Files and Folders" using PowerShell.

But if you don't want to use PowerShell, you can do something like that:

using System;
using System.IO;
using System.Text;

namespace ConsoleApp1
{
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("APP START");

        string inputDirectory = @"C:\Import\";
        string outputDirectory = @"C:\Output\";

        FileStream stream = File.Create(outputDirectory + "report.txt");

        string [] folders = Directory.GetDirectories(inputDirectory);

        foreach(String path in folders)
        {
            Directory.CreateDirectory(path.Replace(inputDirectory, outputDirectory));
            string[] files = Directory.GetFiles(path);

            foreach (String file in files)
            {
                String record = ConvertPathToReportFormat(file);
                stream.Write(Encoding.UTF8.GetBytes(record), 0, record.Length);
                File.Copy(file, file.Replace(inputDirectory, outputDirectory));
            }
        }
        stream.Close();

        Console.WriteLine("DONE");
        Console.ReadKey();
    }

    private static String ConvertPathToReportFormat(string path)
    {
        string [] splitedPath = path.Split('\\');
        string[] splitedName = splitedPath[splitedPath.Length - 1].Split('.');

        String folder = splitedPath[splitedPath.Length - 2];
        String name = splitedName[0];
        String extension = splitedName[1];

        return String.Format("{0}:{1}:{2}.{3}\n", folder, name, name, extension);
    }
}
}

This little program copy files from one directory to another, and generates report file (report.txt) in following format:

Folder1:File:File.html
Folder1:File:File.txt
Folder1:File2:File2.html
Folder1:File2:File2.txt
Folder1:File3:File3.html
Folder1:File3:File3.txt


问:
Extract value inside square brackets within another square bracket based on key
I have a data like below from where I need to extract data by key.

```<code>string filter=[[LUB,=,COMMERCIAL],AND,[Pgm,=,PRIVATE],AND,[Regn,=,Rasna],AND,[Month,=,06],AND,[Year,=,2018],AND,[Bywhat,=,M]]
</code>```

I checked similar cases and able to get below code only which is not giving results based on key

I have tried

```<code>Regex.Match(filter, @"\[(.*?)\]")
</code>```

if I gives Regn, I need to get Rasna

and if I gives LUB, it should give COMMERCIAL and like that

答:
Try following :</p>

```<code>            string filter="[[LUB,=,COMMERCIAL],AND,[Pgm,=,PRIVATE],AND,[Regn,=,Rasna],AND,[Month,=,06],AND,[Year,=,2018],AND,[Bywhat,=,M]]";

            string pattern = @"\[(?'key'\w+),=,(?'value'[^\]]+)";

            MatchCollection matches = Regex.Matches(filter, pattern);

            foreach (Match match in matches.Cast<Match>())
            {
                Console.WriteLine("Key : '{0}', Value : '{1}'", match.Groups["key"].Value, match.Groups["value"].Value);
            }
            Console.ReadLine();
            Dictionary<string, string> dict = matches.Cast<Match>().GroupBy(x => x.Groups["key"].Value, y => y.Groups["value"].Value)
               .ToDictionary(x => x.Key, y => y.FirstOrDefault());
</code>```

Body:
I have a data like below from where I need to extract data by key.

string filter=[[LUB,=,COMMERCIAL],AND,[Pgm,=,PRIVATE],AND,[Regn,=,Rasna],AND,[Month,=,06],AND,[Year,=,2018],AND,[Bywhat,=,M]]

I checked similar cases and able to get below code only which is not giving results based on key

I have tried

Regex.Match(filter, @"\[(.*?)\]")

if I gives Regn, I need to get Rasna

and if I gives LUB, it should give COMMERCIAL and like that

Body:
Try following :

            string filter="[[LUB,=,COMMERCIAL],AND,[Pgm,=,PRIVATE],AND,[Regn,=,Rasna],AND,[Month,=,06],AND,[Year,=,2018],AND,[Bywhat,=,M]]";

            string pattern = @"\[(?'key'\w+),=,(?'value'[^\]]+)";

            MatchCollection matches = Regex.Matches(filter, pattern);

            foreach (Match match in matches.Cast<Match>())
            {
                Console.WriteLine("Key : '{0}', Value : '{1}'", match.Groups["key"].Value, match.Groups["value"].Value);
            }
            Console.ReadLine();
            Dictionary<string, string> dict = matches.Cast<Match>().GroupBy(x => x.Groups["key"].Value, y => y.Groups["value"].Value)
               .ToDictionary(x => x.Key, y => y.FirstOrDefault());


问:
Changing the size of a scrollbar in tkinter(using grid layout)
I'm making a Tkinter GUI that allows you to query a database and will display results in a scrollable frame. However, when you produce the results the scrollbar will not adjust to match the new size of the frame. How can I get the scrollbar to be able to display all of the results? I've put together a quick and dirty version of the code to demonstrate the problem I'm having.

```<code>import tkinter as tk

def Lookup():
    list = frame_buttons.grid_slaves()
    for l in list:
        l.destroy()
    for x in range(1000):
        tk.Label(frame_buttons, text="test", background="white").grid(row=x)

root = tk.Tk()
root.grid_rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)

frame_main = tk.Frame(root, bg="white")
frame_main.grid(row = 0,sticky='news')
frame_input = tk.Frame(frame_main, background = "white")
frame_input.grid(row=0, column=0, pady=(5, 0), sticky='nw')

tk.Button(frame_input, text="Search", fg="black", background = "grey",command=Lookup).grid(row=3, column=0,sticky='nw')

# Create a frame for the canvas with non-zero row&column weights
frame_canvas = tk.Frame(frame_main)
frame_canvas.grid(row=1, column=0, pady=(5, 0), sticky='nw')
frame_canvas.grid_rowconfigure(0, weight=1)
frame_canvas.grid_columnconfigure(0, weight=1)
# Set grid_propagate to False to allow 5-by-5 buttons resizing later
frame_canvas.grid_propagate(False)

# Add a canvas in that frame
canvas = tk.Canvas(frame_canvas, bg="gray")
canvas.grid(row=0, column=0, sticky="news")

# Link a scrollbar to the canvas
vsb = tk.Scrollbar(frame_canvas, orient="vertical", command=canvas.yview)
vsb.grid(row=0, column=1, sticky='ns')
canvas.configure(yscrollcommand=vsb.set)
frame_buttons = tk.Frame(canvas, bg="gray")
canvas.create_window((0, 0), window=frame_buttons, anchor='nw')
for x in range(15):
    tk.Label(frame_buttons, text="blah", background = "white").grid(row=x)
frame_buttons.update_idletasks()
frame_canvas.config(width=500, height=100)
canvas.config(scrollregion=canvas.bbox("all"))
root.mainloop()
</code>```

this initially puts 20 labels in the scroll region, which is enough to activate the scrollbar. Then when you click search it replaces those 20 lables with 1000 test labels. But only the first 20 will be viewable.

答:
You need to reset the scrollregion whenever the frame changes size and the items are redrawn.

The normal way to do that is to bind to the <Configure> event of the frame so that it happens automatically as the frame grows and shrinks.

Example:

```<code>def reset_scrollregion(event):
    canvas.config(scrollregion=canvas.bbox("all"))
...
frame_buttons.bind("<Configure>", reset_scrollregion)
</code>```

Body:
I'm making a Tkinter GUI that allows you to query a database and will display results in a scrollable frame. However, when you produce the results the scrollbar will not adjust to match the new size of the frame. How can I get the scrollbar to be able to display all of the results? I've put together a quick and dirty version of the code to demonstrate the problem I'm having.

import tkinter as tk

def Lookup():
    list = frame_buttons.grid_slaves()
    for l in list:
        l.destroy()
    for x in range(1000):
        tk.Label(frame_buttons, text="test", background="white").grid(row=x)

root = tk.Tk()
root.grid_rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)

frame_main = tk.Frame(root, bg="white")
frame_main.grid(row = 0,sticky='news')
frame_input = tk.Frame(frame_main, background = "white")
frame_input.grid(row=0, column=0, pady=(5, 0), sticky='nw')

tk.Button(frame_input, text="Search", fg="black", background = "grey",command=Lookup).grid(row=3, column=0,sticky='nw')

# Create a frame for the canvas with non-zero row&column weights
frame_canvas = tk.Frame(frame_main)
frame_canvas.grid(row=1, column=0, pady=(5, 0), sticky='nw')
frame_canvas.grid_rowconfigure(0, weight=1)
frame_canvas.grid_columnconfigure(0, weight=1)
# Set grid_propagate to False to allow 5-by-5 buttons resizing later
frame_canvas.grid_propagate(False)

# Add a canvas in that frame
canvas = tk.Canvas(frame_canvas, bg="gray")
canvas.grid(row=0, column=0, sticky="news")

# Link a scrollbar to the canvas
vsb = tk.Scrollbar(frame_canvas, orient="vertical", command=canvas.yview)
vsb.grid(row=0, column=1, sticky='ns')
canvas.configure(yscrollcommand=vsb.set)
frame_buttons = tk.Frame(canvas, bg="gray")
canvas.create_window((0, 0), window=frame_buttons, anchor='nw')
for x in range(15):
    tk.Label(frame_buttons, text="blah", background = "white").grid(row=x)
frame_buttons.update_idletasks()
frame_canvas.config(width=500, height=100)
canvas.config(scrollregion=canvas.bbox("all"))
root.mainloop()

this initially puts 20 labels in the scroll region, which is enough to activate the scrollbar. Then when you click search it replaces those 20 lables with 1000 test labels. But only the first 20 will be viewable.

Body:
You need to reset the scrollregion whenever the frame changes size and the items are redrawn.

The normal way to do that is to bind to the <Configure> event of the frame so that it happens automatically as the frame grows and shrinks.

Example:

def reset_scrollregion(event):
    canvas.config(scrollregion=canvas.bbox("all"))
...
frame_buttons.bind("<Configure>", reset_scrollregion)


问:
Calculator layout not staying stable with varying width
When i shrink the web page to check for responsive behavior, the layout is all jumbled.

Converted the padding from pixels to rem
Converted font size from pixels to VW

.main-class{
}
.calculator-begin{
  align-items: center;
  margin-top: 3.125rem;
  margin-bottom: 3.125rem;
}

.row{
  width: 50%;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}

.screen{
  font: monospace;
  font-size: 2.778vw;
  flex-basis: 100%;
  padding: 3.125rem;
   text-align: right;
   color: white;
   background-color: black;
}

.cancel{
  background-color: #bababa;
  font-size: 2.778vw;
  flex-basis: 50%;
  padding: 3.125rem;
   text-align: center;
   border: 1.5px solid black;
}
.cancel:active{
  background: #a0a0a0;
}
.numbers{
  padding: 3.125rem;
  font-size: 2.778vw;
  flex-basis: 25%;
  text-align: center;
  background-color:  #bababa;
  border: 1.5px solid black;
}
.numbers:active{
  background: #a0a0a0;
}
.operations{
  padding: 3.125rem;
  font-size: 2.778vw;
  flex-basis: 25%;
  text-align: center;
  background-color:  #ffa642;
  border: 1.5px solid black;
}
.operations:active{
  background-color: #ff8905;
}
.zero{
  padding: 3.125rem;
  flex-basis: 75%;
  font-size: 2.778vw;
  text-align: center;
  background-color:   #bababa;
  border: 1.5px solid black;
}
.zero:active{
  background: #a0a0a0;
}

.remove-left-border{
  border-left: 0px;
}

.remove-right-border{
  border-right: 0px;
}

.remote-bot-border{
  border-bottom: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="calculatorStyle.css">
    <title>Calculator using JS</title>
  </head>
  <body>
    <div class="main-class">
      <center>
      <div class="calculator-begin">
        <div class="row">
         <div class="screen">
           <section>
             XXXXX
           </section>
         </div>
        </div>
        <div class="row">
          <button class="cancel remove-left-border">C</button>
          <button class="numbers">←</button>
          <button class="operations remove-right-border">÷</button>
        </div>
        <div class="row">
          <button class="numbers remove-left-border">7</button>
          <button class="numbers">8</button>
          <button class="numbers">9</button>
          <button class="operations remove-right-border">X</button>
        </div>
        <div class="row">
          <button class="numbers remove-left-border">4</button>
          <button class="numbers">5</button>
          <button class="numbers">6</button>
          <button class="operations remove-right-border">-</button>
        </div>
        <div class="row">
          <button class="numbers remove-left-border">1</button>
          <button class="numbers">2</button>
          <button class="numbers">3</button>
          <button class="operations remove-right-border">+</button>
        </div>
        <div class="row">
          <button class="zero remove-left-border remove-bottom-border">0</button>
          <button class="operations remove-right-border remove-bottom-border">=</button>
        </div>
      </div>
      </center>
    </div>
  </body>
</html></code>```

I want the layout to be rigid and to scale along with the browser size, that is , the relative positions of these elements should remain the same.

答:
Remove the horizontal padding from padding: 3.125rem; from your CSS. What's happening is that when you shrink your browser, you eventually reach a point where the padding won't allow the container to shrink anymore.

.main-class{
}
.calculator-begin{
  align-items: center;
  margin-top: 3.125rem;
  margin-bottom: 3.125rem;
}

.row{
  width: 50%;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}

.screen{
  font: monospace;
  font-size: 2.778vw;
  flex-basis: 100%;
  padding: 3.125rem;
   text-align: right;
   color: white;
   background-color: black;
}

.cancel{
  background-color: #bababa;
  font-size: 2.778vw;
  flex-basis: 50%;
  padding: 3.125rem 0;
   text-align: center;
   border: 1.5px solid black;
}
.cancel:active{
  background: #a0a0a0;
}
.numbers{
  padding: 3.125rem 0;
  font-size: 2.778vw;
  flex-basis: 25%;
  text-align: center;
  background-color:  #bababa;
  border: 1.5px solid black;
}
.numbers:active{
  background: #a0a0a0;
}
.operations{
  padding: 3.125rem 0;
  font-size: 2.778vw;
  flex-basis: 25%;
  text-align: center;
  background-color:  #ffa642;
  border: 1.5px solid black;
}
.operations:active{
  background-color: #ff8905;
}
.zero{
  padding: 3.125rem 0;
  flex-basis: 75%;
  font-size: 2.778vw;
  text-align: center;
  background-color:   #bababa;
  border: 1.5px solid black;
}
.zero:active{
  background: #a0a0a0;
}

.remove-left-border{
  border-left: 0px;
}

.remove-right-border{
  border-right: 0px;
}

.remote-bot-border{
  border-bottom: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="calculatorStyle.css">
    <title>Calculator using JS</title>
  </head>
  <body>
    <div class="main-class">
      <center>
      <div class="calculator-begin">
        <div class="row">
         <div class="screen">
           <section>
             XXXXX
           </section>
         </div>
        </div>
        <div class="row">
          <button class="cancel remove-left-border">C</button>
          <button class="numbers">←</button>
          <button class="operations remove-right-border">÷</button>
        </div>
        <div class="row">
          <button class="numbers remove-left-border">7</button>
          <button class="numbers">8</button>
          <button class="numbers">9</button>
          <button class="operations remove-right-border">X</button>
        </div>
        <div class="row">
          <button class="numbers remove-left-border">4</button>
          <button class="numbers">5</button>
          <button class="numbers">6</button>
          <button class="operations remove-right-border">-</button>
        </div>
        <div class="row">
          <button class="numbers remove-left-border">1</button>
          <button class="numbers">2</button>
          <button class="numbers">3</button>
          <button class="operations remove-right-border">+</button>
        </div>
        <div class="row">
          <button class="zero remove-left-border remove-bottom-border">0</button>
          <button class="operations remove-right-border remove-bottom-border">=</button>
        </div>
      </div>
      </center>
    </div>
  </body></code>```

Body:
When i shrink the web page to check for responsive behavior, the layout is all jumbled.

Converted the padding from pixels to rem
Converted font size from pixels to VW

.main-class{
}
.calculator-begin{
  align-items: center;
  margin-top: 3.125rem;
  margin-bottom: 3.125rem;
}

.row{
  width: 50%;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}

.screen{
  font: monospace;
  font-size: 2.778vw;
  flex-basis: 100%;
  padding: 3.125rem;
   text-align: right;
   color: white;
   background-color: black;
}

.cancel{
  background-color: #bababa;
  font-size: 2.778vw;
  flex-basis: 50%;
  padding: 3.125rem;
   text-align: center;
   border: 1.5px solid black;
}
.cancel:active{
  background: #a0a0a0;
}
.numbers{
  padding: 3.125rem;
  font-size: 2.778vw;
  flex-basis: 25%;
  text-align: center;
  background-color:  #bababa;
  border: 1.5px solid black;
}
.numbers:active{
  background: #a0a0a0;
}
.operations{
  padding: 3.125rem;
  font-size: 2.778vw;
  flex-basis: 25%;
  text-align: center;
  background-color:  #ffa642;
  border: 1.5px solid black;
}
.operations:active{
  background-color: #ff8905;
}
.zero{
  padding: 3.125rem;
  flex-basis: 75%;
  font-size: 2.778vw;
  text-align: center;
  background-color:   #bababa;
  border: 1.5px solid black;
}
.zero:active{
  background: #a0a0a0;
}

.remove-left-border{
  border-left: 0px;
}

.remove-right-border{
  border-right: 0px;
}

.remote-bot-border{
  border-bottom: 0px;
}

<!DOCTYPE html>

    <meta charset="utf-8">
    <link rel="stylesheet" href="calculatorStyle.css">
    <title>Calculator using JS</title>

             XXXXX

          <button class="cancel remove-left-border">C</button>
          <button class="numbers">←</button>
          <button class="operations remove-right-border">÷</button>

          <button class="numbers remove-left-border">7</button>
          <button class="numbers">8</button>
          <button class="numbers">9</button>
          <button class="operations remove-right-border">X</button>

          <button class="numbers remove-left-border">4</button>
          <button class="numbers">5</button>
          <button class="numbers">6</button>
          <button class="operations remove-right-border">-</button>

          <button class="numbers remove-left-border">1</button>
          <button class="numbers">2</button>
          <button class="numbers">3</button>
          <button class="operations remove-right-border">+</button>

          <button class="zero remove-left-border remove-bottom-border">0</button>
          <button class="operations remove-right-border remove-bottom-border">=</button>

I want the layout to be rigid and to scale along with the browser size, that is , the relative positions of these elements should remain the same.

Body:
Remove the horizontal padding from padding: 3.125rem; from your CSS. What's happening is that when you shrink your browser, you eventually reach a point where the padding won't allow the container to shrink anymore.

.main-class{
}
.calculator-begin{
  align-items: center;
  margin-top: 3.125rem;
  margin-bottom: 3.125rem;
}

.row{
  width: 50%;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}

.screen{
  font: monospace;
  font-size: 2.778vw;
  flex-basis: 100%;
  padding: 3.125rem;
   text-align: right;
   color: white;
   background-color: black;
}

.cancel{
  background-color: #bababa;
  font-size: 2.778vw;
  flex-basis: 50%;
  padding: 3.125rem 0;
   text-align: center;
   border: 1.5px solid black;
}
.cancel:active{
  background: #a0a0a0;
}
.numbers{
  padding: 3.125rem 0;
  font-size: 2.778vw;
  flex-basis: 25%;
  text-align: center;
  background-color:  #bababa;
  border: 1.5px solid black;
}
.numbers:active{
  background: #a0a0a0;
}
.operations{
  padding: 3.125rem 0;
  font-size: 2.778vw;
  flex-basis: 25%;
  text-align: center;
  background-color:  #ffa642;
  border: 1.5px solid black;
}
.operations:active{
  background-color: #ff8905;
}
.zero{
  padding: 3.125rem 0;
  flex-basis: 75%;
  font-size: 2.778vw;
  text-align: center;
  background-color:   #bababa;
  border: 1.5px solid black;
}
.zero:active{
  background: #a0a0a0;
}

.remove-left-border{
  border-left: 0px;
}

.remove-right-border{
  border-right: 0px;
}

.remote-bot-border{
  border-bottom: 0px;
}

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="calculatorStyle.css">
    <title>Calculator using JS</title>
  </head>
  <body>
    <div class="main-class">
      <center>
      <div class="calculator-begin">
        <div class="row">
         <div class="screen">
           <section>
             XXXXX
           </section>
         </div>
        </div>
        <div class="row">
          <button class="cancel remove-left-border">C</button>
          <button class="numbers">←</button>
          <button class="operations remove-right-border">÷</button>
        </div>
        <div class="row">
          <button class="numbers remove-left-border">7</button>
          <button class="numbers">8</button>
          <button class="numbers">9</button>
          <button class="operations remove-right-border">X</button>
        </div>
        <div class="row">
          <button class="numbers remove-left-border">4</button>
          <button class="numbers">5</button>
          <button class="numbers">6</button>
          <button class="operations remove-right-border">-</button>
        </div>
        <div class="row">
          <button class="numbers remove-left-border">1</button>
          <button class="numbers">2</button>
          <button class="numbers">3</button>
          <button class="operations remove-right-border">+</button>
        </div>
        <div class="row">
          <button class="zero remove-left-border remove-bottom-border">0</button>
          <button class="operations remove-right-border remove-bottom-border">=</button>
        </div>
      </div>
      </center>
    </div>
  </body>


问:
how can i add a css file to body of a page?
I am working on a page which has a print view so when the user clicks on "Print" a new window pops up and I want to add a .css file just for that window. </p>

<p>Thanks </p>

答:
You can add a print only style sheet

```<code><link rel="stylesheet"  type="text/css"  media="print" href="print.css" />
</code>```

This stylesheet does not need to be "added" to popup windows. It will be ignored when the user is in the "normal" view and then only applied when the user goes to print the document.

If you want to be both visible and apply to the printed document, just have it cascade.

```<code><link rel="stylesheet"  type="text/css" href="normal.css" /> #normal styling
<link rel="stylesheet"  type="text/css" href="print.css" /> #override normal styling
<link rel="stylesheet"  type="text/css"  media="print" href="print.css" /> #override normal, for printer
</code>```

That way you get the best of both worlds. Override the css rules in normal.css with new rules in print.css, as needed to make the document look as you wish. The new document will visually look different and then also print out differently.

ContentLicense: CC BY-SA 3.0

Body:
I am working on a page which has a print view so when the user clicks on "Print" a new window pops up and I want to add a .css file just for that window.

Thanks

Body:
You can add a print only style sheet

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

This stylesheet does not need to be "added" to popup windows. It will be ignored when the user is in the "normal" view and then only applied when the user goes to print the document.

If you want to be both visible and apply to the printed document, just have it cascade.

<link rel="stylesheet"  type="text/css" href="normal.css" /> #normal styling
<link rel="stylesheet"  type="text/css" href="print.css" /> #override normal styling
<link rel="stylesheet"  type="text/css"  media="print" href="print.css" /> #override normal, for printer

That way you get the best of both worlds. Override the css rules in normal.css with new rules in print.css, as needed to make the document look as you wish. The new document will visually look different and then also print out differently.


问:
JavaScript: Loop through Array of Objects and Find Sum of Specific Key Using Reduce Function
I have the following object below.  It contains an array of objects.  Each object is a superhero that contains details about the superhero.

```<code>const superheroes = [
      {
        name: 'Bruce Wayne',
        alias: 'Batman',
        powerLevel: 50,
        universe: 'DC Comics',
        race: 'Human',
      },
      {
        name: 'Wade Wilson',
        alias: 'Deadpool',
        powerLevel: 90,
        universe: 'Marvel Comics',
        race: 'Mutant',
      },
      {
        name: 'Peter Parker',
        alias: 'Spiderman',
        powerLevel: 70,
        universe: 'Marvel Comics',
        race: 'Human',
      },
      {
        name: 'Kristin Wells',
        alias: 'Superwoman',
        powerLevel: 99,
        universe: 'DC Comics',
        race: 'Kryptonian',
      },
      {
        name: 'Barry Allen',
        alias: 'The Flash',
        powerLevel: 80,
        universe: 'DC Comics',
        race: 'Human',
      },
      {
        name: 'Diana Prince',
        alias: 'Wonder Woman',
        powerLevel: 90,
        universe: 'DC Comics',
        race: 'Human',
      },
      {
        name: 'Ororo Munroe',
        alias: 'Storm',
        powerLevel: 85,
        universe: 'Marvel Comics',
        race: 'Mutant',
      },
      {
        name: 'Helen Parr',
        alias: 'Elastigirl',
        powerLevel: 70,
        universe: 'Dark Horse Comics',
        race: 'Human',
      },
    ];
</code>```

I want to find the average power level of all the superheroes.

I tried the code below:

```<code>function powerLevelAverage(obj){

  let sum = 0;
  let objCount = 0;

  return obj.reduce((accumulator, element) => {

    objCount += 1;
    console.log(objCount)

    sum = accumulator + element.powerLevel

    return sum;

  }, 0)
  return Math.round(sum/objCount);
}

const averagePowerLevel = powerLevelAverage(superheroes);

averagePowerLevel
</code>```

The code appears to return the sum of 634 but does not return the average.  What am I doing wrong?

Note: I want to use reduce modifying function to solve this problem.

答:
There are three mistakes:

You have two return statements in the code. So the code will not reach to the second one which gets average.

You are using reduce() in a wrong way. You are not using accumulator anywhere. You are using reduce() like forEach()

You don't need to count each object in reduce() you already have the length of array in form of obj.length

A cleaner code can be.

```<code>function powerLevelAverage(obj){
  return Math.round(obj.reduce((ac,a) => ac + a.powerLevel,0)/obj.length)
}
</code>```

Working snippet:

const superheroes = [ { name: 'Bruce Wayne', alias: 'Batman', powerLevel: 50, universe: 'DC Comics', race: 'Human', }, { name: 'Wade Wilson', alias: 'Deadpool', powerLevel: 90, universe: 'Marvel Comics', race: 'Mutant', }, { name: 'Peter Parker', alias: 'Spiderman', powerLevel: 70, universe: 'Marvel Comics', race: 'Human', }, { name: 'Kristin Wells', alias: 'Superwoman', powerLevel: 99, universe: 'DC Comics', race: 'Kryptonian', }, { name: 'Barry Allen', alias: 'The Flash', powerLevel: 80, universe: 'DC Comics', race: 'Human', }, { name: 'Diana Prince', alias: 'Wonder Woman', powerLevel: 90, universe: 'DC Comics', race: 'Human', }, { name: 'Ororo Munroe', alias: 'Storm', powerLevel: 85, universe: 'Marvel Comics', race: 'Mutant', }, { name: 'Helen Parr', alias: 'Elastigirl', powerLevel: 70, universe: 'Dark Horse Comics', race: 'Human', }, ];

function powerLevelAverage(obj){
  return Math.round(obj.reduce((ac,a) => ac + a.powerLevel,0)/obj.length)
}

console.log(powerLevelAverage(superheroes))```

Body:
I have the following object below.  It contains an array of objects.  Each object is a superhero that contains details about the superhero.

const superheroes = [
      {
        name: 'Bruce Wayne',
        alias: 'Batman',
        powerLevel: 50,
        universe: 'DC Comics',
        race: 'Human',
      },
      {
        name: 'Wade Wilson',
        alias: 'Deadpool',
        powerLevel: 90,
        universe: 'Marvel Comics',
        race: 'Mutant',
      },
      {
        name: 'Peter Parker',
        alias: 'Spiderman',
        powerLevel: 70,
        universe: 'Marvel Comics',
        race: 'Human',
      },
      {
        name: 'Kristin Wells',
        alias: 'Superwoman',
        powerLevel: 99,
        universe: 'DC Comics',
        race: 'Kryptonian',
      },
      {
        name: 'Barry Allen',
        alias: 'The Flash',
        powerLevel: 80,
        universe: 'DC Comics',
        race: 'Human',
      },
      {
        name: 'Diana Prince',
        alias: 'Wonder Woman',
        powerLevel: 90,
        universe: 'DC Comics',
        race: 'Human',
      },
      {
        name: 'Ororo Munroe',
        alias: 'Storm',
        powerLevel: 85,
        universe: 'Marvel Comics',
        race: 'Mutant',
      },
      {
        name: 'Helen Parr',
        alias: 'Elastigirl',
        powerLevel: 70,
        universe: 'Dark Horse Comics',
        race: 'Human',
      },
    ];

I want to find the average power level of all the superheroes.

I tried the code below:

function powerLevelAverage(obj){

  let sum = 0;
  let objCount = 0;

  return obj.reduce((accumulator, element) => {

    objCount += 1;
    console.log(objCount)

    sum = accumulator + element.powerLevel

    return sum;

  }, 0)
  return Math.round(sum/objCount);
}

const averagePowerLevel = powerLevelAverage(superheroes);

averagePowerLevel

The code appears to return the sum of 634 but does not return the average.  What am I doing wrong?

Note: I want to use reduce modifying function to solve this problem.

Body:
There are three mistakes:

You have two return statements in the code. So the code will not reach to the second one which gets average.

You are using reduce() in a wrong way. You are not using accumulator anywhere. You are using reduce() like forEach()

You don't need to count each object in reduce() you already have the length of array in form of obj.length

A cleaner code can be.

function powerLevelAverage(obj){
  return Math.round(obj.reduce((ac,a) => ac + a.powerLevel,0)/obj.length)
}

Working snippet:

const superheroes = [ { name: 'Bruce Wayne', alias: 'Batman', powerLevel: 50, universe: 'DC Comics', race: 'Human', }, { name: 'Wade Wilson', alias: 'Deadpool', powerLevel: 90, universe: 'Marvel Comics', race: 'Mutant', }, { name: 'Peter Parker', alias: 'Spiderman', powerLevel: 70, universe: 'Marvel Comics', race: 'Human', }, { name: 'Kristin Wells', alias: 'Superwoman', powerLevel: 99, universe: 'DC Comics', race: 'Kryptonian', }, { name: 'Barry Allen', alias: 'The Flash', powerLevel: 80, universe: 'DC Comics', race: 'Human', }, { name: 'Diana Prince', alias: 'Wonder Woman', powerLevel: 90, universe: 'DC Comics', race: 'Human', }, { name: 'Ororo Munroe', alias: 'Storm', powerLevel: 85, universe: 'Marvel Comics', race: 'Mutant', }, { name: 'Helen Parr', alias: 'Elastigirl', powerLevel: 70, universe: 'Dark Horse Comics', race: 'Human', }, ];

function powerLevelAverage(obj){
  return Math.round(obj.reduce((ac,a) => ac + a.powerLevel,0)/obj.length)
}

console.log(powerLevelAverage(superheroes))


问:
Running python package .egg in Azure Databricks Job
Using build tool (setuptools) packaged my python code as .egg format. I wanted to run this package through job in azure data-bricks.

I can able to execute the package in my local machine through below commands.

spark-submit --py-files ./dist/hello-1.0-py3.6.egg  hello/pi.py

1) Copied the package into DBFS path as follows,

work-space -> User -> Create -> Library -> Library Source (DBFS) -> Library Type (Python Egg) -> Uploaded

2) Created a job with task as spark-submit on new cluster mode

3) Below parameters are configured for the task,

["--py-files","dbfs:/FileStore/jars/8c1231610de06d96-hello_1_0_py3_6-70b16.egg","hello/pi.py"]

Actual: /databricks/python/bin/python: can't open file '/databricks/driver/hello/hello.py': [Errno 2] No such file or directory

Expected: Job should execute successfully.

答:
The only way I've got this to work is by using the API to create a Python Job. The UI does not support this for some reason.

I use PowerShell to work with the API - this is an example that creates a job using an egg which works for me:

```<code>$Lib = '{"egg":"LOCATION"}'.Replace("LOCATION", "dbfs:$TargetDBFSFolderCode/pipelines.egg")
$ClusterId = "my-cluster-id"
$j = "sample"
$PythonParameters = "pipelines.jobs.cleansed.$j"
$MainScript = "dbfs:" + $TargetDBFSFolderCode + "/main.py"
Add-DatabricksDBFSFile -BearerToken $BearerToken -Region $Region -LocalRootFolder "./bin/tmp" -FilePattern "*.*"  -TargetLocation $TargetDBFSFolderCode -Verbose
Add-DatabricksPythonJob -BearerToken $BearerToken -Region $Region -JobName "$j-$Environment" -ClusterId $ClusterId `
    -PythonPath $MainScript -PythonParameters $PythonParameters -Libraries $Lib -Verbose
</code>```

That copies my main.py and pipelines.egg to DBFS then creates a job pointed at them passing in a parameter.

One annoying thing about eggs on Databricks - you must uninstall and restart the cluster before it picks up any new versions that you deploy.

If you use an engineering cluster this is not an issue.

Body:
The only way I've got this to work is by using the API to create a Python Job. The UI does not support this for some reason.

I use PowerShell to work with the API - this is an example that creates a job using an egg which works for me:

$Lib = '{"egg":"LOCATION"}'.Replace("LOCATION", "dbfs:$TargetDBFSFolderCode/pipelines.egg")
$ClusterId = "my-cluster-id"
$j = "sample"
$PythonParameters = "pipelines.jobs.cleansed.$j"
$MainScript = "dbfs:" + $TargetDBFSFolderCode + "/main.py"
Add-DatabricksDBFSFile -BearerToken $BearerToken -Region $Region -LocalRootFolder "./bin/tmp" -FilePattern "*.*"  -TargetLocation $TargetDBFSFolderCode -Verbose
Add-DatabricksPythonJob -BearerToken $BearerToken -Region $Region -JobName "$j-$Environment" -ClusterId $ClusterId `
    -PythonPath $MainScript -PythonParameters $PythonParameters -Libraries $Lib -Verbose

That copies my main.py and pipelines.egg to DBFS then creates a job pointed at them passing in a parameter.

One annoying thing about eggs on Databricks - you must uninstall and restart the cluster before it picks up any new versions that you deploy.

If you use an engineering cluster this is not an issue.


问:
Uncaught SyntaxError: Invalid destructuring assignment target
I have problem in my jquery code . Can any one help me regarding this error:

Uncaught SyntaxError: Invalid destructuring assignment target

```<code>$(function() {
  $('#Events').on("slides", function({
    generateNextPrev: true,
    play: 5000,
    pause: 2500,
    hoverPause: true,
    preload: true,
    preloadImage: '/images/loading.gif'
  });

  // $('#slides_container').css("display", "inline");
  );
});
</code>```

This error is coming in this line generateNextPrev: true,. Kindly guide me, what's the issue.

答: This is invalid syntax - take a look at the function declaration on line 1 vs line 2. I don't know what you're trying to accomplish, but you must have a function body. You have this: .on("slides", function({...}); which has an unclosed parenthesis and no function body. .on("slides", function(parameters) {/*do stuff here*/}); is the syntax you need; I'm not really sure where the object is intended to go.

Body:
I have problem in my jquery code . Can any one help me regarding this error:

Uncaught SyntaxError: Invalid destructuring assignment target

$(function() {
  $('#Events').on("slides", function({
    generateNextPrev: true,
    play: 5000,
    pause: 2500,
    hoverPause: true,
    preload: true,
    preloadImage: '/images/loading.gif'
  });

  // $('#slides_container').css("display", "inline");
  );
});

This error is coming in this line generateNextPrev: true,. Kindly guide me, what's the issue.


问:
how to use .map() in nodelist in javascript?
Why am i getting this error? How can i access and print the nodes when i'm selecting the
 tags with querySelectorAll?

script.js:14 Uncaught TypeError: list.map is not a function

HTML

```<code><ul class="wrapper1" id="testDiv">
        <li class="cake">Carrots</li>
        <li class="cake">Cake</li>
        <li class="cake">Wheat</li>
        <li class="cake">Balloons</li>
    </ul>
</code>```

JS

```<code> let list = document.querySelectorAll("li");
        let items = list.map(elem => {
      console.log(elem);
    })
</code>```

答:
I know this is an old thread but listed as #1 on Google search result. So here is an alternative to those in need.</p>

```<code>let items = [].map.call(list, item => console.log(item));
</code>```

Body:
Why am i getting this error? How can i access and print the nodes when i'm selecting the
 tags with querySelectorAll?

script.js:14 Uncaught TypeError: list.map is not a function

HTML

Carrots

Cake

Wheat

Balloons

JS

 let list = document.querySelectorAll("li");
        let items = list.map(elem => {
      console.log(elem);
    })

Body:
I know this is an old thread but listed as #1 on Google search result. So here is an alternative to those in need.

let items = [].map.call(list, item => console.log(item));


问:
Having trouble understanding output of line of code -
I don't understand the use of return 0* statement??

Tried looking for answers on Google

```<code>return 0*printf("%d",a[i]);
</code>```

I don't understand the outcome.

答:
As for me then this

```<code>return 0*printf("%d",a[i]);
</code>```

just a bad programming style.

At least it would be better to write instead

```<code>return ( printf("%d",a[i]), 0 );
</code>```

not saying about

```<code>printf("%d",a[i]);
return 0;
</code>```

Maybe this statement is found in a recursive function.

As for your question

Having trouble understanding output of line of code -

then this line outputs the value of the i-th element of the integral array a and exits the corresponding function.

Body:
I don't understand the use of return 0* statement??

Tried looking for answers on Google

return 0*printf("%d",a[i]);

I don't understand the outcome.

Body:
As for me then this

return 0*printf("%d",a[i]);

just a bad programming style.

At least it would be better to write instead

return ( printf("%d",a[i]), 0 );

not saying about

printf("%d",a[i]);
return 0;

Maybe this statement is found in a recursive function.

As for your question

Having trouble understanding output of line of code -

then this line outputs the value of the i-th element of the integral array a and exits the corresponding function.


答:
You're returning your sum right here, which doesn't account for your division....

Change this to

```<code>function powerLevelAverage(obj){

  let sum = 0;
  let objCount = 0;

  return obj.reduce((accumulator, element) => {

    objCount += 1;
    console.log(objCount)

    sum = accumulator + element.powerLevel

    // return sum; // Just get rid of this

  }, 0)
  return Math.round(sum/objCount);
}
</code>```

Title: JavaScript: Loop through Array of Objects and Find Sum of Specific Key Using Reduce Function

Body:
You're returning your sum right here, which doesn't account for your division....

Change this to

function powerLevelAverage(obj){

  let sum = 0;
  let objCount = 0;

  return obj.reduce((accumulator, element) => {

    objCount += 1;
    console.log(objCount)

    sum = accumulator + element.powerLevel

    // return sum; // Just get rid of this

  }, 0)
  return Math.round(sum/objCount);
}


问:
Don't return model if it is null
I want to return a GraphQl response to UI, where I have to enable or disable a particular feature based on the response.

I am getting a response in both the cases, i.e if value found then a proper string is getting rendered and is sent back a response, but when value is not found then null is getting sent as a response from the kotlin data model.

```<code>data class FinalObject(
     val isEnableDisable : String? = null
)
</code>```

Kotlin class for GraphQl

```<code>@GraphQLDescription("Random string")
data class ActualClassForGraphQl(
     val finalObject: FinalObject
)
</code>```

Kotlin class where actual logic is written

```<code>@Component
class ActualClassForLogic{
      fun isEnableDisable():FinalObject{
           if(true){
              return FinalObject("some string")
           }
           return FinalObject()
      }
}
</code>```

Expected result:

Nothing needs to be sent, i.e the key FinalObject itself need not to get populated in response, i.e an empty response body needs to sent to UI.

Actual result :
In case when it is entering in "if" block i.e success scenario

```<code>FinalObject{
     isEnableDisable:"some string"
}
</code>```

In case when it is not entering "if" block i.e failure scenario

```<code>FinalObject{
     isEnableDisable:null
}
</code>```

答: unless i misunderstood your question, I think thats not how GraphQL spec is defined, its more driven from client side than server side what to display in response and what not, If client sends that field(finalObject ?) in query, it should be returned regardless of what value(null on non null) and thats what the contract graphql spec gives to users.</p>

Title: Don't return model if it is null

Body:
I want to return a GraphQl response to UI, where I have to enable or disable a particular feature based on the response.

I am getting a response in both the cases, i.e if value found then a proper string is getting rendered and is sent back a response, but when value is not found then null is getting sent as a response from the kotlin data model.

data class FinalObject(
     val isEnableDisable : String? = null
)

Kotlin class for GraphQl

@GraphQLDescription("Random string")
data class ActualClassForGraphQl(
     val finalObject: FinalObject
)

Kotlin class where actual logic is written

@Component
class ActualClassForLogic{
      fun isEnableDisable():FinalObject{
           if(true){
              return FinalObject("some string")
           }
           return FinalObject()
      }
}

Expected result:

Nothing needs to be sent, i.e the key FinalObject itself need not to get populated in response, i.e an empty response body needs to sent to UI.

Actual result :
In case when it is entering in "if" block i.e success scenario

FinalObject{
     isEnableDisable:"some string"
}

In case when it is not entering "if" block i.e failure scenario

FinalObject{
     isEnableDisable:null
}


问:
Problem on invalidating the cache of a Cloudfront distribution
I have some problem on invalidating the cache of my CloudFront distribution.

I mapped a wildcard domain name to my CloudFront distribution; then I created a Lamba@Edge that modify the request origin redirecting each subdomain to its subfolder.

It works in this way:

```<code>aaa.mydomain.com => mydomain.com/aaa
bbb.mydomain.com => mydomain.com/bbb
ccc.mydomain.com => mydomain.com/ccc
...
</code>```

I'm not be able to invalidate the cache:
if I invalidate the path /bbb/* it doesn't work. Instead with the path /* works, but in this way I invalidate all the S3 Bucket and I would like to avoid it.

Any help?

Thanks!

答:
I ran into the same problem. At first I investigated writing a Lambda@Edge function that would check to see if content should be invalidated and then break the cache by appending a query parameter to the URL. But this seemed to be just as problematic (and expensive) as invalidating the entire S3 bucket. The solution I settled on instead was using the Cache-Control: no-cache header on the specific assets that shouldn't be cached by CloudFront and then just invalidating the other cached assets with query parameters. And this method doesn't require issuing any CloudFront invalidations.

So for example, if I'm hosting a static site on CloudFront / S3 that looks like this:

```<code>- index.html
- header.jpg
- site.css
</code>```

I upload it to S3 as follows:

```<code>- index.html // Cache-Control: no-cache
- header.jpg // Linked with <img src='header.jpg?uniquedigest' />
- site.css // Linked with <link href='site.css?uniquedigest' />
</code>```

This way everything is kept up to date in CloudFrontL Only the index.html isn't cached and all the assets are still cached after the initial fetch from the origin S3 bucket. The one downside is that the index.html is always fetched from origin but HTML should be small enough that this doesn't have a big performance impact.

Body:
I have some problem on invalidating the cache of my CloudFront distribution.

I mapped a wildcard domain name to my CloudFront distribution; then I created a Lamba@Edge that modify the request origin redirecting each subdomain to its subfolder.

It works in this way:

aaa.mydomain.com => mydomain.com/aaa
bbb.mydomain.com => mydomain.com/bbb
ccc.mydomain.com => mydomain.com/ccc
...

I'm not be able to invalidate the cache:
if I invalidate the path /bbb/* it doesn't work. Instead with the path /* works, but in this way I invalidate all the S3 Bucket and I would like to avoid it.

Any help?

Thanks!

Body:
I ran into the same problem. At first I investigated writing a Lambda@Edge function that would check to see if content should be invalidated and then break the cache by appending a query parameter to the URL. But this seemed to be just as problematic (and expensive) as invalidating the entire S3 bucket. The solution I settled on instead was using the Cache-Control: no-cache header on the specific assets that shouldn't be cached by CloudFront and then just invalidating the other cached assets with query parameters. And this method doesn't require issuing any CloudFront invalidations.

So for example, if I'm hosting a static site on CloudFront / S3 that looks like this:

- index.html
- header.jpg
- site.css

I upload it to S3 as follows:

- index.html // Cache-Control: no-cache
- header.jpg // Linked with <img src='header.jpg?uniquedigest' />
- site.css // Linked with <link href='site.css?uniquedigest' />

This way everything is kept up to date in CloudFrontL Only the index.html isn't cached and all the assets are still cached after the initial fetch from the origin S3 bucket. The one downside is that the index.html is always fetched from origin but HTML should be small enough that this doesn't have a big performance impact.


问:
Conditional Styling and Binding
In Angular 2 I am binding a dollar value like this inside a TABLE TD.

```<code><td>
  {{eachOutlet.dollarValue}}
</td>
</code>```

This dollarValue will be less than 0 or equal to 0 or greater than 0.
When it is less than zero it should show up in "Red" color.
When it is zero, nothing should show up. Just blank text.
When it is greater than zero, it should use thousands separator and show the number.

How can I apply such conditional styling using Angular 2 binding?
Is it even possible to do it ?

答:
We can do like this.</p>

```<code><div class="responsive-standalone--Overlay" (click)="mobileRMenu()" [style.display]="rMenu ? 'block' :'none'"></div>
</code>```

Title: Conditional Styling and Binding

Body:
In Angular 2 I am binding a dollar value like this inside a TABLE TD.

  {{eachOutlet.dollarValue}}

This dollarValue will be less than 0 or equal to 0 or greater than 0.
When it is less than zero it should show up in "Red" color.
When it is zero, nothing should show up. Just blank text.
When it is greater than zero, it should use thousands separator and show the number.

How can I apply such conditional styling using Angular 2 binding?
Is it even possible to do it ?

Body:
We can do like this.

<div class="responsive-standalone--Overlay" (click)="mobileRMenu()" [style.display]="rMenu ? 'block' :'none'"></div>


问:
Regex to determine legal SQL?

Possible Duplicate:

  Regular expression to match common SQL syntax?

I am writing some helpers to help generate some very domain-specific sql. In my test-suite it would be nice to add a sanity check to ensure that the results are actually valid SQL. I'm not doing anything particularly fancy and this isn't production code so I think some regex would do but it's still annoyingly difficult to write by hand.

Is anyone willing to share a regex expression that would validate valid SQL at least for the 90% case?

答:
SQL is not a regular language. Use a real validator, such as Mimer.

See also:

Is SQL or even TSQL Turing Complete?

Regular expression to match common SQL syntax?

Title: Regex to determine legal SQL?


问:
PHP IMAP decoding messages
I have emails sent via base64 encoding and 8bit encoding. I was wondering how I could check the encoding of the message using imap_fetchstructure (been doing this for about two hours, so lost) and then decode it properly.

Gmail and Mailbox (app on iOS) are sending it as 8bit while Windows 8's Mail app is sending it as base64. Either way, I need to decode whether its 8bit or base64 by detecting what type of encoding it has used.

Using PHP 5.1.6 (yes, I should update, been busy).

I really have no code to show. This is all I have:

```<code><?php
$hostname = '{********:993/imap/ssl}INBOX';
$username = '*********';
$password = '******';

$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to server: ' . imap_last_error());

$emails = imap_search($inbox,'ALL');

if($emails) {

    $output = '';

    rsort($emails);

    foreach($emails as $email_number) {

        $overview = imap_fetch_overview($inbox,$email_number,0);
        $message = imap_fetchbody($inbox,$email_number,2);
        $struct = imap_fetchstructure($inbox, $email_number);

        $output.= '<div class="toggle'.($overview[0]->seen ? 'read' : 'unread').'">';
        $output.= '<span class="subject">'.$overview[0]->subject.'</span> ';
        $output.= '<span class="from">'.$overview[0]->from.'</span>';
        $output.= '<span class="date">on '.$overview[0]->date.'</span>';
        $output.= '</div>';

        /* output the email body */
        $output.= '<div class="body">'.$message.'</div>';
    }

    echo $output;
}

imap_close($inbox);
?>
</code>```

答:
```<code>            // Best for reading attached file from e-mail as well as body of the mail
            $hostname = '{imap.gmail.com:993/imap/ssl}Inbox';
            $username = 'xzy.xyz@xyz.com';
            $password = '****************';

            $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
            $emails   = imap_search($inbox, 'SUBJECT "'.$subject.'"');
            rsort($emails);
            foreach ($emails as $key => $value) {

                $overview = imap_fetch_overview($inbox,$value,0);
                $message_date = new DateTime($overview[0]->date);
                $date = $message_date->format('Ymd');
                $message = imap_fetchbody($inbox,$value,2);
                $structure = imap_fetchstructure($inbox, $value);
                $attachments = [];
                if(isset($structure->parts) && count($structure->parts))
                {
                    for($i = 0; $i < count($structure->parts); $i++)
                    {
                        $attachments[$i] = array(
                                'is_attachment' => false,
                                'filename' => '',
                                'name' => '',
                                'attachment' => ''
                            );
                        if($structure->parts[$i]->ifdparameters)
                        {
                            foreach($structure->parts[$i]->dparameters as $object)
                            {
                                if(strtolower($object->attribute) == 'filename')
                                {
                                    $attachments[$i]['is_attachment'] = true;
                                    $attachments[$i]['filename'] = $object->value;
                                }
                            }
                        }

                        if($structure->parts[$i]->ifparameters)
                        {
                            foreach($structure->parts[$i]->parameters as $object)
                            {
                                if(strtolower($object->attribute) == 'name')
                                {
                                    $attachments[$i]['is_attachment'] = true;
                                    $attachments[$i]['name'] = $object->value;
                                }
                            }
                        }

                        if($attachments[$i]['is_attachment'])
                        {
                            $attachments[$i]['attachment'] = imap_fetchbody($inbox, $value, $i+1);
                            if($structure->parts[$i]->encoding == 3) //3 = BASE64 encoding
                            {
                                $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
                            }
                            elseif($structure->parts[$i]->encoding == 4) //4 = QUOTED-PRINTABLE encoding
                            {
                                $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
                            }
                        }
                    }
                }
            }
            imap_close($inbox);//Never forget to close the connection
</code>```

Title: PHP IMAP decoding messages

Body:
I have emails sent via base64 encoding and 8bit encoding. I was wondering how I could check the encoding of the message using imap_fetchstructure (been doing this for about two hours, so lost) and then decode it properly.

Gmail and Mailbox (app on iOS) are sending it as 8bit while Windows 8's Mail app is sending it as base64. Either way, I need to decode whether its 8bit or base64 by detecting what type of encoding it has used.

Using PHP 5.1.6 (yes, I should update, been busy).

I really have no code to show. This is all I have:

<?php
$hostname = '{********:993/imap/ssl}INBOX';
$username = '*********';
$password = '******';

$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to server: ' . imap_last_error());

$emails = imap_search($inbox,'ALL');

if($emails) {

    $output = '';

    rsort($emails);

    foreach($emails as $email_number) {

        $overview = imap_fetch_overview($inbox,$email_number,0);
        $message = imap_fetchbody($inbox,$email_number,2);
        $struct = imap_fetchstructure($inbox, $email_number);

        $output.= '
seen ? 'read' : 'unread').'">';
        $output.= ''.$overview[0]->subject.' ';
        $output.= ''.$overview[0]->from.'';
        $output.= 'on '.$overview[0]->date.'';
        $output.= '
';

        /* output the email body */
        $output.= '
'.$message.'
';
    }

    echo $output;
}

imap_close($inbox);
?>


问:
Can Keras.load_img work on multiple images in folder
I'm working on an algorithm to classify pictures of dogs and cats using Keras. As per the code below, this works when I feed in one image, but my question is can Keras.load_img work on multiple images in a folder? When I try this it says list object has no attributes seek and read.</p>

```<code>from keras.preprocessing import image
test_image = image.load_img('dataset/single_prediction/cat_or_dog_1.jpg', target_size = (64, 64))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict(test_image)
training_set.class_indices
if result[0][0] == 1:
prediction = 'dog'
else:
prediction = 'cat'
</code>```

答:
I think there is a solution, you can try this:</p>

```<code>images = []
for img in os.listdir(folder_path):
    img = image.load_img(img, target_size=(img_width, img_height))
    img = img.img_to_array(img)
    img = np.expand_dims(img, axis=0)
    images.append(img)
images = np.vstack(images)
classes = classifier.predict(images, batch_size=10)
print(classes)
</code>```

Body:
I'm working on an algorithm to classify pictures of dogs and cats using Keras. As per the code below, this works when I feed in one image, but my question is can Keras.load_img work on multiple images in a folder? When I try this it says list object has no attributes seek and read.

from keras.preprocessing import image
test_image = image.load_img('dataset/single_prediction/cat_or_dog_1.jpg', target_size = (64, 64))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict(test_image)
training_set.class_indices
if result[0][0] == 1:
prediction = 'dog'
else:
prediction = 'cat'

Body:
I think there is a solution, you can try this:

images = []
for img in os.listdir(folder_path):
    img = image.load_img(img, target_size=(img_width, img_height))
    img = img.img_to_array(img)
    img = np.expand_dims(img, axis=0)
    images.append(img)
images = np.vstack(images)
classes = classifier.predict(images, batch_size=10)
print(classes)


问:
Javascript function ONLY works on the first row of the table
Each row in my table has an edit button wherein it has a javascript function to edit the data in a row. Whenever I click the edit button, all rows got affected and all input fields were enabled. At first all input fields in all rows are disabled, but when I click any edit button all input fields are affected.

I already used a class selector in my javascript function and in my button and input fields tag.

Here is my html code:

```<code><?php
if($result = mysqli_query($conn, $sql)) {
    while($row = mysqli_fetch_assoc($result)) {
        ?>
        <tr>
            <td> <?php echo $row["productname"]; ?> </td>
            <td><input type="number" name="crit" id="crit" value="<?php echo $row["quantity"]; ?>" disabled></td>
            <td><button type="button" name="edit" id="edit"><i class="fa fa-edit"></i></button></td>
        </tr>
        <?php
    }
}
?>
</code>```

Here is my javascript function:

```<code>    $(document).ready(function() {
    var button = $('#crit');
    $(button).prop('disabled', true);

    $('#edit').click(function() {
        if ($(button).prop('disabled')) $(button).prop('disabled', false);
        else $(button).prop('disabled', true);
    });

});
</code>```

Once I clicked the edit button of a specific row, the input field SHOULD be enabled on that row only.

答:
You give all the elements the same ID - but an ID must be unique. Use a class property instead, and find the closest element with the crit class, using closest() on the button.

```<code><?php
if($result = mysqli_query($conn, $sql)) {
   while($row = mysqli_fetch_assoc($result)){
   ?>
      <tr>
          <td> <?php echo $row["productname"]; ?> </td>
          <td><input type="number" class="crit" value="<?php echo $row["quantity"]; ?>" disabled></td>
          <td><button type="button" class="edit"><i class="fa fa-edit"></i></button></td>
     </tr>
    <?php
    }
}
</code>```

```<code>$(document).ready(function() {
    var buttons = $('.crit');
    $(buttons).prop('disabled', true);

    $('.edit').click(function() {
        var button = $(this).closest("tr").find(".crit");  // closest element with the crit-class
        var status = button.prop("disabled");              // current status
        button.prop("disabled", !status);                  // toggle disabled
    });
});
</code>```

The same goes for the name attributes, these should also be unique.

Body:
Each row in my table has an edit button wherein it has a javascript function to edit the data in a row. Whenever I click the edit button, all rows got affected and all input fields were enabled. At first all input fields in all rows are disabled, but when I click any edit button all input fields are affected.

I already used a class selector in my javascript function and in my button and input fields tag.

Here is my html code:

<?php
if($result = mysqli_query($conn, $sql)) {
    while($row = mysqli_fetch_assoc($result)) {
        ?>

             <?php echo $row["productname"]; ?>
            <input type="number" name="crit" id="crit" value="<?php echo $row["quantity"]; ?>" disabled>
            <button type="button" name="edit" id="edit"></button>

        <?php
    }
}
?>

Here is my javascript function:

    $(document).ready(function() {
    var button = $('#crit');
    $(button).prop('disabled', true);

    $('#edit').click(function() {
        if ($(button).prop('disabled')) $(button).prop('disabled', false);
        else $(button).prop('disabled', true);
    });

});

Once I clicked the edit button of a specific row, the input field SHOULD be enabled on that row only.

Body:
You give all the elements the same ID - but an ID must be unique. Use a class property instead, and find the closest element with the crit class, using closest() on the button.

<?php
if($result = mysqli_query($conn, $sql)) {
   while($row = mysqli_fetch_assoc($result)){
   ?>
      <tr>
          <td> <?php echo $row["productname"]; ?> </td>
          <td><input type="number" class="crit" value="<?php echo $row["quantity"]; ?>" disabled></td>
          <td><button type="button" class="edit"><i class="fa fa-edit"></i></button></td>
     </tr>
    <?php
    }
}

$(document).ready(function() {
    var buttons = $('.crit');
    $(buttons).prop('disabled', true);

    $('.edit').click(function() {
        var button = $(this).closest("tr").find(".crit");  // closest element with the crit-class
        var status = button.prop("disabled");              // current status
        button.prop("disabled", !status);                  // toggle disabled
    });
});

The same goes for the name attributes, these should also be unique.


问:
Is there a way to show an explanation of an option in a dropdown menu in Excel?
I've created a dropdown menu in Excel (cell A2) for a performance review sheet, which has the usual rating options (Excellent, Great, Good, etc.). Currently I have it tied to an IF statement in cell B2 to populate with an explanation of the chosen rating.

Is there a way to bring up the explanation in a pop-up when hovering over that rating in the dropdown?

For example, if I hovered over Excellent a pop up would show what that rating means.

答:
Yes there is. First, insert a comment by right-clicking on A2 and Insert Comment (this can be done using VBA, but for the simplicity of the example do it manually).

Then use the Worksheet_Change event within the sheet to trigger when the dropdown is changed. Send the text value to another function that edits the comment with the desired description (this can be done in the Worksheet_Change function but I perfer to split. See below code:

In the sheet module:

```<code>Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    If Intersect(Target, Range("A2")) Is Nothing Then Exit Sub

    Call ChangeText(Range("A2").Text)

End Sub
</code>```

In a normal module:

```<code>Sub ChangeText(iTxt As String)

    If iTxt = "Excellent" Then
        Range("A2").Comment.Text Text:="A"
    ElseIf iTxt = "Good" Then
        Range("A2").Comment.Text Text:="B"
    ElseIf iTxt = "Bad" Then
        Range("A2").Comment.Text Text:="C"
    End If

End Sub
</code>```

Body:
Yes there is. First, insert a comment by right-clicking on A2 and Insert Comment (this can be done using VBA, but for the simplicity of the example do it manually).

Then use the Worksheet_Change event within the sheet to trigger when the dropdown is changed. Send the text value to another function that edits the comment with the desired description (this can be done in the Worksheet_Change function but I perfer to split. See below code:

In the sheet module:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    If Intersect(Target, Range("A2")) Is Nothing Then Exit Sub

    Call ChangeText(Range("A2").Text)

End Sub

In a normal module:

Sub ChangeText(iTxt As String)

    If iTxt = "Excellent" Then
        Range("A2").Comment.Text Text:="A"
    ElseIf iTxt = "Good" Then
        Range("A2").Comment.Text Text:="B"
    ElseIf iTxt = "Bad" Then
        Range("A2").Comment.Text Text:="C"
    End If

End Sub


问:
Unable to establish SSL connection, how do I fix my SSL cert?
I'm trying to wget to my own box, and it can't be an internal address in the wget (so says another developer).

When I wget, I get this:

```<code>wget http://example.com
--2013-03-01 15:03:30--  http://example.com/
Resolving example.com... 172.20.0.224
Connecting to example.com|172.20.0.224|:80... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://www.example.com/ [following]
--2013-03-01 15:03:30--  https://www.example.com/
Resolving www.example.com... 172.20.0.224
Connecting to www.example.com|172.20.0.224|:443... connected.
OpenSSL: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
Unable to establish SSL connection.
</code>```

I believe it is because I do not have the certificate setup properly. Using openssl:

```<code>openssl s_client -connect example.com:443
CONNECTED(00000003)
15586:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_clnt.c:588:
</code>```

While if I do the same command on another site, it shows the entire cert.

Perhaps the ssl cert was never setup in the conf file on Apache for that domain?

If so, what should I be specifying in the virtualhost? Is there any alternative other than specifying --no-check-certificate because I don't want to do that?

答:
This problem happened for me only in special cases, when I called website from some internet providers,

I've configured only ip v4 in VirtualHost configuration of apache,
but some of router use ip v6, and when I added ip v6 to apache config the problem solved.

Body:
I'm trying to wget to my own box, and it can't be an internal address in the wget (so says another developer).

When I wget, I get this:

wget http://example.com
--2013-03-01 15:03:30--  http://example.com/
Resolving example.com... 172.20.0.224
Connecting to example.com|172.20.0.224|:80... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://www.example.com/ [following]
--2013-03-01 15:03:30--  https://www.example.com/
Resolving www.example.com... 172.20.0.224
Connecting to www.example.com|172.20.0.224|:443... connected.
OpenSSL: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
Unable to establish SSL connection.

I believe it is because I do not have the certificate setup properly. Using openssl:

openssl s_client -connect example.com:443
CONNECTED(00000003)
15586:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_clnt.c:588:

While if I do the same command on another site, it shows the entire cert.

Perhaps the ssl cert was never setup in the conf file on Apache for that domain?

If so, what should I be specifying in the virtualhost? Is there any alternative other than specifying --no-check-certificate because I don't want to do that?


问:
MYSWL database. Trying to display a table. res.length is undefind
I am working on displaying a mysql data table and creating a function which displays my data. When I run this function I receive the following error.

```<code>     for (var i = 0; i < res.length; i++) {
                              ^

TypeError: Cannot read property 'length' of undefined
</code>```

```<code>function viewProducts(){
    var query = 'SELECT id, product_name, department, price, stock_quantity  FROM products Where stock_quantity > 0';

    connection.query(query, function(err, res){
        console.log('Items for Sale');
        console.log('Id \t Name \t Department \t Price \t Quantity\n');

            for (var i = 0; i < res.length; i++) {
                console.log(
                    res[i].id + '\t' + res[i].product_name + '\t' + res[i].department + '\t' +
                    res[i].price + '\t' + res[i].quantity + '\n');
            };
         runSearch();
    });

}
</code>```

答:
whenever you're trying to implement any I/O operation always catch the error before continue the execution. like this:-</p>

```<code>function viewProducts(){
    var query = 'SELECT id, product_name, department, price, stock_quantity  FROM
 products Where stock_quantity > 0';
    connection.query(query, function(err, res){
     if(err) {
      console.log(err);
     } else {
         if(res.length > 0) {
// only get inside if response is there
        console.log('Items for Sale');
        console.log('Id \t Name \t Department \t Price \t Quantity\n');

            for (var i = 0; i < res.length; i++) {
                console.log(
                    res[i].id + '\t' + res[i].product_name + '\t' + res[i].department +
 '\t' +
                    res[i].price + '\t' + res[i].quantity + '\n');
            }
         runSearch();
      }
    });
 }
 }

</code>```

Body:
I am working on displaying a mysql data table and creating a function which displays my data. When I run this function I receive the following error.

     for (var i = 0; i < res.length; i++) {
                              ^

TypeError: Cannot read property 'length' of undefined

function viewProducts(){
    var query = 'SELECT id, product_name, department, price, stock_quantity  FROM products Where stock_quantity > 0';

    connection.query(query, function(err, res){
        console.log('Items for Sale');
        console.log('Id \t Name \t Department \t Price \t Quantity\n');

            for (var i = 0; i < res.length; i++) {
                console.log(
                    res[i].id + '\t' + res[i].product_name + '\t' + res[i].department + '\t' +
                    res[i].price + '\t' + res[i].quantity + '\n');
            };
         runSearch();
    });

}

Body:
whenever you're trying to implement any I/O operation always catch the error before continue the execution. like this:-

function viewProducts(){
    var query = 'SELECT id, product_name, department, price, stock_quantity  FROM
 products Where stock_quantity > 0';
    connection.query(query, function(err, res){
     if(err) {
      console.log(err);
     } else {
         if(res.length > 0) {
// only get inside if response is there
        console.log('Items for Sale');
        console.log('Id \t Name \t Department \t Price \t Quantity\n');

            for (var i = 0; i < res.length; i++) {
                console.log(
                    res[i].id + '\t' + res[i].product_name + '\t' + res[i].department +
 '\t' +
                    res[i].price + '\t' + res[i].quantity + '\n');
            }
         runSearch();
      }
    });
 }
 }


问:
HTML unordered list sucks in IE7
I've created a HTML ordered list which looks fine in FF, but pretty awful in IE.
My specific problems with the way IE displays the list are:

List markers are missing

Vertical spacing between list items is very uneven

It seems the superscripts are the cause of (2), but I'm not sure how I can fix this problem (without removing the superscripts).

EDIT: I gave up on my single-list dreams and split the list into 3 separate lists. I've removed the link from the text above to avoid confusing future readers.

Thanks,
Don

答:
As others mentioned the height is due to the superscripted text.

As for the bullets Floating a list-item doesn't work well in IE.  If you plan on doing a three column layout try something like this.

```<code><style type="text/css">
ul {
  float:left;
  padding:2em;
  width:14em;
}
</style>

<ul>
 <li>col1 - item1</li>
 <li>col1 - item2</li>
 <li>col1 - item3</li>
</ul>

<ul>
 <li>col2 - item1</li>
 <li>col2 - item2</li>
 <li>col2 - item3</li>
</ul>

<ul>
 <li>col3 - item1</li>
 <li>col3 - item2</li>
 <li>col3 - item3</li>
</ul>
</code>```

OwnerDisplayName: Don

ContentLicense: CC BY-SA 2.5

Title: HTML unordered list sucks in IE7

LastEditorDisplayName: Don

Body:
As others mentioned the height is due to the superscripted text.

As for the bullets Floating a list-item doesn't work well in IE.  If you plan on doing a three column layout try something like this.

<style type="text/css">
ul {
  float:left;
  padding:2em;
  width:14em;
}
</style>

<ul>
 <li>col1 - item1</li>
 <li>col1 - item2</li>
 <li>col1 - item3</li>
</ul>

<ul>
 <li>col2 - item1</li>
 <li>col2 - item2</li>
 <li>col2 - item3</li>
</ul>

<ul>
 <li>col3 - item1</li>
 <li>col3 - item2</li>
 <li>col3 - item3</li>
</ul>

OwnerDisplayName: bendewey


问:
Styling MathJax
I'm so confused about this.  I've searched for tutorials but can't find any that make much sense to me, how do I set a CSS class for MathJax output?  I just want to make the font big.  The current include is:

```<code><script type="text/javascript"
  src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
</code>```

At the bottom of my page.  Renders TEX fine, but I'd like to set some CSS on it!

Ideally I'd like to pass a CSS class name to it.

答:
Have you tried setting the scale option in your output processor?  See the manual.  You can set the configuration options either in a file or inline; this page covers the process.

Basically, you include a short snippet of JavaScript in your page, or in a file you include.  Example:

```<code><script type="text/javascript">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js"],
    "HTML-CSS": { scale: 100}
  });
</script>
</code>```

Also, you can simply surround the thing in a div with a CSS class applied.  View the source on this page.

```<code><div style="font-size: 500%;">
\[

  g\frac{d^2u}{dx^2} + L\sin u = 0

\]
</div>
</code>```

The equation will simply inherit the font size.

Title: Styling MathJax

Body:
I'm so confused about this.  I've searched for tutorials but can't find any that make much sense to me, how do I set a CSS class for MathJax output?  I just want to make the font big.  The current include is:

At the bottom of my page.  Renders TEX fine, but I'd like to set some CSS on it!

Ideally I'd like to pass a CSS class name to it.

Body:
Have you tried setting the scale option in your output processor?  See the manual.  You can set the configuration options either in a file or inline; this page covers the process.

Basically, you include a short snippet of JavaScript in your page, or in a file you include.  Example:

<script type="text/javascript">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js"],
    "HTML-CSS": { scale: 100}
  });
</script>

Also, you can simply surround the thing in a div with a CSS class applied.  View the source on this page.

<div style="font-size: 500%;">
\[

  g\frac{d^2u}{dx^2} + L\sin u = 0

\]
</div>

The equation will simply inherit the font size.


问:
Is there a library/code snipped which which can convert meshes to a sdf in vector representation for subvoxel exact representation?
I need to generate a sdf on a grid from a 2D mesh to represent the mesh as a closed body in cinder.

My first approach was to use a distance function (euclidean) to check if a gridpoint is close to a meshpoint and then set the value to - or +, but this resulted in bad resolution. Next I tried to add up distances to get a continuous distance field. which resulted in a blown up object.
I am not sure how to represent the the distance to a closed object described by a mesh (concav or convex). My current approach is described in the code below.

#include <iostream>
#include <fstream>
#include <string>
#include <Eigen/Dense>
#include <vector>
#include <algorithm>
#include <random>

using namespace std;
using namespace Eigen;
typedef Eigen::Matrix<double, 2, 1> Vector2;
typedef Eigen::Matrix<double, 3, 2> Vector32;
typedef std::vector<Vector2, Eigen::aligned_allocator<Vector2> > Vector2List;
typedef std::vector<Eigen::Vector3i, Eigen::aligned_allocator<Eigen::Vector3i> > Vector3iList;
typedef std::vector<Vector32> Vector32List;
typedef Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic> grid_t;

void f( Vector2List vertices, Vector3iList triangles)
{ // each entry of triangles describe which vertice point belongs
  // to a triangle of the mesh
grid_t sdf  = grid_t::Zero(resolution, resolution);
for (int x = 0; x < resolution; ++x) {
        for (int y = 0; y < resolution; ++y) {
            Vector2d pos((x + 0.5) / resolution, (y + 0.5) / resolution);
            double dist = 1 / double(resolution*resolution);
            double check = 100;
            double val = 0;
for (std::vector<Vector2>::iterator mean = vertices.begin(); mean != vertices.end(); ++mean) {
        //try sdf with euclidian distance function
                check = (pos - *mean).squaredNorm();
                if (check < dist) {
                    val = -1; break;
                }
                else {
                    val = 20;
                }

            }

            val *= resolution;
            static const double epsilon = 0.01;
            if (abs(val) < epsilon) {
                val = 0;
                numberOfClamped++;
            }
            sdf(x,  y) = val; //
        }
    }
}
```

答:
It seems as if you have a slight misunderstanding of what the SDF actually is. So let me start with this.

The Signed Distance Function is a function over 2D space that gives you the distance of the respective point to the closest point on the mesh. The distance is positive for points outside of the mesh and negative for points inside (or the other way around). Naturally, points directly on the mesh will have zero distance. We can represent this function formally as:

```<code>sdf(x, y) = distance
</code>```

This is a continuous function and we need a discrete representation that we can work with. A common choice is to use a uniform grid like the one that you want to use. We then sample the SDF at the grid points. Once we have distance values for all our grid points, we can interpolate the SDF between them to get the SDF everywhere. Note that each sample corresponds to a single point and not an area (e.g., a cell).

With this in mind, let us take a look at your code:

```<code>Vector2d pos((x + 0.5) / resolution, (y + 0.5) / resolution);
</code>```

This depends on how the grid point indices map to global coordinates. It might be correct. However, it looks as if it assumes that sample positions are located in the middle of the respective cells. Again, this might be correct, but I assume the + 0.5 should be left away.

```<code>for (std::vector<Vector2>::iterator mean = vertices.begin(); mean != vertices.end(); ++mean)
</code>```

This is an approximation of the SDF. It calculates the closest vertex of the mesh and not the closest point (which may lie on an edge). For dense meshes, this should be fine. If you have coarse meshes, you should iterate the edges and calculate the closest points on these.

```<code>if (check < dist) {
    val = -1; break;
} else {
    val = 20;
}
</code>```

I don't really know what this is. As explained above, the value of the SDF is the signed distance. Not some arbitrary value. Also the sign should not correspond to whether the mesh is close to the grid position. So, what you should have done instead is:

```<code>if(check < val * val) {
    //this point is closer than the current closest point
    val = std::sqrt(check); //set to absolute distance
    if(*mean is inside the mesh)
        val *= -1; //invert the sign
}
</code>```

And finally, this piece:

```<code>val *= resolution;
static const double epsilon = 0.01;
if (abs(val) < epsilon) {
    val = 0;
    numberOfClamped++;
}
</code>```

Again, I don't know what this is supposed to do. Just leave it away.

Body:
It seems as if you have a slight misunderstanding of what the SDF actually is. So let me start with this.

The Signed Distance Function is a function over 2D space that gives you the distance of the respective point to the closest point on the mesh. The distance is positive for points outside of the mesh and negative for points inside (or the other way around). Naturally, points directly on the mesh will have zero distance. We can represent this function formally as:

sdf(x, y) = distance

This is a continuous function and we need a discrete representation that we can work with. A common choice is to use a uniform grid like the one that you want to use. We then sample the SDF at the grid points. Once we have distance values for all our grid points, we can interpolate the SDF between them to get the SDF everywhere. Note that each sample corresponds to a single point and not an area (e.g., a cell).

With this in mind, let us take a look at your code:

Vector2d pos((x + 0.5) / resolution, (y + 0.5) / resolution);

This depends on how the grid point indices map to global coordinates. It might be correct. However, it looks as if it assumes that sample positions are located in the middle of the respective cells. Again, this might be correct, but I assume the + 0.5 should be left away.

for (std::vector<Vector2>::iterator mean = vertices.begin(); mean != vertices.end(); ++mean)

This is an approximation of the SDF. It calculates the closest vertex of the mesh and not the closest point (which may lie on an edge). For dense meshes, this should be fine. If you have coarse meshes, you should iterate the edges and calculate the closest points on these.

if (check < dist) {
    val = -1; break;
} else {
    val = 20;
}

I don't really know what this is. As explained above, the value of the SDF is the signed distance. Not some arbitrary value. Also the sign should not correspond to whether the mesh is close to the grid position. So, what you should have done instead is:

if(check < val * val) {
    //this point is closer than the current closest point
    val = std::sqrt(check); //set to absolute distance
    if(*mean is inside the mesh)
        val *= -1; //invert the sign
}

And finally, this piece:

val *= resolution;
static const double epsilon = 0.01;
if (abs(val) < epsilon) {
    val = 0;
    numberOfClamped++;
}

Again, I don't know what this is supposed to do. Just leave it away.