问:
Vapor project not building/running with Swift 4 and Xcode 9
I have the most recent version of Xcode 9 installed and have reinstalled vapor with brew a couple times now, but I'm still getting the following error whenever I try to build/run/update the project.

Here's what I'm working with

```<code>1.) Vapor Toolbox: 3.1.2

2.) Apple Swift version 4.0 (swiftlang-900.0.43 clang-900.0.22.8)
    Target: x86_64-apple-macosx10.9

3.) Xcode 9.0
    Build version 9M136h
</code>```

Error: Could not generate Xcode project: error: manifest parse error(s):
/var/folder/60/n3ldjzgs5vsg06v17_1yy44h0000gn/T/TemporaryFile.VwrbJo.swift:41:5
: error: argument 'targets' must preceed argument 'dependencies'
    targets" [
    ^
error: The product dependency 'Vapor' was not found.
error: The product dependency 'FluentProvider' was not found.
error: The product dependency 'Testing' was not found.
```

<p>Here is my Package.swift file. Looking at my original error, I did try switching the 'targets' and 'dependencies' order in which they appear in the file. This didn't solve anything and produced the following error message:  <code>error: argument 'dependencies' must precede argument 'targets'</code></p>

<p><em>Package.swift</em></p>

<pre class="lang-swift prettyprint-override"><code>let package = Package(
    name: "test",
    products: [
        .library(name: "App", targets: ["App"]),
        .executable(name: "Run", targets: ["Run"])
    ],
    dependencies: [
        .package(url: "https://github.com/vapor/vapor.git", .upToNextMajor(from: "2.1.0")),
        .package(url: "https://github.com/vapor/fluent-provider.git", .upToNextMajor(from: "1.2.0")),
    ],
    targets: [
        .target(
            name: "App",
            dependencies: ["Vapor", "FluentProvider"],
            exclude: [
                    "Config",
                    "Public",
                    "Resources",
                    ]
        ),
        .target(name: "Run", dependencies: ["App"]),
        .testTarget(name: "AppTests", dependencies: ["App", "Testing"])
    ]
)
</code>```

答:
Xcode 12 / Swift 5.3 Update

vapor is now part of homebrew/core. Source: github homebrew-core/Formula/vapor.rb.

##### If applicable, remove the obsolete 'vapor/tap' #####
## List current taps:
brew tap
# homebrew/core
# vapor/tap
## Remove tap:
brew untap vapor/tap

#### Install current version of vapor #####
brew install vapor
brew upgrade vapor
```
<p><strong>Xcode 9 / Swift 4</strong></p>
<ol>
<li><p>Double Check Versions: "the most recent releases" would be at least <strong>Xcode 9.1</strong> (9B55) and Apple <strong>Swift 4.0.2</strong> (swiftlang-900.0.69.1 clang-900.0.38)</p>
</li>
<li><p>Verify that the first line in <code>Packages.swift</code> is <code>// swift-tools-version:4.0</code>.  <em><em>Without <code>swift-tools-version</code> line, Packages.swift could be processed as swift-tools-version 3.</em> which <em>will cause an error</em>.</em>*</p>
</li>
</ol>
<pre class="lang-sh prettyprint-override"><code>cd _PROJECT_PATH_
swift package tools-version
# if not 4.0.0, then …
swift package tools-version --set-current
</code>```

An example, Package.swift is shown below. See Swift Package Manager Manifest API Redesign and swift-package-manager Usage Documentation for additional information.

// swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift
// required to build this package.
// Syntax: '// swift-tools-version:<specifier>' on the 1st line

import PackageDescription

let package = Package(
    name: "test",
    products: [
        .library(name: "App", targets: ["App"]),
        .executable(name: "Run", targets: ["Run"])
    ],
    dependencies: [
        .package(url: "https://github.com/vapor/vapor.git", .upToNextMajor(from: "2.3.0")),
        .package(url: "https://github.com/vapor/fluent-provider.git", .upToNextMajor(from: "1.3.0")),
    ],
    targets: [
        .target(
            name: "App",
            dependencies: ["Vapor", "FluentProvider"],
            exclude: [
                    "Config",
                    "Public",
                    "Resources",
                    ]
        ),
        .target(name: "Run", dependencies: ["App"]),
        .testTarget(name: "AppTests", dependencies: ["App", "Testing"])
    ]
)
```
<ol start="3">
<li>Recheck</li>
</ol>
<pre class="lang-sh prettyprint-override"><code>cd _PROJECT_PATH_
swift package tools-version
# should be 4.0.0

vapor clean
vapor update
vapor --version

# Vapor Toolbox: 3.1.2
# Vapor Framework: 2.3.0
</code>```

Try to build again.

More notes are posted on StackOverflow here for using Xcode 9 and Swift 4 with Vapor 2.

The GitHub repository Vapor Examples Lab has several example projects which have been migrated to Vapor 2 and Swift 4.

Body:
I have the most recent version of Xcode 9 installed and have reinstalled vapor with brew a couple times now, but I'm still getting the following error whenever I try to build/run/update the project.

Here's what I'm working with

1.) Vapor Toolbox: 3.1.2

2.) Apple Swift version 4.0 (swiftlang-900.0.43 clang-900.0.22.8)
    Target: x86_64-apple-macosx10.9

3.) Xcode 9.0
    Build version 9M136h

Error: Could not generate Xcode project: error: manifest parse error(s):
/var/folder/60/n3ldjzgs5vsg06v17_1yy44h0000gn/T/TemporaryFile.VwrbJo.swift:41:5
: error: argument 'targets' must preceed argument 'dependencies'
    targets" [
    ^
error: The product dependency 'Vapor' was not found.
error: The product dependency 'FluentProvider' was not found.
error: The product dependency 'Testing' was not found.

Here is my Package.swift file. Looking at my original error, I did try switching the 'targets' and 'dependencies' order in which they appear in the file. This didn't solve anything and produced the following error message:  error: argument 'dependencies' must precede argument 'targets'

Package.swift

let package = Package(
    name: "test",
    products: [
        .library(name: "App", targets: ["App"]),
        .executable(name: "Run", targets: ["Run"])
    ],
    dependencies: [
        .package(url: "https://github.com/vapor/vapor.git", .upToNextMajor(from: "2.1.0")),
        .package(url: "https://github.com/vapor/fluent-provider.git", .upToNextMajor(from: "1.2.0")),
    ],
    targets: [
        .target(
            name: "App",
            dependencies: ["Vapor", "FluentProvider"],
            exclude: [
                    "Config",
                    "Public",
                    "Resources",
                    ]
        ),
        .target(name: "Run", dependencies: ["App"]),
        .testTarget(name: "AppTests", dependencies: ["App", "Testing"])
    ]
)

Body:
Xcode 12 / Swift 5.3 Update

vapor is now part of homebrew/core. Source: github homebrew-core/Formula/vapor.rb.

##### If applicable, remove the obsolete 'vapor/tap' #####
## List current taps:
brew tap
# homebrew/core
# vapor/tap
## Remove tap:
brew untap vapor/tap

#### Install current version of vapor #####
brew install vapor
brew upgrade vapor

Xcode 9 / Swift 4

Double Check Versions: "the most recent releases" would be at least Xcode 9.1 (9B55) and Apple Swift 4.0.2 (swiftlang-900.0.69.1 clang-900.0.38)

Verify that the first line in Packages.swift is // swift-tools-version:4.0.  Without swift-tools-version line, Packages.swift could be processed as swift-tools-version 3. which will cause an error.*

cd _PROJECT_PATH_
swift package tools-version
# if not 4.0.0, then …
swift package tools-version --set-current

An example, Package.swift is shown below. See Swift Package Manager Manifest API Redesign and swift-package-manager Usage Documentation for additional information.

// swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift
// required to build this package.
// Syntax: '// swift-tools-version:<specifier>' on the 1st line

import PackageDescription

let package = Package(
    name: "test",
    products: [
        .library(name: "App", targets: ["App"]),
        .executable(name: "Run", targets: ["Run"])
    ],
    dependencies: [
        .package(url: "https://github.com/vapor/vapor.git", .upToNextMajor(from: "2.3.0")),
        .package(url: "https://github.com/vapor/fluent-provider.git", .upToNextMajor(from: "1.3.0")),
    ],
    targets: [
        .target(
            name: "App",
            dependencies: ["Vapor", "FluentProvider"],
            exclude: [
                    "Config",
                    "Public",
                    "Resources",
                    ]
        ),
        .target(name: "Run", dependencies: ["App"]),
        .testTarget(name: "AppTests", dependencies: ["App", "Testing"])
    ]
)

Recheck

cd _PROJECT_PATH_
swift package tools-version
# should be 4.0.0

vapor clean
vapor update
vapor --version

# Vapor Toolbox: 3.1.2
# Vapor Framework: 2.3.0

Try to build again.

More notes are posted on StackOverflow here for using Xcode 9 and Swift 4 with Vapor 2.

The GitHub repository Vapor Examples Lab has several example projects which have been migrated to Vapor 2 and Swift 4.


来源: stackexchange

问:
Error during make: error adding symbols: DSO missing from command line
I am trying to compile some code downloaded from a git repository (OpenNI2, https://github.com/occipital/OpenNI2). I am getting the following errors after running make:

```<code>make -C Source/Tools/NiViewer
make[1]: Entering directory `/home/karnivaurus/Data/Libraries/OpenNI2/Source/Tools/NiViewer'
g++ -o ../../../Bin/x64-Release/NiViewer ./../../../Bin/Intermediate/x64-Release/NiViewer/Device.o ./../../../Bin/Intermediate/x64-Release/NiViewer/Draw.o ./../../../Bin/Intermediate/x64-Release/NiViewer/Keyboard.o ./../../../Bin/Intermediate/x64-Release/NiViewer/Menu.o ./../../../Bin/Intermediate/x64-Release/NiViewer/MouseInput.o ./../../../Bin/Intermediate/x64-Release/NiViewer/NiViewer.o ./../../../Bin/Intermediate/x64-Release/NiViewer/Capture.o -L../../../ThirdParty/PSCommon/XnLib/Bin/x64-Release -L../../../Bin/x64-Release -lglut -lGL -lOpenNI2 -lXnLib -Wl,-rpath ./
/usr/bin/ld: ../../../ThirdParty/PSCommon/XnLib/Bin/x64-Release/libXnLib.a(XnLinuxMutex.o): undefined reference to symbol 'pthread_mutexattr_settype@@GLIBC_2.2.5'
//lib/x86_64-linux-gnu/libpthread.so.0: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
make[1]: *** [../../../Bin/x64-Release/NiViewer] Error 1
make[1]: Leaving directory `/home/karnivaurus/Data/Libraries/OpenNI2/Source/Tools/NiViewer'
make: *** [Source/Tools/NiViewer] Error 2
</code>```

Any ideas on how I should go about solving this?

答:
You need add the pthread library into the target_link_libraries. You can edit your CMakeLists.txt file as follow. This solution works for me.</p>

```<code>    target_link_libraries(ExcutableFileName ${Existed_LIBRARY})
    -->
    target_link_libraries(ExcutableFileName ${Existed_LIBRARY} pthread)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to compile some code downloaded from a git repository (OpenNI2, https://github.com/occipital/OpenNI2). I am getting the following errors after running make:

make -C Source/Tools/NiViewer
make[1]: Entering directory `/home/karnivaurus/Data/Libraries/OpenNI2/Source/Tools/NiViewer'
g++ -o ../../../Bin/x64-Release/NiViewer ./../../../Bin/Intermediate/x64-Release/NiViewer/Device.o ./../../../Bin/Intermediate/x64-Release/NiViewer/Draw.o ./../../../Bin/Intermediate/x64-Release/NiViewer/Keyboard.o ./../../../Bin/Intermediate/x64-Release/NiViewer/Menu.o ./../../../Bin/Intermediate/x64-Release/NiViewer/MouseInput.o ./../../../Bin/Intermediate/x64-Release/NiViewer/NiViewer.o ./../../../Bin/Intermediate/x64-Release/NiViewer/Capture.o -L../../../ThirdParty/PSCommon/XnLib/Bin/x64-Release -L../../../Bin/x64-Release -lglut -lGL -lOpenNI2 -lXnLib -Wl,-rpath ./
/usr/bin/ld: ../../../ThirdParty/PSCommon/XnLib/Bin/x64-Release/libXnLib.a(XnLinuxMutex.o): undefined reference to symbol 'pthread_mutexattr_settype@@GLIBC_2.2.5'
//lib/x86_64-linux-gnu/libpthread.so.0: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
make[1]: *** [../../../Bin/x64-Release/NiViewer] Error 1
make[1]: Leaving directory `/home/karnivaurus/Data/Libraries/OpenNI2/Source/Tools/NiViewer'
make: *** [Source/Tools/NiViewer] Error 2

Any ideas on how I should go about solving this?

Body:
You need add the pthread library into the target_link_libraries. You can edit your CMakeLists.txt file as follow. This solution works for me.

    target_link_libraries(ExcutableFileName ${Existed_LIBRARY})
    -->
    target_link_libraries(ExcutableFileName ${Existed_LIBRARY} pthread)

ContentLicense: CC BY-SA 3.0


问:
Some items not formatted right but the rest are
I do not know why some items are not formatted right, the short names seem to be fine but the longer ones throw themselfs off
https://pastebin.com/pkGL0Nwy</p>

```<code>prices = {}
groceries = []

file = open("grocery_store_price_list.txt", "r")
for strx in file:
    strs = list(filter(None, strx.strip().split(" ")))
    prices[strs[0]] = [strs[1]], [strs[2]]
file.close()

file = open("my_personal_gro_list.txt", "r")
for strx in file :
    strs = list(filter(None, strx.strip().split(" ")))
    groceries.append([strs[1], strs[0]])

headings = "{:6s} {:9s} {:6s} {:7s} {:6s}".format("item", "qty", "unit", "cost", "total")

print(headings)

finalCost = 0

for strs in groceries:
    item = strs[0]
    qty = int(strs[1])
    unit = prices[strs[0]][1]
    cost = float(prices[strs[0]][0][0])
    total = qty*cost

    finalCost += total

    print(item, qty, unit, cost, total,)
</code>```

答:
```<code>print("{item}\t{qty}\t{unit}\t{cost}\t{total}".format(item=item, qty=qty, unit=unit, cost=cost, total=total))
</code>```

Body:
I do not know why some items are not formatted right, the short names seem to be fine but the longer ones throw themselfs off
https://pastebin.com/pkGL0Nwy

prices = {}
groceries = []

file = open("grocery_store_price_list.txt", "r")
for strx in file:
    strs = list(filter(None, strx.strip().split(" ")))
    prices[strs[0]] = [strs[1]], [strs[2]]
file.close()

file = open("my_personal_gro_list.txt", "r")
for strx in file :
    strs = list(filter(None, strx.strip().split(" ")))
    groceries.append([strs[1], strs[0]])

headings = "{:6s} {:9s} {:6s} {:7s} {:6s}".format("item", "qty", "unit", "cost", "total")

print(headings)

finalCost = 0

for strs in groceries:
    item = strs[0]
    qty = int(strs[1])
    unit = prices[strs[0]][1]
    cost = float(prices[strs[0]][0][0])
    total = qty*cost

    finalCost += total

    print(item, qty, unit, cost, total,)


问:
Lightbox video Gallery for Bootstrap not working
I'm using bootstrap 4 for a website which includes an image gallery and video gallery. I'm pulling some sourcing from http://ashleydw.github.io/lightbox/#image-gallery for the lightbox work.

I've implemented the css and the jQuery script at the bottom of my body. The image gallery works perfectly so I know the implementation seems to be okay. However, when I input the html for the video gallery, the modal box appears on click, but no video runs. This is true even with their default videos listed on the website.

Should look like this:

With this default code:

```<code><a href="http://youtu.be/iQ4D273C7Ac" data-toggle="lightbox" data-gallery="youtubevideos" class="col-sm-4">
    <img src="http://i1.ytimg.com/vi/iQ4D273C7Ac/mqdefault.jpg" class="img-fluid">
</a>
</code>```

And here is my code:

```<code>    <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Band Homepage" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css?family=Syncopate:400,700" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ekko-lightbox/5.3.0/ekko-lightbox.css"/>
    <link rel="stylesheet" href="css/main-style.css">

    <title>Truth Takes Time</title>
</head>

<body>

    <!--navbar-->
    <nav class="navbar navbar-expand-lg navbar-light">
        <div class="container">
            <a class="navbar-brand" href="#">Truth Takes Time</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
                <div class="navbar-nav ml-auto">
                    <a class="nav-item nav-link active" href="#">Home <span class="sr-only">(current)</span></a>
                    <a class="nav-item nav-link" href="#">News</a>
                    <a class="nav-item nav-link" href="#">Photos</a>
                    <a class="nav-item nav-link" href="#">Videos</a>
                    <a class="nav-item nav-link" href="#">Music</a>
                    <a class="nav-item nav-link" href="#">Tour</a>
                    <a class="nav-item nav-link" href="#">Store</a>
                </div>
            </div>
        </div>
    </nav>

    <!--jumbotron-->
    <div class="jumbotron jumbotron-fluid">
        <div class="container text-center">
            <h1 class="display-3">Truth Takes Time</h1>
        </div>
    </div>

    <section class="section-header mt-5 mb-5">
            <div class="card">
                <div class="card-header">
                    <div class="container">
                        <div class="row">
                            <i class="fa fa-newspaper-o fa-3x mr-4 mt-2" aria-hidden="true"></i><h4 class="display-4"> Latest News</h4>
                            <a href="#" class="btn btn-link ml-auto mt-3">View all news   <i class="fa fa-arrow-circle-o-right" aria-hidden="true"></i></a>
                        </div>
                    </div>
                </div>
            </div>
    </section>

    <section id="news">
        <div class="container">
            <div class="row mb-3">
                <div class="col-md-6">
                    <div class="card mb-3">
                        <a href="#">
                            <img class="card-img-top" src="img/pexels-photo-257909.jpeg" alt="Card image cap">
                        </a>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card-body">
                        <a href="#">
                            <h4 class="card-title">Tis the Treason Holiday Bundle</h4>
                        </a>
                        <p class="card-text">We’ve added a few new items the webstore, including this limited Tis the Treason...</p>
                        <p class="card-text"><small>November 3, 2017</small></p>
                    </div>
                </div>
            </div>
            <div class="row mb-3">
                <div class="col-md-6">
                    <div class="card mb-3">
                        <a href="#">
                            <img class="card-img-top" src="img/pexels-photo-69212.jpeg" alt="Card image cap">
                        </a>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card-body">
                        <a href="#">
                            <h4 class="card-title">Vevo "Why I Vote"</h4>
                        </a>
                        <p class="card-text">Tim recently sat down with Vevo to discuss why it's improtant to vote.  Check it out </p>
                        <p class="card-text"><small>October 23, 2017</small></p>
                    </div>
                </div>
            </div>
            <div class="row mb-3">
                <div class="col-md-6">
                    <div class="card mb-3">
                        <a href="#">
                            <img class="card-img-top" src="img/pexels-photo-167523.jpeg" alt="Card image cap">
                        </a>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card-body">
                        <a href="#">
                            <h4 class="card-title">Synthesis available everywhere now!</h4>
                        </a>
                        <p class="card-text">Our new album, Synthesis, is available everywhere now!</p>
                        <p class="card-text"><small>September 12, 2017</small></p>
                    </div>
                </div>
            </div>
            <div class="row mb-3">
                <div class="col-md-6">
                    <div class="card mb-3">
                        <a href="#">
                            <img class="card-img-top" src="img/pexels-photo-167580.jpeg" alt="Card image cap">
                        </a>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card-body">
                        <a href="#">
                            <h4 class="card-title">2017 Fall Tour</h4>
                        </a>
                        <p class="card-text">We’re hitting the road this Fall for a run of headline dates across the US + Canada with special guests!</p>
                        <p class="card-text"><small>August 9, 2017</small></p>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <section class="section-header mt-5 mb-5">
        <div class="card">
            <div class="card-header">
                <div class="container">
                    <div class="row">
                        <i class="fa fa-camera fa-3x mr-4 mt-2" aria-hidden="true"></i><h4 class="display-4"> Photos</h4>
                        <a href="#" class="btn btn-link ml-auto mt-3">View all pics   <i class="fa fa-arrow-circle-o-right" aria-hidden="true"></i></a>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <section id="picGallery">
        <div class="container mt-5">
            <div class="row mb-3">
                <div class="col-md-3">
                    <a href="img/pexels-photo-92080.jpeg" data-toggle="lightbox" data-gallery="picGallery">
                        <img src="img/pexels-photo-92080.jpeg" class="img-fluid" alt="#">
                    </a>
                </div>
                <div class="col-md-3">
                    <a href="img/pexels-photo-167378.jpeg" data-toggle="lightbox" data-gallery="picGallery">
                        <img src="img/pexels-photo-167378.jpeg" class="img-fluid" alt="#">
                    </a>
                </div>
                <div class="col-md-3">
                    <a href="img/pexels-photo-417473.jpeg" data-toggle="lightbox" data-gallery="picGallery">
                        <img src="img/pexels-photo-417473.jpeg" class="img-fluid" alt="#">
                    </a>
                </div>
                <div class="col-md-3">
                    <a href="img/pexels-photo-354304.jpeg" data-toggle="lightbox" data-gallery="picGallery">
                        <img src="img/pexels-photo-354304.jpeg" class="img-fluid" alt="#">
                    </a>
                </div>
            </div>
            <div class="row mb-3">
                <div class="col-md-3">
                    <a href="img/pexels-photo-167609.jpeg" data-toggle="lightbox" data-gallery="picGallery">
                        <img src="img/pexels-photo-167609.jpeg" class="img-fluid" alt="#">
                    </a>
                </div>
                <div class="col-md-3">
                    <a href="img/pexels-photo-167382.jpeg" data-toggle="lightbox" data-gallery="picGallery">
                        <img src="img/pexels-photo-167382.jpeg" class="img-fluid" alt="#">
                    </a>
                </div>
                <div class="col-md-3">
                    <a href="img/pexels-photo-167466.jpeg" data-toggle="lightbox" data-gallery="picGallery">
                        <img src="img/pexels-photo-167466.jpeg" class="img-fluid" alt="#">
                    </a>
                </div>
                <div class="col-md-3">
                    <a href="img/pexels-photo-141376.jpeg" data-toggle="lightbox" data-gallery="picGallery">
                        <img src="img/pexels-photo-141376.jpeg" class="img-fluid" alt="#">
                    </a>
                </div>
            </div>
        </div>
    </section>

    <section class="section-header mt-5 mb-5">
        <div class="card">
            <div class="card-header">
                <div class="container">
                    <div class="row">
                        <i class="fa fa-video-camera fa-3x mr-4 mt-2" aria-hidden="true"></i><h4 class="display-4"> Videos</h4>
                        <a href="#" class="btn btn-link ml-auto mt-3">View all videos   <i class="fa fa-arrow-circle-o-right" aria-hidden="true"></i></a>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <section id="vidGallery">
        <div class="container mt-5">
            <div class="row mb-3">
                <div class="col-sm-3">
                    <a href="http://www.youtube.com/watch?v=k6mFF3VmVAs" data-toggle="lightbox" data-gallery="youtubevideos">
                        <img src="http://i1.ytimg.com/vi/yP11r5n5RNg/mqdefault.jpg" class="img-fluid">
                    </a>
                </div>
                <div class="col-sm-3">
                    <a href="http://youtu.be/iQ4D273C7Ac" data-toggle="lightbox" data-gallery="youtubevideos">
                        <img src="http://i1.ytimg.com/vi/iQ4D273C7Ac/mqdefault.jpg" class="img-fluid">
                    </a>
                </div>
                <div class="col-sm-3">
                    <a href="//www.youtube.com/embed/b0jqPvpn3sY" data-toggle="lightbox" data-gallery="youtubevideos">
                        <img src="http://i1.ytimg.com/vi/b0jqPvpn3sY/mqdefault.jpg" class="img-fluid">
                    </a>
                </div>
                <div class="col-sm-3">
                    <a href="http://youtu.be/iQ4D273C7Ac" data-toggle="lightbox" data-gallery="youtubevideos">
                        <img src="http://i1.ytimg.com/vi/iQ4D273C7Ac/mqdefault.jpg" class="img-fluid">
                    </a>
                </div>
            </div>
            <div class="row mb-3">
                <div class="col-sm-3">
                    <a href="http://www.youtube.com/watch?v=k6mFF3VmVAs" data-toggle="lightbox" data-gallery="youtubevideos">
                        <img src="http://i1.ytimg.com/vi/yP11r5n5RNg/mqdefault.jpg" class="img-fluid">
                    </a>
                </div>
                <div class="col-sm-3">
                    <a href="http://youtu.be/iQ4D273C7Ac" data-toggle="lightbox" data-gallery="youtubevideos">
                        <img src="http://i1.ytimg.com/vi/iQ4D273C7Ac/mqdefault.jpg" class="img-fluid">
                    </a>
                </div>
                <div class="col-sm-3">
                    <a href="//www.youtube.com/embed/b0jqPvpn3sY" data-toggle="lightbox" data-gallery="youtubevideos">
                        <img src="http://i1.ytimg.com/vi/b0jqPvpn3sY/mqdefault.jpg" class="img-fluid">
                    </a>
                </div>
                <div class="col-sm-3">
                    <div class="embed-responsive embed-responsive-16by9">
                        <iframe class="embed-responsive-item" src="https://www.youtube.com/embed/zpOULjyy-n8?rel=0" allowfullscreen></iframe>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <section class="section-header mt-5 mb-5">
        <div class="card">
            <div class="card-header">
                <div class="container">
                    <div class="row">
                        <i class="fa fa-shopping-basket fa-3x mr-4 mt-2" aria-hidden="true"></i><h4 class="display-4"> Store</h4>
                        <a href="#" class="btn btn-link ml-auto mt-3">View all merch   <i class="fa fa-arrow-circle-o-right" aria-hidden="true"></i></a>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <script src="https://use.fontawesome.com/9a90c9b9d4.js"></script>
    <!--bootstrap standard Javascript-->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>

    <!--lightbox js-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ekko-lightbox/5.3.0/ekko-lightbox.js"></script>

    <script>
        $(document).on('click', '[data-toggle="lightbox"]', function (event) {
            event.preventDefault();
            $(this).ekkoLightbox();
        });
    </script>

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

The only difference is I remove the class="col-md-4" from the default code as my  tag is already in a col-md-3.

Mine comes out looking like this:

答:
I believe your issue is going to be with the iframe looking for the video in the local environment - I am assuming you are developing locally and not serving your file via a server. The iframe will be basically looking for file://youtube.com/embed/someVideoBlahBlah. This wiki article talks about it https://en.wikipedia.org/wiki/File_URI_scheme. In order to fix the issue you will have to develop via a server. I created a super simple Express server (see code below), ran your code and the videos work perfectly. In other words - your code is fine, it's just the way you are serving your html file that's causing the problem.

```<code>const express = require('express')
const app = express()
const path = require('path');

app.get('/', (req, res) => res.sendFile(path.join(__dirname + '/index.html')))

app.listen(3000, () => console.log('Example app listening on port 3000!'))
</code>```

Body:
I'm using bootstrap 4 for a website which includes an image gallery and video gallery. I'm pulling some sourcing from http://ashleydw.github.io/lightbox/#image-gallery for the lightbox work.

I've implemented the css and the jQuery script at the bottom of my body. The image gallery works perfectly so I know the implementation seems to be okay. However, when I input the html for the video gallery, the modal box appears on click, but no video runs. This is true even with their default videos listed on the website.

Should look like this:

With this default code:

And here is my code:

    <!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Band Homepage" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css?family=Syncopate:400,700" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ekko-lightbox/5.3.0/ekko-lightbox.css"/>
    <link rel="stylesheet" href="css/main-style.css">

    <title>Truth Takes Time</title>

            Truth Takes Time
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">

            </button>

                    Home (current)
                    News
                    Photos
                    Videos
                    Music
                    Tour
                    Store

Truth Takes Time

 Latest News

                            View all news

Tis the Treason Holiday Bundle

We’ve added a few new items the webstore, including this limited Tis the Treason...

November 3, 2017

Vevo "Why I Vote"

Tim recently sat down with Vevo to discuss why it's improtant to vote.  Check it out

October 23, 2017

Synthesis available everywhere now!

Our new album, Synthesis, is available everywhere now!

September 12, 2017

2017 Fall Tour

We’re hitting the road this Fall for a run of headline dates across the US + Canada with special guests!

August 9, 2017

 Photos

                        View all pics

 Videos

                        View all videos

 Store

                        View all merch

The only difference is I remove the class="col-md-4" from the default code as my  tag is already in a col-md-3.

Mine comes out looking like this:

Body:
I believe your issue is going to be with the iframe looking for the video in the local environment - I am assuming you are developing locally and not serving your file via a server. The iframe will be basically looking for file://youtube.com/embed/someVideoBlahBlah. This wiki article talks about it https://en.wikipedia.org/wiki/File_URI_scheme. In order to fix the issue you will have to develop via a server. I created a super simple Express server (see code below), ran your code and the videos work perfectly. In other words - your code is fine, it's just the way you are serving your html file that's causing the problem.

const express = require('express')
const app = express()
const path = require('path');

app.get('/', (req, res) => res.sendFile(path.join(__dirname + '/index.html')))

app.listen(3000, () => console.log('Example app listening on port 3000!'))


问:
LetsEncrypt SSL Certificates with multi domains and multi subdomains
We've been using a PositiveSSL Multi-Domain Cert for some years, and that's been working fine. Under that Cert, we have, for instance:

domain1:

mail.domain1.com

www.domain1.com

domain1.com

domain2:

mail.domain2.fr

www.domain2.fr

domain2.fr

etc., with a total of 5 different domains.

Now, since we're going to expand our domain base and that the current Cert is expiring, we're looking closely at Lets-Encrypt.

Before I get into this, however, I'd like to know a couple of things:

(1)- does every subdomain (mail. www., etc.) as well as their main respective domain have to be listed in the main certificate? I'm mainly asking that because (a) that was my original understanding, and (b) the verification stage with Lets-Encrypt will differ (preferred-challenges=dns instead of by default apache-based), which will lead me to add DNS records for each domain/subdomain.

(2)- if it is indeed needed (and if I have no choice but use preferred-challenges=dns, at the time of the next Cert renewal (i.e. < 90 days), should the DNS records still have to be present? I'm asking this because last time I left the DNS records after creation, the mail server couldn't be reached anymore after the DNS propagation time. I'm pretty sure that it was because of my bad setup, but it's a risk I prefer to avoid taking.

(3)- if I'm missing here of you have a better advice to give me, let me know.

答:
At https://websocket.email I am using the Subject Alternative Name (SAN) mechanism to handle api.websocket.email etc. I did not have to configure DNS records and used http challenges. The exact way you would do this depends on your acme client. Mine had the option listed under a config section "alternative names".

Edit: To clarify, I needed DNS records to point to my subdomains all to the same server, I am using this acme client - https://man.openbsd.org/acme-client.conf.5 and set the alternative names option. When getting my certificates I could see in my http logs, lets-encrypt fetching a single challenge file per domain to prove I own it.


问:
how to write the following sql query in linq
```<code>select
    coalesce(x.value,a.default_value) as value
from table1 a
left outer join
    (
       select
          b.configid,
          b.value
       from table2 b
       join table3 c on b.dataid=c.id
       where c.id=0
    )x on a.id=x.configid
where a.key='abc'
</code>```

答:
For translating SQL to LINQ,

Translate subselects as separate variables

Translate each clause in LINQ clause order, leaving monadic operators (DISTINCT, TOP, etc) as functions applied to the whole LINQ query.

Use table aliases as range variables. Use column aliases as anonymous type field names.

Use anonymous types (new { }) for multiple columns

Left Join is simulated by using a join variable and doing another from from the join variable followed by .DefaultIfEmpty().

Replace coalesce with the conditional operator and a null test.


问:
Reading from URL, store data as double?
```<code>public static void getClientUpdate() {
    try {
        String inputLine;
        double version = 0;
        URL url = new URL("http://ds-forums.com/client/version.txt");
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
        version = inputLine;
        System.out.println("The version is: " + version);
    } catch (Exception x) {
        System.out.println(x);
    }
}
</code>```

This is going to sound really stupid but I have a txt file that contains a double and I want to save it as a double. Instead it wants a string.  Am I doing this wrong or is there just a few steps I need to add?

答:
You can parse the string you obtained: Double.parseDouble(inputLine.trim())

But, in fact, I don't think versions should be doubles. In your particular case, today, this might be the case, but it can easily change. Here are some examples of popular "versionings", that cannot be represented as doubles:

3.0.5

  2.1.GA

  1.5-SNAPSHOT

  0.8b

So, I'd suggest leaving this a string.

ContentLicense: CC BY-SA 2.5

Title: Reading from URL, store data as double?

Body:
public static void getClientUpdate() {
    try {
        String inputLine;
        double version = 0;
        URL url = new URL("http://ds-forums.com/client/version.txt");
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
        version = inputLine;
        System.out.println("The version is: " + version);
    } catch (Exception x) {
        System.out.println(x);
    }
}

This is going to sound really stupid but I have a txt file that contains a double and I want to save it as a double. Instead it wants a string.  Am I doing this wrong or is there just a few steps I need to add?


问:
Create a pdf for J2EE applications
Could you please anyone tell me the way to create a pdf document for J2EE Application other than iText.

We are previously used the iText, but the problem is the html file (which is generated from Jsp) display is different with the generated PDF. So I need some other way to create a pdf as same as jsp display.

Any one please suggest me the libraries other than iText?

Thanks in Advance.

答:
This is always tricky because HTML and PDF have differing purposes (with a lot of overlap).  That means "simply" converting between the two is sometimes not going to work well.

You can

Snapshot an image of the HTML and PDF the image.   This has various downsides (can't search / extract text easily, larger, poor zoom, pagination) but is simple if it doesn't conflict with your requirements.

Use a PDF system (like iText) to construct the PDF as desired using the same data.  This is obviously more work (possibly a lot more), but is the optimal result in terms of PDF quality and fitness for purpose.

Simplify/adjust your HTML so it converts better into PDF.  This depends on what HTML tools/libraries you are using - you might not have much control over the HTML.

Try various other conversion libraries to see if you find a tool that works better for your HTML.

Title: Create a pdf for J2EE applications


问:
Error and incompatibility with crosstab (Postgresql-10)
I'm trying to use the 'crosstab' function in Postgres 10 and it throws me the following error and I do not understand why:

ERROR: return and sql tuple descriptions are incompatible
SQL state: 42601

```<code>select * from crosstab
($$select xx, xxy, sum(t) as lala from po.zBORRARvi_intermedia
                           group by xx, xxy order by 1,2$$) as
ct("xx" varchar(255), "xy1" double precision, "xy2" double precision, "xy3" double precision,
"xy4" double precision,"xy5" double precision, "xy6" double precision, "xy7" double precision,
   "xy8" double precision);
</code>```

答:
the return type of the crosstab must be defined correctly, according to the number of expected columns.

Please read this link

Body:
I'm trying to use the 'crosstab' function in Postgres 10 and it throws me the following error and I do not understand why:

ERROR: return and sql tuple descriptions are incompatible
SQL state: 42601

select * from crosstab
($$select xx, xxy, sum(t) as lala from po.zBORRARvi_intermedia
                           group by xx, xxy order by 1,2$$) as
ct("xx" varchar(255), "xy1" double precision, "xy2" double precision, "xy3" double precision,
"xy4" double precision,"xy5" double precision, "xy6" double precision, "xy7" double precision,
   "xy8" double precision);


问:
Custom Dimensions Not Reporting Through to Google Analytics API V4
I am attempting to pass information collected as, "custom dimensions," from Google Tag Manager through Google Analytics and then extract them out via the Google Analytics V4 API.

I have set up four of the fundamental custom dimensions suggested by Simo Ahava in this article.

My variable setup looks like the following:

variable setup

Essentially, I have been able to successfully pass through userID_dimension, hittimestamp_dimension, clientid_dimension and sessionid_dimension to the Google Analytics dashboard, but for some reason I am not able to extract out the hittimestamp_dimension through the API.

Here's what I am able to see on the dashboard:

Google Analytics Dashboard

As far as the API itself, I am using the HelloAnalytics.py python version supplied by Google, and I am able to extract out all of the above information, minus the timestamps dimensions on the right hand side of each.

I'm storing the timestamp information in dimension2, but upon making the below call (again, using API V4) I get blank...nothing.

```<code>analytics.reports().batchGet(
  body={
    'reportRequests': [
    {
      'viewId': VIEW_ID,
      'dateRanges': [{'startDate': '2017-10-05', 'endDate': '2017-10-06'}],
      'samplingLevel': 'LARGE',
      'dimensions': [{'name': 'ga:dimension4'},{'name': 'ga:dimension2'}]
     }]
  }
).execute()
</code>```

Upon making this call, one would expect that the above would report out dimensions similar to what the Google Analytics dashboard would show.  E.g. one would think that the dashboard itself is using the API.  However what prints out is blank.  All other custom dimensions print out as expected.

If I try to call the above function on just dimension2 itself with no other dimension, it is also blank.

Is there something special one has to do in order to extract hit-scoped variables within the API?  Or does the API just not allow hit-scoped variables to pass through?

thanks,

答:
You forgot to add a 'metrics' field to your request, it is required as per documentation

Source: Reporting API v4 - Method: reports.batchGet

The metrics requested. Requests must specify at least one metric. Requests can have a total of 10 metrics.

The below modified request should work:

```<code>analytics.reports().batchGet(
  body={
    'reportRequests': [
    {
      'viewId': VIEW_ID,
      'dateRanges': [{'startDate': '2017-10-05', 'endDate': '2017-10-06'}],
      'samplingLevel': 'LARGE',
      'dimensions': [{'name': 'ga:dimension4'},{'name': 'ga:dimension2'}],
      'metrics': [{'expression': 'ga:sessions'}]
     }]
  }
).execute()
</code>```

Body:
I am attempting to pass information collected as, "custom dimensions," from Google Tag Manager through Google Analytics and then extract them out via the Google Analytics V4 API.

I have set up four of the fundamental custom dimensions suggested by Simo Ahava in this article.

My variable setup looks like the following:

variable setup

Essentially, I have been able to successfully pass through userID_dimension, hittimestamp_dimension, clientid_dimension and sessionid_dimension to the Google Analytics dashboard, but for some reason I am not able to extract out the hittimestamp_dimension through the API.

Here's what I am able to see on the dashboard:

Google Analytics Dashboard

As far as the API itself, I am using the HelloAnalytics.py python version supplied by Google, and I am able to extract out all of the above information, minus the timestamps dimensions on the right hand side of each.

I'm storing the timestamp information in dimension2, but upon making the below call (again, using API V4) I get blank...nothing.

analytics.reports().batchGet(
  body={
    'reportRequests': [
    {
      'viewId': VIEW_ID,
      'dateRanges': [{'startDate': '2017-10-05', 'endDate': '2017-10-06'}],
      'samplingLevel': 'LARGE',
      'dimensions': [{'name': 'ga:dimension4'},{'name': 'ga:dimension2'}]
     }]
  }
).execute()

Upon making this call, one would expect that the above would report out dimensions similar to what the Google Analytics dashboard would show.  E.g. one would think that the dashboard itself is using the API.  However what prints out is blank.  All other custom dimensions print out as expected.

If I try to call the above function on just dimension2 itself with no other dimension, it is also blank.

Is there something special one has to do in order to extract hit-scoped variables within the API?  Or does the API just not allow hit-scoped variables to pass through?

thanks,

Body:
You forgot to add a 'metrics' field to your request, it is required as per documentation

Source: Reporting API v4 - Method: reports.batchGet

The metrics requested. Requests must specify at least one metric. Requests can have a total of 10 metrics.

The below modified request should work:

analytics.reports().batchGet(
  body={
    'reportRequests': [
    {
      'viewId': VIEW_ID,
      'dateRanges': [{'startDate': '2017-10-05', 'endDate': '2017-10-06'}],
      'samplingLevel': 'LARGE',
      'dimensions': [{'name': 'ga:dimension4'},{'name': 'ga:dimension2'}],
      'metrics': [{'expression': 'ga:sessions'}]
     }]
  }
).execute()


问:
EF & listview to display value from lookup table
I have 2 tables:

User(Id PK, TitleId FK, Name, Active)

Title(Id PK, Text)

Table Title is a lookup table of titles (Mr, Miss,...) and its got a relationship with table User by TitleId.

Now I'm trying to display the data in a web page using .net and Entity Framework. I'm using a ListView control and a query as a source. it all displays fine except for the Title.

Here is my code:

```<code>    MyEntities _entities = new MyEntities ();

    User user = new User(_entities);
    IQueryable u = (from x in _entities.Users
           where x.Active == true
           select x);

    ListView1.DataSource = u;
    ListView1.DataBind();
</code>```

and the code in the front end:

```<code><asp:ListView ID="ListView1" runat="server"
    EnableModelValidation="True" DataKeyNames="Id">

<ItemTemplate>
    <tr>
        <td>
            <%# Eval("Id") %>
        </td>
        <td>
            <%# Eval("Title.Text") %>
        </td>

        <td>
            <%# Eval("Name") %>
        </td>
     </tr>
</ItemTemplate>
<LayoutTemplate>
                 <table ID="itemPlaceholderContainer" runat="server">
                    <tr runat="server">
                        <th id="Th2" runat="server">
                            Id</th>
                        <th id="Th1" runat="server">
                            Title</th>
                        <th id="Th3" runat="server">
                            Name</th>
                        <th runat="server">
                    </tr>
                    <tr runat="server" ID="itemPlaceholder">
                    </tr>
                </table>

</LayoutTemplate>
</code>```

How do I manage to get the Title Text associated with a User to display on the ListView?

答:
I just figured out how to do it:

_entities.Users.Include("Title")

Body:
I have 2 tables:

User(Id PK, TitleId FK, Name, Active)

Title(Id PK, Text)

Table Title is a lookup table of titles (Mr, Miss,...) and its got a relationship with table User by TitleId.

Now I'm trying to display the data in a web page using .net and Entity Framework. I'm using a ListView control and a query as a source. it all displays fine except for the Title.

Here is my code:

    MyEntities _entities = new MyEntities ();

    User user = new User(_entities);
    IQueryable u = (from x in _entities.Users
           where x.Active == true
           select x);

    ListView1.DataSource = u;
    ListView1.DataBind();

and the code in the front end:

<asp:ListView ID="ListView1" runat="server"
    EnableModelValidation="True" DataKeyNames="Id">

<ItemTemplate>

            <%# Eval("Id") %>

            <%# Eval("Title.Text") %>

            <%# Eval("Name") %>

</ItemTemplate>
<LayoutTemplate>

                            Id

                            Title

                            Name

</LayoutTemplate>

How do I manage to get the Title Text associated with a User to display on the ListView?


问:
Codeigniter list only files non-recursively
I'd like to list the names of files from a specific location, without names of the subdirectories and files they may contain.

I've used CI's directory_map function with a success, but had to make a small workaround to get rid of the folder names in not quite a neat way:

```<code>$files = directory_map('src/img/example/', 1);

foreach($files as $i => $file) {
    if(strpos($file, '\\') !== false) {
        unset($files[$i]);
    }
}
</code>```

I'm sure there has to be a way easier and better solution, but had no luck finding it

答:
You can get an array of filenames in a one-liner, using scandir()

http://php.net/manual/en/function.scandir.php

Here's an example that does an array_diff() to remove the "." and ".." directories.

```<code> $files = array_diff(scandir('src/img/example'), array('..', '.'));
</code>```

You can also use array_filter().

```<code>$files = array_filter(scandir('src/img/example'), function($item) {
  return !is_dir('directory/' . $item);
});
</code>```

Body:
I'd like to list the names of files from a specific location, without names of the subdirectories and files they may contain.

I've used CI's directory_map function with a success, but had to make a small workaround to get rid of the folder names in not quite a neat way:

$files = directory_map('src/img/example/', 1);

foreach($files as $i => $file) {
    if(strpos($file, '\\') !== false) {
        unset($files[$i]);
    }
}

I'm sure there has to be a way easier and better solution, but had no luck finding it

Body:
You can get an array of filenames in a one-liner, using scandir()

http://php.net/manual/en/function.scandir.php

Here's an example that does an array_diff() to remove the "." and ".." directories.

 $files = array_diff(scandir('src/img/example'), array('..', '.'));

You can also use array_filter().

$files = array_filter(scandir('src/img/example'), function($item) {
  return !is_dir('directory/' . $item);
});


问:
Python / Requests: Log In to Website Javascript
I am trying to create a script to log into a website but I am struggling to have it work on this particular page. FYI I'm rather new to using python requests. I can perform the function in selenium and I can use requests on other sites to log in but I believe this one is using javascript and that is more than likely my issue.

Code:

```<code>while (FoundItem == "Nope"):

    SignIn = "https://www.bestbuy.ca/profile/signin.aspx"

    Email = "ctl00$CP$SignInUC1$UserNameContainer$txtUserName"
    Password= "ctl00$CP$SignInUC1$PasswordContainer$txtPassword"

    payload = {
    'ctl00$CP$SignInUC1$UserNameContainer$txtUserName': 'MYEMAIL',
    'ctl00$CP$SignInUC1$PasswordContainer$txtPassword': 'MYPASSWORD'
}

    with requests.Session() as s:
        p = s.post(SignIn, data=payload)

        print(p.content)
</code>```

HTML from the site log in form:

```<code><div class="chkout-fieldbox std-half-cln signinblock checkout-form" id="sign-in">
    <div class="std-half-cln-wrapper">

        <h2 class="module-title"><span id="ctl00_CP_SignInUC1_lblSinginHeader">Returning Customer?</span></h2>
        <p class="std-bottomspace">Please sign in to Your Account</p>

        <fieldset class="checkout-fieldset">
            <legend>Sign in for fast and easy checkout</legend>
            <ul class="clearfix">
                <li class="large">
                    <label for="ctl00_CP_SignInUC1_UserNameContainer_txtUserName">Email Address</label>

                    <span id="ctl00_CP_SignInUC1_UserNameContainer"><span id="ctl00_CP_SignInUC1_UserNameContainer_proxyValidator" style="color:Red;display:none;"></span><input name="ctl00$CP$SignInUC1$UserNameContainer$txtUserName" type="email" maxlength="80" id="ctl00_CP_SignInUC1_UserNameContainer_txtUserName" tabindex="1" class="txtbox" autocomplete="off" placeholder="example@example.com" onblur="if (this.onchange!=null)this.onchange();"><span id="ctl00_CP_SignInUC1_UserNameContainer_ctl00" style="display:none;">
                            <img id="ctl00_CP_SignInUC1_UserNameContainer_ctl00_imgUserName" src="https://images.bbycastatic.ca/sf/images/common/pictures/warningiconsmall.gif" alt=" ">
                        </span></span>
                </li>
                <li class="large">
                    <label for="ctl00_CP_SignInUC1_PasswordContainer_txtPassword">Password</label>
                    <span id="ctl00_CP_SignInUC1_PasswordContainer"><span id="ctl00_CP_SignInUC1_PasswordContainer_proxyValidator" style="color:Red;display:none;"></span><input name="ctl00$CP$SignInUC1$PasswordContainer$txtPassword" type="password" id="ctl00_CP_SignInUC1_PasswordContainer_txtPassword" tabindex="2" class="txtbox" autocomplete="off" onblur="if (this.onchange!=null)this.onchange();"><span id="ctl00_CP_SignInUC1_PasswordContainer_ctl00" style="display:none;">
                            <img id="ctl00_CP_SignInUC1_PasswordContainer_ctl00_imgPassword" src="https://images.bbycastatic.ca/sf/images/common/pictures/warningiconsmall.gif" alt=" ">
                        </span></span>
                    <span class="subtext-wrapper">
                        <p class="subtext-notification">
                            <a id="ctl00_CP_SignInUC1_lnkForgotPassword" href="javascript:__doPostBack('ctl00$CP$SignInUC1$lnkForgotPassword','')">I forgot my password</a>
                        </p>

                    </span>
                </li>
            </ul>
            <div id="CaptchaContainer" class="clearfix btm-margin2x">

            </div>

         </fieldset>
        <a id="ctl00_CP_SignInUC1_BtnLoginButton" tabindex="4" type="submit" class="button-left btn-primary btn btn-lock" href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$CP$SignInUC1$BtnLoginButton", "", true, "signin", "", false, true))'>Sign In</a>
    </div>
</div>
</code>```

答:
I don't have a complete answer for you, but maybe I can help with direction.

First off, you're correct, javascript is being called. In the html you posted, the login button is ctl00_CP_SignInUC1_BtnLoginButton and it has some javascript hidden in its href property:

href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$CP$SignInUC1$BtnLoginButton", "", true, "signin", "", false, true))

When the button is clicked, your browser launches a postback to the server, which contains the state of the login page.

Unfortunately, I've never dealt with postback before. But there does seems to be a few posts on the topic. Here's one that looks useful.

Body:
I am trying to create a script to log into a website but I am struggling to have it work on this particular page. FYI I'm rather new to using python requests. I can perform the function in selenium and I can use requests on other sites to log in but I believe this one is using javascript and that is more than likely my issue.

Code:

while (FoundItem == "Nope"):

    SignIn = "https://www.bestbuy.ca/profile/signin.aspx"

    Email = "ctl00$CP$SignInUC1$UserNameContainer$txtUserName"
    Password= "ctl00$CP$SignInUC1$PasswordContainer$txtPassword"

    payload = {
    'ctl00$CP$SignInUC1$UserNameContainer$txtUserName': 'MYEMAIL',
    'ctl00$CP$SignInUC1$PasswordContainer$txtPassword': 'MYPASSWORD'
}

    with requests.Session() as s:
        p = s.post(SignIn, data=payload)

        print(p.content)

HTML from the site log in form:

Returning Customer?

Please sign in to Your Account

        <fieldset class="checkout-fieldset">
            <legend>Sign in for fast and easy checkout</legend>

                    Email Address

                    <input name="ctl00$CP$SignInUC1$UserNameContainer$txtUserName" type="email" maxlength="80" id="ctl00_CP_SignInUC1_UserNameContainer_txtUserName" tabindex="1" class="txtbox" autocomplete="off" placeholder="example@example.com" onblur="if (this.onchange!=null)this.onchange();">

                    Password
                    <input name="ctl00$CP$SignInUC1$PasswordContainer$txtPassword" type="password" id="ctl00_CP_SignInUC1_PasswordContainer_txtPassword" tabindex="2" class="txtbox" autocomplete="off" onblur="if (this.onchange!=null)this.onchange();">

                            I forgot my password

         </fieldset>
        Sign In


问:
pymongo single insert is too slow, despite WriteConcern(w=0)
I am using pymongo to write to my mongodb.
I want as fast as possible performance, so I set the write concern to w=0. I tried three ways:

1.

```<code>client = MongoClient(host=HOST, port=PORT, w=0)
collection = client[DB][COLLECTION]
collection.insert_one(data)
</code>```

2.

```<code>client = MongoClient(host=HOST, port=PORT)
collection = collection.with_options(write_concern=WriteConcern(w=0))
collection = client[DB][COLLECTION]
collection.insert_one(data)
</code>```

3.

```<code>client = MongoClient(host=HOST, port=PORT)
collection = client[DB][COLLECTION]
collection.insert_one(data, bypass_document_validation=True)
</code>```

In all above attempts, the time it took for collection.insert_one() was ~0.5 seconds (!)

Why is insertion still taking so long?

I understand that it should be about a fifth of that time at least. More so, 'data' is not a lot of data, only a few items. I am using mongodb 3.4 and pymongo 3.0

答:
First, you would need to answer "how fast is fast enough".

"Slow" and "fast" are very subjective terms. It depends on so many factors, including the provisioned server, the language you're using, the document you're inserting, how many indexes you defined in the collection, all the way to your expectations.

For some people, "slow" is >100ms. For others, "slow" is >10ms. Of course, the "faster" you want to get results, the more expensive it will cost you in terms of server provisioning.

On another note, Python is not the fastest language. It is well known to have limitations in terms of its use of the Global Interpreter Lock. It's also an interpreted language, and designed primarily for readability and not for sheer speed. You can usually get an immediate speed boost using a compiled language (C, C++, etc.)

Another thing you can try is to use bulk insert, and not trying to insert many documents using insert_one(). Please see http://api.mongodb.com/python/current/examples/bulk.html#bulk-insert for examples using bulk insert.

Body:
I am using pymongo to write to my mongodb.
I want as fast as possible performance, so I set the write concern to w=0. I tried three ways:

1.

client = MongoClient(host=HOST, port=PORT, w=0)
collection = client[DB][COLLECTION]
collection.insert_one(data)

2.

client = MongoClient(host=HOST, port=PORT)
collection = collection.with_options(write_concern=WriteConcern(w=0))
collection = client[DB][COLLECTION]
collection.insert_one(data)

3.

client = MongoClient(host=HOST, port=PORT)
collection = client[DB][COLLECTION]
collection.insert_one(data, bypass_document_validation=True)

In all above attempts, the time it took for collection.insert_one() was ~0.5 seconds (!)

Why is insertion still taking so long?

I understand that it should be about a fifth of that time at least. More so, 'data' is not a lot of data, only a few items. I am using mongodb 3.4 and pymongo 3.0


问:
Add Comments to Specific cells in Range. Excel VBA
I am trying to add comments to specific cells in a range if they meet criteria. So I have a list in Sheet1 where the information is housed. I also have the cell value on sheet16 where I want the comment in column U, so it will say F6 in row U. I keep getting

Application-Defined or object-defined error

Any thoughts?

Thanks in Advance.

```<code>Sub Comments()

    Dim rcell As Range

    Sheet16.Range("C6:AR17").ClearComments

    For Each rcell In Sheet1.Range("A2:A" & Sheet1.Range("A" & Sheet1.Rows.CountLarge).End(xlUp).Row)
        If rcell.Offset(0, 1).Value(10) = Sheet7.Range("G1").Value(10) Then
            commentvalue = rcell.Offset(0, 4).Value
            Sheet16.Range("U" & rcell.Row).AddComment (commentvalue)
        End If
    Next rcell

End Sub
</code>```

答:
The AddComment method fails if there's already a comment on a cell. Do it like this:

```<code>Sub Comments()
    Dim rcell As Range
    Dim commentvalue As String

    Sheet16.Range("C6:AR17").ClearComments

    For Each rcell In Sheet1.Range("A2:A" & Sheet1.Range("A" & Sheet1.Rows.CountLarge).End(xlUp).row)
        If rcell.Offset(0, 1).Value = Sheet7.Range("G1").Value Then
            commentvalue = CStr(rcell.Offset(0, 4).Value)

            With Sheet16.Range("U" & rcell.row)
                .ClearComments '<=== :-)
                .AddComment commentvalue
            End With
        End If
    Next rcell
End Sub
</code>```

Edit

As per @Jeeped's comment, you could want to "cumulate" comments. My assumption was that you ran the code once, then ran it again and hit the error because the first run had created the comments. Depending on what you try to achieve, you may want to systematically clear the comments in column U from rows 2 to your last row, outside of the loop, and remove the .ClearComments in the loop, in order to start clean each time. That's the simplest case. I'll let you work out the details if it's anything more complicated.

Body:
I am trying to add comments to specific cells in a range if they meet criteria. So I have a list in Sheet1 where the information is housed. I also have the cell value on sheet16 where I want the comment in column U, so it will say F6 in row U. I keep getting

Application-Defined or object-defined error

Any thoughts?

Thanks in Advance.

Sub Comments()

    Dim rcell As Range

    Sheet16.Range("C6:AR17").ClearComments

    For Each rcell In Sheet1.Range("A2:A" & Sheet1.Range("A" & Sheet1.Rows.CountLarge).End(xlUp).Row)
        If rcell.Offset(0, 1).Value(10) = Sheet7.Range("G1").Value(10) Then
            commentvalue = rcell.Offset(0, 4).Value
            Sheet16.Range("U" & rcell.Row).AddComment (commentvalue)
        End If
    Next rcell

End Sub

Body:
The AddComment method fails if there's already a comment on a cell. Do it like this:

Sub Comments()
    Dim rcell As Range
    Dim commentvalue As String

    Sheet16.Range("C6:AR17").ClearComments

    For Each rcell In Sheet1.Range("A2:A" & Sheet1.Range("A" & Sheet1.Rows.CountLarge).End(xlUp).row)
        If rcell.Offset(0, 1).Value = Sheet7.Range("G1").Value Then
            commentvalue = CStr(rcell.Offset(0, 4).Value)

            With Sheet16.Range("U" & rcell.row)
                .ClearComments '<=== :-)
                .AddComment commentvalue
            End With
        End If
    Next rcell
End Sub

Edit

As per @Jeeped's comment, you could want to "cumulate" comments. My assumption was that you ran the code once, then ran it again and hit the error because the first run had created the comments. Depending on what you try to achieve, you may want to systematically clear the comments in column U from rows 2 to your last row, outside of the loop, and remove the .ClearComments in the loop, in order to start clean each time. That's the simplest case. I'll let you work out the details if it's anything more complicated.


问:
Counting the (year)quarters between two dates
I have project built using laravel and a I have to build a function that counts all the complete quarters that are in the selected date range - the dates used are inserted via input.

Here are the quarters(i used numerical representations for the months)

01 - 03 first quarter
04 - 06 second quarter
07 - 09 third quarter
10 - 12 forth quarter

I would really appreciate your help,because I've been at it for an entire day now and basically have nothing to show for it,i thing I've been trying so hard i'm actually at the point where i'm so tired, i can t think straight.

I do have some code but it;s worthless, because it doesn't work, and any kind of idea or snippet of code is welcomed.

Thanks for your help in advance.

答:
Something like this in the function and you should be set.</p>

```<code>use Carbon\Carbon;

$first = Carbon::parse('2012-1-1'); //first param
$second = Carbon::parse('2014-9-15'); //second param

$fY = $first->year; //2012
$fQ = $first->quarter; //1

$sY = $second->year; //2014
$sQ = $second->quarter; //3

$n = 0; //the number of quarters we have counted
$i = 0; //an iterator we will use to determine if we are in the first year

for ($y=$fY; $y < $sY; $y++, $i++) { //for each year less than the second year (if any)
    $s = ($i > 0) ? 1 : $fQ; //determine the starting quarter
    for ($q=$s; $q <= 4; $q++) { //for each quarter
        $n++; //count it
    }
}

if ($sY > $fY) { //if both dates are not in the same year
    $n = $n + $sQ; //total is the number of quarters we've counted plus the second quarter value
} else {
    for ($q=$fQ; $q <= $sQ; $q++) { //for each quarter between the first quarter and second
        $n++; //count it
    }
}

print $n; //the value to return (11)
</code>```

Body:
Something like this in the function and you should be set.

use Carbon\Carbon;

$first = Carbon::parse('2012-1-1'); //first param
$second = Carbon::parse('2014-9-15'); //second param

$fY = $first->year; //2012
$fQ = $first->quarter; //1

$sY = $second->year; //2014
$sQ = $second->quarter; //3

$n = 0; //the number of quarters we have counted
$i = 0; //an iterator we will use to determine if we are in the first year

for ($y=$fY; $y < $sY; $y++, $i++) { //for each year less than the second year (if any)
    $s = ($i > 0) ? 1 : $fQ; //determine the starting quarter
    for ($q=$s; $q <= 4; $q++) { //for each quarter
        $n++; //count it
    }
}

if ($sY > $fY) { //if both dates are not in the same year
    $n = $n + $sQ; //total is the number of quarters we've counted plus the second quarter value
} else {
    for ($q=$fQ; $q <= $sQ; $q++) { //for each quarter between the first quarter and second
        $n++; //count it
    }
}

print $n; //the value to return (11)


问:
Google Maps that looks like pokemon GO map
I'm trying to create a map similar to Pokemon GO maps, using this URL.

(http://maps.googleapis.com/maps/api/staticmap?center=23.038357,%2072.529030&zoom=17&size=2160x1920&scale=2&maptype=roadmap&style=feature:road|element:geometry.fill|color:0x589b89|weight:8&style=element:labels|visibility:off&style=feature:landscape|element:geometry|color:0xbcffaf&style=feature:poi|color:0x93efd5&style=feature:poi.park|color:0x08ab91&style=feature:road|element:geometry.stroke|color:0xf6ff8f|weight:1&style=feature:water|color:0x1e8cdb&style=feature:transit|visibility:ff&style=feature:water)

But I want to show few random markers(so, they look like pokestops / gyms).
Can anyone help me understand the URL or modify it to show markers.

Also, The final result should be a URL, no xml or API.

答:
It seems like you're new and trying to create static maps with custom markers. Usually, you should only post development related questions, but I'll give you a hint with where to go.

The best resource for the map you are saying is the Documentation on Static Maps:
https://developers.google.com/maps/documentation/static-maps/intro

Then in the markers section, you can learn more about adding custom markers:
https://developers.google.com/maps/documentation/static-maps/intro#Markers

If you encounter any issues with Static Maps, just post another question with your sample request or code and many avid community members will be able to help you :)

Body:
I'm trying to create a map similar to Pokemon GO maps, using this URL.

(<a href="http://maps.googleapis.com/maps/api/staticmap?center=23.038357,%2072.529030&zoom=17&size=2160x1920&scale=2&maptype=roadmap&style=feature:road|element:geometry.fill|color:0x589b89|weight:8&style=element:labels|visibility:off&style=feature:landscape|element:geometry|color:0xbcffaf&style=feature:poi|color:0x93efd5&style=feature:poi.park|color:0x08ab91&style=feature:road|element:geometry.stroke|color:0xf6ff8f|weight:1&style=feature:water|color:0x1e8cdb&style=feature:transit|visibility:ff&style=feature:water" rel="nofollow noreferrer">http://maps.googleapis.com/maps/api/staticmap?center=23.038357,%2072.529030&zoom=17&size=2160x1920&scale=2&maptype=roadmap&style=feature:road|element:geometry.fill|color:0x589b89|weight:8&style=element:labels|visibility:off&style=feature:landscape|element:geometry|color:0xbcffaf&style=feature:poi|color:0x93efd5&style=feature:poi.park|color:0x08ab91&style=feature:road|element:geometry.stroke|color:0xf6ff8f|weight:1&style=feature:water|color:0x1e8cdb&style=feature:transit|visibility:ff&style=feature:water)

But I want to show few random markers(so, they look like pokestops / gyms).
Can anyone help me understand the URL or modify it to show markers.

Also, The final result should be a URL, no xml or API.


问:
Python & NetworkX for Network Topology Data
I tried thousands of times to apply "NetworkX" Python library to analyze the datasets found by this link:

```<code>http://konect.uni-koblenz.de/networks/topology
</code>```

As long as I execute my Python code to the data found there I got, for example, some unrealistic results.

```<code>g = nx.read_weighted_edgelist('out.topology')
g.size()
0
</code>```

0 as a result for this huge data is completely wrong !

Could you please help me to read this data through "NetworkX" Python library ?

答:
As someone mentioned trying reading the list gets errors. However, if you get rid of the first line (% sym positive) and try the code below to create your graph it should be fine:

```<code>import networkx as nx

with open("out.topology", 'rt') as f:
    g = nx.parse_edgelist(f, create_using=nx.DiGraph(), data=[('weight', float), ('timestamp', float)])
</code>```

The data contains 4 columns: source | target | weight | timestamp of edge.

Just include that info in the arguments as shown in my snippet.

Body:
I tried thousands of times to apply "NetworkX" Python library to analyze the datasets found by this link:

http://konect.uni-koblenz.de/networks/topology

As long as I execute my Python code to the data found there I got, for example, some unrealistic results.

g = nx.read_weighted_edgelist('out.topology')
g.size()
0

0 as a result for this huge data is completely wrong !

Could you please help me to read this data through "NetworkX" Python library ?

Body:
As someone mentioned trying reading the list gets errors. However, if you get rid of the first line (% sym positive) and try the code below to create your graph it should be fine:

import networkx as nx

with open("out.topology", 'rt') as f:
    g = nx.parse_edgelist(f, create_using=nx.DiGraph(), data=[('weight', float), ('timestamp', float)])

The data contains 4 columns: source | target | weight | timestamp of edge.

Just include that info in the arguments as shown in my snippet.


问:
(Java)Why does my decimal to binary conversion method only work some of the time when counting consecutive integers in a character array?
I'm a novice Java coder working on a problem dealing with counting consecutive integers in the binary forms of numbers.

The numbers are read from the input, and converted to binary using the method called conversion. The binary form is then sent to a character array where the for loop checks for consecutive characters(specifically the number 1) and prints the maximum count as the final answer.

I've managed to get the code to a state where I feel it should be working, but I've only had success with about half of the test cases. The larger number conversions like 262,141 tend to produce incorrect answers. Can anyone tell me where I've gone wrong?

I have a suspicion that it's something to do with the character array, but after several hours of research I haven't been able to find a solution to my particular problem.

```<code>import java.io.*;
import java.util.*;

public class Solution {

    public static int conversion(int decimal){//this will take the decimal from the input and convert it to binary

        int result = 0;//the result from each step of the conversion
        int base = 1;//used to multiply the remainder by 1, 10, 100 etc

        while(decimal > 0){
            int remainder = decimal % 2;//takes the remainder of the iteration
            decimal = decimal / 2;//halves the decimal number
            result = result + (remainder * base);//pseudo concatenation of the binary
            base = base * 10;//increases the base multiplier to continue filling out the binary leftward
        }
        return result;//returns result after loop has finished

    }

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();//scan the input to obtain the decimal number

        int binaryForm = conversion(n);//convert the decimal to binary and assign to binaryForm variable
        String stringForm = Integer.toString(binaryForm);//convert binaryForm to a String

        int counter = 1;
        int max = 1;
        char testArray[] = stringForm.toCharArray();//send stringForm to fill out testArray

        for(int i = 0; i < testArray.length - 1; i++){//loops through testArray to test stringForm values

            if(testArray[i] == testArray[i + 1] && testArray[i] == '1'){//if consecutive values equal char 1, increase counter
                counter += 1;
                if(counter > max){
                    max = counter;//if counter is higher than current maxCounter, increase maxCounter
                }
            }

            else {//if consecutive values do not equal 1, reset counter
                counter = 1;
            }
        }

        System.out.print(max);//print the maximum consecutive values for the decimal input when converted to binary

    }
}
</code>```

答:
You are trying to create a binary representation of a decimal number using an integer. This will work for smaller numbers but it doesn't take long for you to reach an overflow. You should use a string representation of the binary number like so

```<code>    String numBin = "";
    while(num > 0)
    {
        numBin = num % 2 + numBin;
        num = num / 2;
    }
    System.out.println("Binary Representation: " + numBin);
</code>```

Then take that string and loop through it calculating the consecutive counts of 1's

```<code>    int consecutiveCount = 0;
    for(int i = 0; i < numBin.length() - 1; i++)
    {
        if(numBin.charAt(i) == '1' && numBin.charAt(i + 1) == '1')
        {
            consecutiveCount++;
        }
    }
    System.out.println("Consecutive Count: " + consecutiveCount);
</code>```

Output

```<code>Number: 261141
Binary Representation: 111111110000010101
Consecutive Count: 7

Number: 3
Binary Representation: 11
Consecutive Count: 1

Number: 18
Binary Representation: 10010
Consecutive Count: 0

Number: 1111111
Binary Representation: 100001111010001000111
Consecutive Count: 5
</code>```

Body:
I'm a novice Java coder working on a problem dealing with counting consecutive integers in the binary forms of numbers.

The numbers are read from the input, and converted to binary using the method called conversion. The binary form is then sent to a character array where the for loop checks for consecutive characters(specifically the number 1) and prints the maximum count as the final answer.

I've managed to get the code to a state where I feel it should be working, but I've only had success with about half of the test cases. The larger number conversions like 262,141 tend to produce incorrect answers. Can anyone tell me where I've gone wrong?

I have a suspicion that it's something to do with the character array, but after several hours of research I haven't been able to find a solution to my particular problem.

import java.io.*;
import java.util.*;

public class Solution {

    public static int conversion(int decimal){//this will take the decimal from the input and convert it to binary

        int result = 0;//the result from each step of the conversion
        int base = 1;//used to multiply the remainder by 1, 10, 100 etc

        while(decimal > 0){
            int remainder = decimal % 2;//takes the remainder of the iteration
            decimal = decimal / 2;//halves the decimal number
            result = result + (remainder * base);//pseudo concatenation of the binary
            base = base * 10;//increases the base multiplier to continue filling out the binary leftward
        }
        return result;//returns result after loop has finished

    }

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();//scan the input to obtain the decimal number

        int binaryForm = conversion(n);//convert the decimal to binary and assign to binaryForm variable
        String stringForm = Integer.toString(binaryForm);//convert binaryForm to a String

        int counter = 1;
        int max = 1;
        char testArray[] = stringForm.toCharArray();//send stringForm to fill out testArray

        for(int i = 0; i < testArray.length - 1; i++){//loops through testArray to test stringForm values

            if(testArray[i] == testArray[i + 1] && testArray[i] == '1'){//if consecutive values equal char 1, increase counter
                counter += 1;
                if(counter > max){
                    max = counter;//if counter is higher than current maxCounter, increase maxCounter
                }
            }

            else {//if consecutive values do not equal 1, reset counter
                counter = 1;
            }
        }

        System.out.print(max);//print the maximum consecutive values for the decimal input when converted to binary

    }
}

Body:
You are trying to create a binary representation of a decimal number using an integer. This will work for smaller numbers but it doesn't take long for you to reach an overflow. You should use a string representation of the binary number like so

    String numBin = "";
    while(num > 0)
    {
        numBin = num % 2 + numBin;
        num = num / 2;
    }
    System.out.println("Binary Representation: " + numBin);

Then take that string and loop through it calculating the consecutive counts of 1's

    int consecutiveCount = 0;
    for(int i = 0; i < numBin.length() - 1; i++)
    {
        if(numBin.charAt(i) == '1' && numBin.charAt(i + 1) == '1')
        {
            consecutiveCount++;
        }
    }
    System.out.println("Consecutive Count: " + consecutiveCount);

Output

Number: 261141
Binary Representation: 111111110000010101
Consecutive Count: 7

Number: 3
Binary Representation: 11
Consecutive Count: 1

Number: 18
Binary Representation: 10010
Consecutive Count: 0

Number: 1111111
Binary Representation: 100001111010001000111
Consecutive Count: 5


问:
Running systemd unit directly after local-fs.target and before basic.target
I am creating an embedded system. The embedded system mounts a partition. Directly after mounting the partition, I need to prep an encrypted folder (encfs). I need this to run before any other multi-user.target or graphical.target

Here is my unit file, which works by it's self.

```<code>[Unit]
Description=Mx Encrypted Folder

[Service]
Type=oneshot
ExecStart=/usr/bin/mxmountencrypted
RemainAfterExit=true
ExecStop=/usr/bin/mxunmountencrypted
</code>```

This unit file has no dependencies defined, currently.

Again, I need:

To run this directly after mounting file systems (local-fs.target)

Before any multi-user.target or graphical.target, where must of the services that depend on it will be ran.

It must stop fully before stopping local-fs.target, since there will be a nested mount that needs to be unmounted before systemd can unmount the partition.

I looked into using the systemd.mount item, but it doesn't support encfs.

答:
Based on what you have listed in the requirements:

```<code>[Unit]
Description=Mx Encrypted Folder
Requires=local-fs.target
After=local-fs.target

[Service]
Type=oneshot
ExecStart=/usr/bin/mxmountencrypted
RemainAfterExit=true
ExecStop=/usr/bin/mxunmountencrypted

[Install]
WantedBy=multi-user.target
</code>```

More on systemd Unit files here: https://www.freedesktop.org/software/systemd/man/systemd.unit.html

and systemd Service files: https://www.freedesktop.org/software/systemd/man/systemd.service.html

Body:
I am creating an embedded system. The embedded system mounts a partition. Directly after mounting the partition, I need to prep an encrypted folder (encfs). I need this to run before any other multi-user.target or graphical.target

Here is my unit file, which works by it's self.

[Unit]
Description=Mx Encrypted Folder

[Service]
Type=oneshot
ExecStart=/usr/bin/mxmountencrypted
RemainAfterExit=true
ExecStop=/usr/bin/mxunmountencrypted

This unit file has no dependencies defined, currently.

Again, I need:

To run this directly after mounting file systems (local-fs.target)

Before any multi-user.target or graphical.target, where must of the services that depend on it will be ran.

It must stop fully before stopping local-fs.target, since there will be a nested mount that needs to be unmounted before systemd can unmount the partition.

I looked into using the systemd.mount item, but it doesn't support encfs.

Body:
Based on what you have listed in the requirements:

[Unit]
Description=Mx Encrypted Folder
Requires=local-fs.target
After=local-fs.target

[Service]
Type=oneshot
ExecStart=/usr/bin/mxmountencrypted
RemainAfterExit=true
ExecStop=/usr/bin/mxunmountencrypted

[Install]
WantedBy=multi-user.target

More on systemd Unit files here: https://www.freedesktop.org/software/systemd/man/systemd.unit.html

and systemd Service files: https://www.freedesktop.org/software/systemd/man/systemd.service.html


问:
Divide and Difference Between Two TextBoxes
I want to get difference and divided value in two textboxes. Either my javascript or Jquery isn't running. I get problem to get output while calculating the difference in Time and Divided value and finally multiplying with 100.

View:

```<code>        <td>
            <input type="text" id="supply" class="supply form-control" onchange="fill()"/>
            <span class="error">Supply required</span>
        </td>

        <td>
            <input type="text" id="POB" class="POB form-control" onchange="fill()"/>
            <span class="error">POB required</span>
        </td>
        <td>
            <input type="text" id="OCC" class="OCC form-control"/>
            <span class="error">OCC required</span>
        </td>

        <td>
            <input type="text" id="ETD" placeholder="00:00" class="ETD form-control" />
            <span class="error">ETD required</span>
        </td>

        <td>
            <input type="text" id="ATD" placeholder="00:00" class="ATD form-control" onchange="DifferenceTime()" />
            <span class="error">ATD required</span>
        </td>

        <td>
            <input type="text" id="Delay" placeholder="00:00" class="Delay form-control" />
            <span class="error">Delay required</span>
        </td>
</code>```

and inside the Page at bottom i have created a function as:

```<code>function fill() {
            var total = (Number($('#POB').val()) / Number($('#supply').val()))*100;
            $('#OCC').val(total);
        }

function DifferenceTime(){
    var time= $('#ATD').val() -$('#ETD').val();
    $('#Delay').val(time);
    }
</code>```

While calculating difference in time is as:
ATD: 00:20
ETD: 00:10 finally Delay should be 00:10. I need suitable help from all members.

答:
This might be more than you were looking for. Hope it helps.

Working Example: https://jsfiddle.net/Twisty/zyLa1xtw/6/

HTML

```<code><div class="ui-widget">
  <table>
    <td>
      <input type="number" id="supply" class="supply form-control" value="0" />
      <span class="error">Supply<em>*</em></span>
    </td>

    <td>
      <input type="number" id="POB" class="POB form-control" value="0" />
      <span class="error">POB<em>*</em></span>
    </td>
    <td>
      <input type="text" id="OCC" class="OCC form-control" />
      <span class="error">OCC<em>*</em></span>
    </td>
    <td>
      <input type="time" id="ETD" placeholder="00:00" class="ETD form-control" />
      <span class="error">ETD<em>*</em></span>
    </td>
    <td>
      <input type="time" id="ATD" placeholder="00:00" class="ATD form-control" />
      <span class="error">ATD<em>*</em></span>
    </td>
    <td>
      <input type="time" id="Delay" class="Delay form-control" />
      <span class="error">Delay<em>*</em></span>
    </td>
  </table>
  <em>*</em> - Required.
</div>
</code>```

Making use of HTML5 input fields, you can help ensure that users are not entering unwanted data.

JavaScript

```<code>function fill(e) {
  var pob = parseInt($('#POB').val()),
    sup = parseInt($('#supply').val());
  if (pob === 0 || sup === 0) {
    return false;
  }
  $('#OCC').val((pob / sup) * 100);
}

function timeDiff(e) {
  if ($('#ATD').val() === "" || $('#ETD').val() === "") {
    return false;
  }
  var t1 = string2times($('#ATD').val()),
    t2 = string2times($('#ETD').val()),
    s1 = (t1.h * 3600) + (t1.m * 60) + (t1.s),
    s2 = (t2.h * 3600) + (t2.m * 60) + (t2.s),
    d = s1 - s2,
    sec = d % 60,
    min = Math.floor(d / 60),
    hour = Math.floor(d / 3600),
    format;

  console.log(t1, t2, s1, s2, d);
  if (d < 10) {
    $('#Delay').val("00:00:0" + d);
    return false;
  }
  if (d < 60) {
    $('#Delay').val("00:00:" + d);
    return false;
  }
  if (d < 3600) {
    min = Math.floor(d / 60);
    sec = d % 60;
    format = (min < 10 ? "0" + min : min) + ":";
    format += (sec < 10 ? "0" + sec : sec);
    $('#Delay').val(format);
    return false;
  }
  sec = d % 60;
  min = Math.floor(d / 60);
  hour = Math.floor(d / 3600);
  format = (hour < 10 ? "0" + hour : hour) + ":";
  format += (min < 10 ? "0" + min : min) + ":";
  format += (sec < 10 ? "0" + sec : sec);
  $('#Delay').val(format);
  return false;
}

function string2times(s) {
  var elems = s.split(":");
  var time = {
    h: 0,
    m: 0,
    s: 0
  };
  if (elems.length == 3) {
    time.h = parseInt(elems[0]);
    time.m = parseInt(elems[1]);
    time.s = parseInt(elems[2]);
  } else {
    console.log("2 Count", elems);
    time.m = parseInt(elems[0]);
    time.s = parseInt(elems[1]);
  }
  return time;
}

$(function() {
  $(".supply, .POB").change(fill);
  $(".ATD").change(timeDiff);
});
</code>```

Depending on how you're loading your JavaScript, your onchange callbacks may not identify the functions. You can easily move all this into one jQuery block and bind the events there.

In regards to calculating the difference between two times, you need to convert the times to seconds, do the math, and convert them back to a human readable result. I wasn't sure if you were working with mm:ss or hh:mm:ss or hh:mm.ss, but I took a guess that users might enter hh:mm:ss or mm:ss and this can handle both.

The functions also check for empty fields or 0 values. Since you cannot divide by 0 and you don't want to subtract from 00:00, resulting ian negative delay value.

Body:
I want to get difference and divided value in two textboxes. Either my javascript or Jquery isn't running. I get problem to get output while calculating the difference in Time and Divided value and finally multiplying with 100.

View:

            <input type="text" id="supply" class="supply form-control" onchange="fill()"/>
            Supply required

            <input type="text" id="POB" class="POB form-control" onchange="fill()"/>
            POB required

            <input type="text" id="OCC" class="OCC form-control"/>
            OCC required

            <input type="text" id="ETD" placeholder="00:00" class="ETD form-control" />
            ETD required

            <input type="text" id="ATD" placeholder="00:00" class="ATD form-control" onchange="DifferenceTime()" />
            ATD required

            <input type="text" id="Delay" placeholder="00:00" class="Delay form-control" />
            Delay required

and inside the Page at bottom i have created a function as:

function fill() {
            var total = (Number($('#POB').val()) / Number($('#supply').val()))*100;
            $('#OCC').val(total);
        }

function DifferenceTime(){
    var time= $('#ATD').val() -$('#ETD').val();
    $('#Delay').val(time);
    }

While calculating difference in time is as:
ATD: 00:20
ETD: 00:10 finally Delay should be 00:10. I need suitable help from all members.

Body:
This might be more than you were looking for. Hope it helps.

Working Example: https://jsfiddle.net/Twisty/zyLa1xtw/6/

HTML

<div class="ui-widget">
  <table>
    <td>
      <input type="number" id="supply" class="supply form-control" value="0" />
      <span class="error">Supply<em>*</em></span>
    </td>

    <td>
      <input type="number" id="POB" class="POB form-control" value="0" />
      <span class="error">POB<em>*</em></span>
    </td>
    <td>
      <input type="text" id="OCC" class="OCC form-control" />
      <span class="error">OCC<em>*</em></span>
    </td>
    <td>
      <input type="time" id="ETD" placeholder="00:00" class="ETD form-control" />
      <span class="error">ETD<em>*</em></span>
    </td>
    <td>
      <input type="time" id="ATD" placeholder="00:00" class="ATD form-control" />
      <span class="error">ATD<em>*</em></span>
    </td>
    <td>
      <input type="time" id="Delay" class="Delay form-control" />
      <span class="error">Delay<em>*</em></span>
    </td>
  </table>
  <em>*</em> - Required.
</div>

Making use of HTML5 input fields, you can help ensure that users are not entering unwanted data.

JavaScript

function fill(e) {
  var pob = parseInt($('#POB').val()),
    sup = parseInt($('#supply').val());
  if (pob === 0 || sup === 0) {
    return false;
  }
  $('#OCC').val((pob / sup) * 100);
}

function timeDiff(e) {
  if ($('#ATD').val() === "" || $('#ETD').val() === "") {
    return false;
  }
  var t1 = string2times($('#ATD').val()),
    t2 = string2times($('#ETD').val()),
    s1 = (t1.h * 3600) + (t1.m * 60) + (t1.s),
    s2 = (t2.h * 3600) + (t2.m * 60) + (t2.s),
    d = s1 - s2,
    sec = d % 60,
    min = Math.floor(d / 60),
    hour = Math.floor(d / 3600),
    format;

  console.log(t1, t2, s1, s2, d);
  if (d < 10) {
    $('#Delay').val("00:00:0" + d);
    return false;
  }
  if (d < 60) {
    $('#Delay').val("00:00:" + d);
    return false;
  }
  if (d < 3600) {
    min = Math.floor(d / 60);
    sec = d % 60;
    format = (min < 10 ? "0" + min : min) + ":";
    format += (sec < 10 ? "0" + sec : sec);
    $('#Delay').val(format);
    return false;
  }
  sec = d % 60;
  min = Math.floor(d / 60);
  hour = Math.floor(d / 3600);
  format = (hour < 10 ? "0" + hour : hour) + ":";
  format += (min < 10 ? "0" + min : min) + ":";
  format += (sec < 10 ? "0" + sec : sec);
  $('#Delay').val(format);
  return false;
}

function string2times(s) {
  var elems = s.split(":");
  var time = {
    h: 0,
    m: 0,
    s: 0
  };
  if (elems.length == 3) {
    time.h = parseInt(elems[0]);
    time.m = parseInt(elems[1]);
    time.s = parseInt(elems[2]);
  } else {
    console.log("2 Count", elems);
    time.m = parseInt(elems[0]);
    time.s = parseInt(elems[1]);
  }
  return time;
}

$(function() {
  $(".supply, .POB").change(fill);
  $(".ATD").change(timeDiff);
});

Depending on how you're loading your JavaScript, your onchange callbacks may not identify the functions. You can easily move all this into one jQuery block and bind the events there.

In regards to calculating the difference between two times, you need to convert the times to seconds, do the math, and convert them back to a human readable result. I wasn't sure if you were working with mm:ss or hh:mm:ss or hh:mm.ss, but I took a guess that users might enter hh:mm:ss or mm:ss and this can handle both.

The functions also check for empty fields or 0 values. Since you cannot divide by 0 and you don't want to subtract from 00:00, resulting ian negative delay value.


问:
How to create a dictionary of arrays to strings in Python?
I'm trying to create a dictionary that maps a specific array like [1,1,0,0] to a string 'Car' but the dictionary does not accept arrays or lists

```<code>a={(1,1,0,0):'Car',
(0,0,0,1):'Pedestrian',
(1,0,0,0):'Traffic Light'}

b=np.array([[1,1,0,0],[1,0,0,0],[0,0,0,1]])
</code>```

Both codes are free of errors but obviously they don't match. Here is my idea:

```<code>b.map(a)

Out[3]=['Car','Traffic Light','Pedestrian']
</code>```

Thanks in advance.

答:
If you are looking after efficiency if b is a big array,  transform it in hashable keys :

```<code>B=(b<<np.arange(4)).sum(1)
# array([3, 1, 8], dtype=int32)
</code>```

Then define dict as :

```<code>A={1: 'Traffic Light', 3: 'Car', 8: 'Pedestrian'}
</code>```

The mapping  now can be:

```<code>[A[key] for key in B]
</code>```

Body:
I'm trying to create a dictionary that maps a specific array like [1,1,0,0] to a string 'Car' but the dictionary does not accept arrays or lists

a={(1,1,0,0):'Car',
(0,0,0,1):'Pedestrian',
(1,0,0,0):'Traffic Light'}

b=np.array([[1,1,0,0],[1,0,0,0],[0,0,0,1]])

Both codes are free of errors but obviously they don't match. Here is my idea:

b.map(a)

Out[3]=['Car','Traffic Light','Pedestrian']

Thanks in advance.

Body:
If you are looking after efficiency if b is a big array,  transform it in hashable keys :

B=(b<<np.arange(4)).sum(1)
# array([3, 1, 8], dtype=int32)

Then define dict as :

A={1: 'Traffic Light', 3: 'Car', 8: 'Pedestrian'}

The mapping  now can be:

[A[key] for key in B]


问:
Is it possible to get a subversion client log file?
At the moment, we have a problem that exists only for a few Subversion clients.

We would like to get a Subversion client log file, which contains information what command was send to the server, what response came back and so on. Is there the possibility to switch on logging to get that information on the client?

I found tons of information what to do with subversion logs, but that does not help here.

Because the notes asked for, here is the problem part:

We have a central LDAP for all authentication information. This is used everywhere in the company,

Subversion is configured such to get the authentication information there,

The clients that have problems tell us that they have to change their password on some days even two or three times due to wrong authentication. The LDAP allows max X times the wrong password in a row, after that, the password has to be changed,

The clients that have problems tell us that they do not use any scripts or automatic clients,

The Apache HTTP Server logs tell us that the clients try to log-in in the same second 15 times.

We use HTTPS to access the subversion server from everywhere.

So I think, there should be anything wrong on the client side, but I have no clue what the reason could be. And the subversion client log files would be a great help here.

答:
Set neon-debug-mask in the [global] section of your subversion servers config file to 138 to get authentication debugging.

```<code>[global]
<snip...>
neon-debug-mask = 138
</code>```

This can be done on the SVN server side and/or the client side. One side is usually enough to see what's exploding.

Most likely the LDAP integration is screwy; keep in mind that depending on your setup, the users' LDAP logins may be case sensitive according to what you've configured in your svn permissions file.

[Note: I haven't actually had to do this since around SVN 1.3, I assume it still works similarly.]

OwnerDisplayName: mliebelt

LastEditorDisplayName: mliebelt

Body:
Set neon-debug-mask in the [global] section of your subversion servers config file to 138 to get authentication debugging.

[global]
<snip...>
neon-debug-mask = 138

This can be done on the SVN server side and/or the client side. One side is usually enough to see what's exploding.

Most likely the LDAP integration is screwy; keep in mind that depending on your setup, the users' LDAP logins may be case sensitive according to what you've configured in your svn permissions file.

[Note: I haven't actually had to do this since around SVN 1.3, I assume it still works similarly.]

OwnerDisplayName: Dan Fitch

LastEditorDisplayName: Dan Fitch


问:
Can you use python-socketio for django?
I've looked around for socketio solutions for Django, and I haven't found anything that says I can use python-socketio for it, but I also haven't found anything that says I can't. It's python, so I would assume it works, but is it bad practice? Will something go wrong?

Thank you

答:
Yes, there are an example app with django in their repos
https://github.com/miguelgrinberg/python-socketio/tree/master/examples/server/wsgi/django_example</p>

Title: Can you use python-socketio for django?


问:
How to get NTWDBLIB.DLL as a 64 bit file
I am trying to compile and run a really really old application on my Windows 7 box.

It seems to need NTWDBLIB.DLL from SQL Server 2000.  I can get that file, but it is a 32 bit file.  When I try to run RegServ32 on it I get an error message.

Installing SQL Server 2000 Client tools is not allowed on Windows 7.

Is there any way of getting this file?  (Short of making a 64 bit VM and installing on it to get the file.)

答:
I just needed to copy the 32 bit version to the SysWOW64 folder rather than the System32 folder.

Kind of lame that the folder with 64 in the name is for the 32 bit stuff and the folder with the 32 in the name is for the 64 bit stuff.