问:
Nodejs not able to respond to more than one request for mongoose connection test
I'm fairly new to mongoose and node. I am trying to write a simple API using Nodejs and Express, wherein I send a MongoDB URI, and if it is valid, i.e. the username/password combo works and a connection to that URI is successfully established, a success message should be returned.

I initially tried to create a separate function to try to connect to the given URI:

```<code>function testURI(uri) {
   mongoose.connect(uri, {useNewUrlParser: true} );
   mongoose.connection.on("connected", function() { return true } );
}

module.exports.test = function(req, res) {
   var uri = req.body.uri;
   if(testURI(uri)) res.status(200).json({'success': true});
   else res.status(400).json({'success': false});
};
</code>```

But this failed, since mongoose connects asyncronously, and the "connected" event callback is not able to return true for the main function

So I dropped the idea for a separate function, and instead tried to achieve it within the module.exports.test function:

```<code>module.exports.test = function(req, res) {
   var uri = req.body.uri;
   mongoose.connect(uri, { useNewUrlParser: true, connectTimeoutMS: 2500 });

   mongoose.connection.on("connected", function() {
       mongoose.connection.close();
       res.status(200).json({'success': true});
   });

 mongoose.connection.on("error", function(err) {
        result = {
            'error': true,
            'errorMsg': 'Error: Could not connect to the given host.'
        }
        mongoose.connection.close();
        res.status(400).json(result);
    });
};
</code>```

This works fine, except that the server dies after responding to one request. Once I try with an invalid URI, it returns HTTP 400 as expected, but then when I send another request with a different URI, the app just crashes with the error

Error: Can't set headers after they are sent.

And then I have to restart the app before I can send another request. Apparently the two separate  res.status(200).json and res.status(400).json in the same controller are creating the problem and the app is treating subsequent requests also as the same request.

答:
Fixed the problem by creating a custom middleware. Instead of returning the result via res.status().json() within the controller function, I used this function as a middleware and returned the result from the next function

```<code>module.exports.test = function(req, res, next) {
   var uri = req.body.uri;
   mongoose.connect(uri, { useNewUrlParser: true, connectTimeoutMS: 2500 });

   mongoose.connection.on("connected", function() {
       mongoose.connection.close();
       req.status = 200;
       req.result = {'success': true};
       next();
   });

 mongoose.connection.on("error", function(err) {
        result = {
            'error': true,
            'errorMsg': 'Error: Could not connect to the given host.'
        }
        mongoose.connection.close();
        req.status = 400;
        req.result = result;
        next();
    });
};

module.exports.returnDb = function(req, res) {
    res.status(req.status).json(req.result);
};
</code>```

Edited route declaration:

```<code>router.route('/test')
.post(client.test, client.returnDb);
</code>```

Body:
I'm fairly new to mongoose and node. I am trying to write a simple API using Nodejs and Express, wherein I send a MongoDB URI, and if it is valid, i.e. the username/password combo works and a connection to that URI is successfully established, a success message should be returned.

I initially tried to create a separate function to try to connect to the given URI:

function testURI(uri) {
   mongoose.connect(uri, {useNewUrlParser: true} );
   mongoose.connection.on("connected", function() { return true } );
}

module.exports.test = function(req, res) {
   var uri = req.body.uri;
   if(testURI(uri)) res.status(200).json({'success': true});
   else res.status(400).json({'success': false});
};

But this failed, since mongoose connects asyncronously, and the "connected" event callback is not able to return true for the main function

So I dropped the idea for a separate function, and instead tried to achieve it within the module.exports.test function:

module.exports.test = function(req, res) {
   var uri = req.body.uri;
   mongoose.connect(uri, { useNewUrlParser: true, connectTimeoutMS: 2500 });

   mongoose.connection.on("connected", function() {
       mongoose.connection.close();
       res.status(200).json({'success': true});
   });

 mongoose.connection.on("error", function(err) {
        result = {
            'error': true,
            'errorMsg': 'Error: Could not connect to the given host.'
        }
        mongoose.connection.close();
        res.status(400).json(result);
    });
};

This works fine, except that the server dies after responding to one request. Once I try with an invalid URI, it returns HTTP 400 as expected, but then when I send another request with a different URI, the app just crashes with the error

Error: Can't set headers after they are sent.

And then I have to restart the app before I can send another request. Apparently the two separate  res.status(200).json and res.status(400).json in the same controller are creating the problem and the app is treating subsequent requests also as the same request.

Body:
Fixed the problem by creating a custom middleware. Instead of returning the result via res.status().json() within the controller function, I used this function as a middleware and returned the result from the next function

module.exports.test = function(req, res, next) {
   var uri = req.body.uri;
   mongoose.connect(uri, { useNewUrlParser: true, connectTimeoutMS: 2500 });

   mongoose.connection.on("connected", function() {
       mongoose.connection.close();
       req.status = 200;
       req.result = {'success': true};
       next();
   });

 mongoose.connection.on("error", function(err) {
        result = {
            'error': true,
            'errorMsg': 'Error: Could not connect to the given host.'
        }
        mongoose.connection.close();
        req.status = 400;
        req.result = result;
        next();
    });
};

module.exports.returnDb = function(req, res) {
    res.status(req.status).json(req.result);
};

Edited route declaration:

router.route('/test')
.post(client.test, client.returnDb);


来源: stackexchange

问:
How to feed LP files to the GLOP solver of or-tools?
I would like to use or-tools and the GLOP solver to solve linear programming problems.

I already have another program that creates LP files which are, as far as I know, fairly standard for defining linear programs.

Has anyone managed to pass those files directly to GLOP? What file format das GLOP understand and how do I pass them to GLOP?

Example lp file:

```<code>maximize 2x1 + 3x2 - x3
subject to
 x1 + x2 <= 1
 x1 + x2 + x3 <= 0
 x2 - 2x3 <= 2
bounds
 x1 free
 x2 free
 x3 free
end
</code>```

Edit:

I am looking for a Java solution

LoadLinearProgramFromModelOrRequest seems to be the way. See here. I don't know how to use it though

答:
There is not API to read LP files, we did not write a good enough LP reader.
We do support reading MPS files.</p>

ContentLicense: CC BY-SA 4.0

Body:
I would like to use or-tools and the GLOP solver to solve linear programming problems.

I already have another program that creates LP files which are, as far as I know, fairly standard for defining linear programs.

Has anyone managed to pass those files directly to GLOP? What file format das GLOP understand and how do I pass them to GLOP?

Example lp file:

maximize 2x1 + 3x2 - x3
subject to
 x1 + x2 <= 1
 x1 + x2 + x3 <= 0
 x2 - 2x3 <= 2
bounds
 x1 free
 x2 free
 x3 free
end

Edit:

I am looking for a Java solution

LoadLinearProgramFromModelOrRequest seems to be the way. See here. I don't know how to use it though


问:
How to align text vertically in middle in UITextView
I'm trying to align text in UITextView vertically in middle. After search I found code and it seems to work until we start to type and hit enter when cursor jumps. When we hit enter key while typing inside text view the cursor jumps to adjust its position which I'm assuming due to the way it's called/implemented.

Is there a better and more elegant solution to this?

I've implemented it as UITextView extension. This code is taken from one of the solutions suggested on Center text vertically in a UITextView

My question is to fix the jumping issue. It's not a duplicate of above question.

```<code>extension UITextView {
    func alignTextVerticallyInContainer() {
        let fittingSize = CGSize(width: bounds.width, height: CGFloat.greatestFiniteMagnitude)
        let size = sizeThatFits(fittingSize)
        let topOffset = ((bounds.size.height - size.height * zoomScale) / 2)
        let positiveTopOffset = max(1, topOffset)
        contentOffset.y = -positiveTopOffset + 1
    }
}
</code>```

And calling it from

```<code>override func viewDidLayoutSubviews() {
    textView.alignTextVerticallyInContainer()
}
</code>```

答:
You can accomplish this with auto-layout only - no code needed.

Start by adding a UIScrollView - I've constrained it to 80-pts from the Top, 20-pts on each side, and a Height constraint of 240 (I set the background to orange-is, to make it easy to see):

Next, add a standard UIView as a subview of the scrollView (I set the background to cyan to make it easy to see). Constrain it 8-pts on each side and on top and bottom (for a little padding). Constrain its Width equal to the scrollView Width, with a constant of -16 (for the side padding), and constrain its Height equal to the scrollView Height, also with a constant of -16 (for the top/bottom padding).

Key point: set the Priority of the Height constraint to Low (250). That will allow it to grow when needed:

Now add a UITextView as a subview of the cyan view. Start with only one line of text. Constrain it 8-pts from each side (for padding); constrain it >= 8-pts on the Top and Bottom; and constrain it Centered Vertically in the span view:

When you run the app, it should function like this (again, no code needed):

Here is the source of the Storyboard:

```<code><?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="LZe-dy-wRt">
    <device id="retina4_7" orientation="portrait">
        <adaptation id="fullscreen"/>
    </device>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14460.20"/>
        <capability name="Safe area layout guides" minToolsVersion="9.0"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--View Controller-->
        <scene sceneID="k3M-Zu-xX0">
            <objects>
                <viewController id="LZe-dy-wRt" sceneMemberID="viewController">
                    <view key="view" contentMode="scaleToFill" id="fZP-6s-NIY">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="guO-HM-qxH">
                                <rect key="frame" x="20" y="100" width="335" height="240"/>
                                <subviews>
                                    <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="zW5-KI-gna">
                                        <rect key="frame" x="8" y="8" width="319" height="224"/>
                                        <subviews>
                                            <textView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" scrollEnabled="NO" text="Start with one line." textAlignment="natural" translatesAutoresizingMaskIntoConstraints="NO" id="S6g-U0-TeD">
                                                <rect key="frame" x="8" y="95.5" width="303" height="33"/>
                                                <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                                                <fontDescription key="fontDescription" type="system" pointSize="14"/>
                                                <textInputTraits key="textInputTraits" autocapitalizationType="sentences"/>
                                            </textView>
                                        </subviews>
                                        <color key="backgroundColor" red="0.45138680930000002" green="0.99309605359999997" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                        <constraints>
                                            <constraint firstAttribute="bottom" relation="greaterThanOrEqual" secondItem="S6g-U0-TeD" secondAttribute="bottom" constant="8" id="Ewc-yq-KHO"/>
                                            <constraint firstItem="S6g-U0-TeD" firstAttribute="leading" secondItem="zW5-KI-gna" secondAttribute="leading" constant="8" id="RIE-gD-bX2"/>
                                            <constraint firstAttribute="trailing" secondItem="S6g-U0-TeD" secondAttribute="trailing" constant="8" id="SfV-e8-TXV"/>
                                            <constraint firstItem="S6g-U0-TeD" firstAttribute="top" relation="greaterThanOrEqual" secondItem="zW5-KI-gna" secondAttribute="top" constant="8" id="byT-nx-8K1"/>
                                            <constraint firstItem="S6g-U0-TeD" firstAttribute="centerY" secondItem="zW5-KI-gna" secondAttribute="centerY" id="qGs-hb-AdH"/>
                                        </constraints>
                                    </view>
                                </subviews>
                                <color key="backgroundColor" red="1" green="0.83234566450000003" blue="0.47320586440000001" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                <constraints>
                                    <constraint firstAttribute="bottom" secondItem="zW5-KI-gna" secondAttribute="bottom" constant="8" id="1xU-wS-Qcb"/>
                                    <constraint firstItem="zW5-KI-gna" firstAttribute="top" secondItem="guO-HM-qxH" secondAttribute="top" constant="8" id="CgB-kT-vjH"/>
                                    <constraint firstItem="zW5-KI-gna" firstAttribute="leading" secondItem="guO-HM-qxH" secondAttribute="leading" constant="8" id="O4I-aF-PEV"/>
                                    <constraint firstAttribute="height" constant="240" id="OZD-dD-yht"/>
                                    <constraint firstAttribute="trailing" secondItem="zW5-KI-gna" secondAttribute="trailing" constant="8" id="QXI-Lh-37A"/>
                                    <constraint firstItem="zW5-KI-gna" firstAttribute="height" secondItem="guO-HM-qxH" secondAttribute="height" priority="250" constant="-16" id="dMe-rS-ZOO"/>
                                    <constraint firstItem="zW5-KI-gna" firstAttribute="width" secondItem="guO-HM-qxH" secondAttribute="width" constant="-16" id="pGF-wL-V4q"/>
                                </constraints>
                            </scrollView>
                        </subviews>
                        <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                        <constraints>
                            <constraint firstItem="XpO-5d-W48" firstAttribute="trailing" secondItem="guO-HM-qxH" secondAttribute="trailing" constant="20" id="Mvu-Ug-NEY"/>
                            <constraint firstItem="guO-HM-qxH" firstAttribute="leading" secondItem="XpO-5d-W48" secondAttribute="leading" constant="20" id="Rfe-Ev-3xj"/>
                            <constraint firstItem="guO-HM-qxH" firstAttribute="top" secondItem="XpO-5d-W48" secondAttribute="top" constant="80" id="YhH-mc-af6"/>
                        </constraints>
                        <viewLayoutGuide key="safeArea" id="XpO-5d-W48"/>
                    </view>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="p5Q-GK-BKG" userLabel="First Responder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="-10" y="775"/>
        </scene>
    </scenes>
</document>
</code>```

Body:
I'm trying to align text in UITextView vertically in middle. After search I found code and it seems to work until we start to type and hit enter when cursor jumps. When we hit enter key while typing inside text view the cursor jumps to adjust its position which I'm assuming due to the way it's called/implemented.

Is there a better and more elegant solution to this?

I've implemented it as UITextView extension. This code is taken from one of the solutions suggested on Center text vertically in a UITextView

My question is to fix the jumping issue. It's not a duplicate of above question.

extension UITextView {
    func alignTextVerticallyInContainer() {
        let fittingSize = CGSize(width: bounds.width, height: CGFloat.greatestFiniteMagnitude)
        let size = sizeThatFits(fittingSize)
        let topOffset = ((bounds.size.height - size.height * zoomScale) / 2)
        let positiveTopOffset = max(1, topOffset)
        contentOffset.y = -positiveTopOffset + 1
    }
}

And calling it from

override func viewDidLayoutSubviews() {
    textView.alignTextVerticallyInContainer()
}

Body:
You can accomplish this with auto-layout only - no code needed.

Start by adding a UIScrollView - I've constrained it to 80-pts from the Top, 20-pts on each side, and a Height constraint of 240 (I set the background to orange-is, to make it easy to see):

Next, add a standard UIView as a subview of the scrollView (I set the background to cyan to make it easy to see). Constrain it 8-pts on each side and on top and bottom (for a little padding). Constrain its Width equal to the scrollView Width, with a constant of -16 (for the side padding), and constrain its Height equal to the scrollView Height, also with a constant of -16 (for the top/bottom padding).

Key point: set the Priority of the Height constraint to Low (250). That will allow it to grow when needed:

Now add a UITextView as a subview of the cyan view. Start with only one line of text. Constrain it 8-pts from each side (for padding); constrain it >= 8-pts on the Top and Bottom; and constrain it Centered Vertically in the span view:

When you run the app, it should function like this (again, no code needed):

Here is the source of the Storyboard:

<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="LZe-dy-wRt">
    <device id="retina4_7" orientation="portrait">
        <adaptation id="fullscreen"/>
    </device>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14460.20"/>
        <capability name="Safe area layout guides" minToolsVersion="9.0"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--View Controller-->
        <scene sceneID="k3M-Zu-xX0">
            <objects>
                <viewController id="LZe-dy-wRt" sceneMemberID="viewController">
                    <view key="view" contentMode="scaleToFill" id="fZP-6s-NIY">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="guO-HM-qxH">
                                <rect key="frame" x="20" y="100" width="335" height="240"/>
                                <subviews>
                                    <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="zW5-KI-gna">
                                        <rect key="frame" x="8" y="8" width="319" height="224"/>
                                        <subviews>
                                            <textView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" scrollEnabled="NO" text="Start with one line." textAlignment="natural" translatesAutoresizingMaskIntoConstraints="NO" id="S6g-U0-TeD">
                                                <rect key="frame" x="8" y="95.5" width="303" height="33"/>
                                                <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                                                <fontDescription key="fontDescription" type="system" pointSize="14"/>
                                                <textInputTraits key="textInputTraits" autocapitalizationType="sentences"/>
                                            </textView>
                                        </subviews>
                                        <color key="backgroundColor" red="0.45138680930000002" green="0.99309605359999997" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                        <constraints>
                                            <constraint firstAttribute="bottom" relation="greaterThanOrEqual" secondItem="S6g-U0-TeD" secondAttribute="bottom" constant="8" id="Ewc-yq-KHO"/>
                                            <constraint firstItem="S6g-U0-TeD" firstAttribute="leading" secondItem="zW5-KI-gna" secondAttribute="leading" constant="8" id="RIE-gD-bX2"/>
                                            <constraint firstAttribute="trailing" secondItem="S6g-U0-TeD" secondAttribute="trailing" constant="8" id="SfV-e8-TXV"/>
                                            <constraint firstItem="S6g-U0-TeD" firstAttribute="top" relation="greaterThanOrEqual" secondItem="zW5-KI-gna" secondAttribute="top" constant="8" id="byT-nx-8K1"/>
                                            <constraint firstItem="S6g-U0-TeD" firstAttribute="centerY" secondItem="zW5-KI-gna" secondAttribute="centerY" id="qGs-hb-AdH"/>
                                        </constraints>
                                    </view>
                                </subviews>
                                <color key="backgroundColor" red="1" green="0.83234566450000003" blue="0.47320586440000001" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                <constraints>
                                    <constraint firstAttribute="bottom" secondItem="zW5-KI-gna" secondAttribute="bottom" constant="8" id="1xU-wS-Qcb"/>
                                    <constraint firstItem="zW5-KI-gna" firstAttribute="top" secondItem="guO-HM-qxH" secondAttribute="top" constant="8" id="CgB-kT-vjH"/>
                                    <constraint firstItem="zW5-KI-gna" firstAttribute="leading" secondItem="guO-HM-qxH" secondAttribute="leading" constant="8" id="O4I-aF-PEV"/>
                                    <constraint firstAttribute="height" constant="240" id="OZD-dD-yht"/>
                                    <constraint firstAttribute="trailing" secondItem="zW5-KI-gna" secondAttribute="trailing" constant="8" id="QXI-Lh-37A"/>
                                    <constraint firstItem="zW5-KI-gna" firstAttribute="height" secondItem="guO-HM-qxH" secondAttribute="height" priority="250" constant="-16" id="dMe-rS-ZOO"/>
                                    <constraint firstItem="zW5-KI-gna" firstAttribute="width" secondItem="guO-HM-qxH" secondAttribute="width" constant="-16" id="pGF-wL-V4q"/>
                                </constraints>
                            </scrollView>
                        </subviews>
                        <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                        <constraints>
                            <constraint firstItem="XpO-5d-W48" firstAttribute="trailing" secondItem="guO-HM-qxH" secondAttribute="trailing" constant="20" id="Mvu-Ug-NEY"/>
                            <constraint firstItem="guO-HM-qxH" firstAttribute="leading" secondItem="XpO-5d-W48" secondAttribute="leading" constant="20" id="Rfe-Ev-3xj"/>
                            <constraint firstItem="guO-HM-qxH" firstAttribute="top" secondItem="XpO-5d-W48" secondAttribute="top" constant="80" id="YhH-mc-af6"/>
                        </constraints>
                        <viewLayoutGuide key="safeArea" id="XpO-5d-W48"/>
                    </view>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="p5Q-GK-BKG" userLabel="First Responder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="-10" y="775"/>
        </scene>
    </scenes>
</document>


问:
How can I switch windows in Vim
I am using Vim and I am unable to switch to one of my windows by using the default bind keys <ctrl+w> j. I have three windows open and the bottom right window is inaccessible. Why is this happening?

答:
<ctrl> + w + w works for me.

If you :sp or :vsp to split a pane, <ctrl> + w + w will allow you to navigate between them.

Title: How can I switch windows in Vim


问:
How to use different random seeds for parallel instances of a reticulate function while using plyr on R
I am trying to combine the parallelizing feature of plyr to call a python function via reticulate but there seems to be an identical seed used on the different instances.

on python:

```<code># This is called python_script.py
import random
def give_a_rand():
   return(random.random())
</code>```

on R

```<code>library(reticulate)
library(plyr)
library(doMC)
doMC::registerDoMC(cores=10)

reticulate::source_python('/path/to/python_script.py')

</code>```

After loading libraries, registering cores for plyr and linking the python script to my R session via reticulate we can now call the python function give_a_rand() natively on R

```<code>> give_a_rand()
[1] 0.896585
</code>```

We can use plyr to run it many times without parallelizing it:

```<code>> aaply(.data=1:10, .margins=1, .fun=function(x){give_a_rand()}, .parallel=F)
          1           2           3           4           5           6
0.183420430 0.539790166 0.817348174 0.130959177 0.143210990 0.794048321
          7           8           9          10
0.276724929 0.820918953 0.003462523 0.903942433
</code>```

I guess that at some point I need to force the seed for the randomization engine in such a way that every instance has a different one.
All is great so far ... but how to parallelize it?

```<code>aaply(.data=1:10, .margins=1, .fun=function(x){give_a_rand()}, .parallel=T)
       1        2        3        4        5        6        7        8
0.896585 0.896585 0.896585 0.896585 0.896585 0.896585 0.896585 0.896585
       9       10
0.896585 0.896585
</code>```

答:
Ok - based on this answer I modified the python function and it works now:</p>

```<code>import random

def seed_from_urandom():
    rand_int = 0
    f = open("/dev/urandom","rb")
    rnd_str = f.read(4)
    for c in rnd_str:
        rand_int <<= 8
        rand_int += int(c)
    return(int(rand_int))

def give_a_rand():
   random.seed(seed_from_urandom())
   return(random.random())
</code>```

Body:
I am trying to combine the parallelizing feature of plyr to call a python function via reticulate but there seems to be an identical seed used on the different instances.

on python:

# This is called python_script.py
import random
def give_a_rand():
   return(random.random())

on R

library(reticulate)
library(plyr)
library(doMC)
doMC::registerDoMC(cores=10)

reticulate::source_python('/path/to/python_script.py')

After loading libraries, registering cores for plyr and linking the python script to my R session via reticulate we can now call the python function give_a_rand() natively on R

> give_a_rand()
[1] 0.896585

We can use plyr to run it many times without parallelizing it:

> aaply(.data=1:10, .margins=1, .fun=function(x){give_a_rand()}, .parallel=F)
          1           2           3           4           5           6
0.183420430 0.539790166 0.817348174 0.130959177 0.143210990 0.794048321
          7           8           9          10
0.276724929 0.820918953 0.003462523 0.903942433

I guess that at some point I need to force the seed for the randomization engine in such a way that every instance has a different one.
All is great so far ... but how to parallelize it?

aaply(.data=1:10, .margins=1, .fun=function(x){give_a_rand()}, .parallel=T)
       1        2        3        4        5        6        7        8
0.896585 0.896585 0.896585 0.896585 0.896585 0.896585 0.896585 0.896585
       9       10
0.896585 0.896585

Body:
Ok - based on this answer I modified the python function and it works now:

import random

def seed_from_urandom():
    rand_int = 0
    f = open("/dev/urandom","rb")
    rnd_str = f.read(4)
    for c in rnd_str:
        rand_int <<= 8
        rand_int += int(c)
    return(int(rand_int))

def give_a_rand():
   random.seed(seed_from_urandom())
   return(random.random())


问:
Why isn't my DiffUtil with RecyclerView working?
I'm trying to create a simple DiffUtil Adapter to work with a RecyclerView and nothing shows up (I only get a blank activity). Here is the code:

MainActivity.java:

```<code>public class MainActivity extends AppCompatActivity {

    private MyAdapter mAdapter;
    private ArrayList<User> myDataset;
    private RecyclerView mRecyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAdapter = new MyAdapter();
        myDataset = new ArrayList<User>();

        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

        myDataset.add(new User("User1"));
        myDataset.add(new User("User2"));
        myDataset.add(new User("User3"));

        mRecyclerView.setAdapter(mAdapter);

        mAdapter.updateList(myDataset);
    }
}
</code>```

Here is MyAdapter.java:

```<code>public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    private AsyncListDiffer<User> mAsyncListDiffer;

    public static class MyViewHolder extends RecyclerView.ViewHolder {

        public TextView singleItemTextView;
        public View layout;
        public ConstraintLayout constraintLayout;

        public MyViewHolder(View v) {
            super(v);
            layout = v;
            singleItemTextView = (TextView) v.findViewById(R.id.singleItemTextView);
            constraintLayout = (ConstraintLayout) v.findViewById(R.id.constraintLayout);
        }
    }

    // Provide a suitable constructor (depends on the kind of dataset)
    public MyAdapter() {
        DiffUtil.ItemCallback<User> diffUtilCallback = new DiffUtil.ItemCallback<User>() {

            @Override
            public boolean areItemsTheSame(@NonNull User newUser, @NonNull User oldUser) {
                return newUser.getUserId().equals(oldUser.getUserId());
            }

            @Override
            public boolean areContentsTheSame(@NonNull User newUser, @NonNull User oldUser) {
                return newUser.equals(oldUser);
            }
        };
        mAsyncListDiffer = new AsyncListDiffer<>(this, diffUtilCallback);
    }

    // Create new views (invoked by the layout manager)
    @Override
    public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_text_view, parent, false);
        MyViewHolder vh = new MyViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {
        User user = mAsyncListDiffer.getCurrentList().get(position);
        holder.singleItemTextView.setText(user.getUserId());
    }

    @Override
    public int getItemCount() {
        return mAsyncListDiffer.getCurrentList().size();
    }

    public void updateList(ArrayList<User> newList) {
        mAsyncListDiffer.submitList(newList);
    }

}
</code>```

Here is User.java:

```<code>public class User {

    private String mUserId;

    public User(String userId) {
        mUserId = userId;
    }

    public String getUserId() {
        return mUserId;
    }

}
</code>```

Here are the XML files:

acivity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_margin="4dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:background="#FFFFFF"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

and here is single_text_view.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:layout_editor_absoluteY="81dp">

    <TextView
        android:id="@+id/singleItemTextView"
        android:layout_width="78dp"
        android:layout_height="78dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

I know that DiffUtil is supposed to compare 2 different lists and here I only set up the initial list, but still, shouldn't it at least display the first list (with 3 users in this case)?

答:
Set LayoutManager with Recyclerview</p>

```<code>    // add data on list
     private ArrayList<User> myDataset=new ArrayList;
     myDataset.add(new User("abc"));

    mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
    LayoutManager layoutManager=new LinearLayoutManager(getActivity());
    mRecyclerView.setLayoutManager(layoutManager);
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    MyAdapter myAdapter=new MyAdapter();
    mAdapter.updateList(myDataset);
    mRecyclerView.setAdapter(mAdapter);
</code>```

Body:
I'm trying to create a simple DiffUtil Adapter to work with a RecyclerView and nothing shows up (I only get a blank activity). Here is the code:

MainActivity.java:

public class MainActivity extends AppCompatActivity {

    private MyAdapter mAdapter;
    private ArrayList<User> myDataset;
    private RecyclerView mRecyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAdapter = new MyAdapter();
        myDataset = new ArrayList<User>();

        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

        myDataset.add(new User("User1"));
        myDataset.add(new User("User2"));
        myDataset.add(new User("User3"));

        mRecyclerView.setAdapter(mAdapter);

        mAdapter.updateList(myDataset);
    }
}

Here is MyAdapter.java:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    private AsyncListDiffer<User> mAsyncListDiffer;

    public static class MyViewHolder extends RecyclerView.ViewHolder {

        public TextView singleItemTextView;
        public View layout;
        public ConstraintLayout constraintLayout;

        public MyViewHolder(View v) {
            super(v);
            layout = v;
            singleItemTextView = (TextView) v.findViewById(R.id.singleItemTextView);
            constraintLayout = (ConstraintLayout) v.findViewById(R.id.constraintLayout);
        }
    }

    // Provide a suitable constructor (depends on the kind of dataset)
    public MyAdapter() {
        DiffUtil.ItemCallback<User> diffUtilCallback = new DiffUtil.ItemCallback<User>() {

            @Override
            public boolean areItemsTheSame(@NonNull User newUser, @NonNull User oldUser) {
                return newUser.getUserId().equals(oldUser.getUserId());
            }

            @Override
            public boolean areContentsTheSame(@NonNull User newUser, @NonNull User oldUser) {
                return newUser.equals(oldUser);
            }
        };
        mAsyncListDiffer = new AsyncListDiffer<>(this, diffUtilCallback);
    }

    // Create new views (invoked by the layout manager)
    @Override
    public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_text_view, parent, false);
        MyViewHolder vh = new MyViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {
        User user = mAsyncListDiffer.getCurrentList().get(position);
        holder.singleItemTextView.setText(user.getUserId());
    }

    @Override
    public int getItemCount() {
        return mAsyncListDiffer.getCurrentList().size();
    }

    public void updateList(ArrayList<User> newList) {
        mAsyncListDiffer.submitList(newList);
    }

}

Here is User.java:

public class User {

    private String mUserId;

    public User(String userId) {
        mUserId = userId;
    }

    public String getUserId() {
        return mUserId;
    }

}

Here are the XML files:

acivity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_margin="4dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:background="#FFFFFF"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

and here is single_text_view.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:layout_editor_absoluteY="81dp">

    <TextView
        android:id="@+id/singleItemTextView"
        android:layout_width="78dp"
        android:layout_height="78dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

I know that DiffUtil is supposed to compare 2 different lists and here I only set up the initial list, but still, shouldn't it at least display the first list (with 3 users in this case)?

Body:
Set LayoutManager with Recyclerview

    // add data on list
     private ArrayList<User> myDataset=new ArrayList;
     myDataset.add(new User("abc"));

    mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
    LayoutManager layoutManager=new LinearLayoutManager(getActivity());
    mRecyclerView.setLayoutManager(layoutManager);
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    MyAdapter myAdapter=new MyAdapter();
    mAdapter.updateList(myDataset);
    mRecyclerView.setAdapter(mAdapter);


问:
docker build Error checking context: 'can't stat '\\?\C:\Users\username\AppData\Local\Application Data''
docker build failed on windows 10,

After docker installed successfully, While building docker image using below command.

docker build -t drtuts:latest .
Facing below issue.

Kindly let me know if any one resolved same issue.

答:
On Windows 10

Opened command line

c:\users\User>

mkdir dockerfiles

cd dockerfiles

notepad Dockerfile.txt

//after notepad opens to type your docker commands and then save your
  Dockerfile.
  back to the command line type "python-hello-world" is an example.

docker image build -t python-hello-world -f ./Dockerfile.txt .

ContentLicense: CC BY-SA 3.0


问:
Linked Lists Append To Tail
I am trying to create an appendToTail function which will add a node to the end of a singly linked list.

I am having trouble in adding a node if the head is NULL(the linked list is empty)

```<code>class Node {
private:
    Node* next;
    int data;

public:
    Node(int d, Node* n = NULL)
        : data(d)
        , next(n)
    {
    }
    void appendToTail(int);
    //other trivial functions(getters and setters etc. ) defined and
    //declared
};

void Node::appendToTail(int d)
{
    Node* end = new Node(d);

    Node* n = this;

    if (n == NULL)
        n = end;

    else {
        while (n->next != NULL)
            n = n->next;
        n->next = end;
        n->next->next = NULL;
    }

    end = NULL;
    delete end;
}

int main()
{
    Node* n = NULL;
    n->appendToTail(5);
    std::cout << n->getData(); //getData() is a function which
    //retrieves the Data member variable
}
</code>```

I am expecting to get 5 but I am getting an error which appears to be caused because my node remains null.

答:
Unfortunately there several errors with your approach. Semantic errors and a logical error with your interpretation of a linked list. Let's start with your initial misunderstanding. You cannot add a new tail to an empty list. Because it is emtpy. Meaning, not yet existing. Only if some object is existing/instantiated you can add a tail. You cannot add something to not existing stuff. So your idea to start with a Node* n = nullptr cannot work logically.

Additionally you are dereferencing a nullptr (major bug). That is also the main problem of your code. Nothing works. You need an instantiated object, before you can call it's member functions.

So before you can populate the list, you need to create/instantiate it initially. So you need to explicitly create the first node in your main function with

```<code> Node* n = new Node (5)
</code>```

Then the list is existing and from now on you can add new members with calling appendToTail.

There are more semantic errors in your code which have luckily no side effects.

You must not delete the 'end' variable in your function. You want to keep the newly allocated memory for the new tail. But you introduced an additional sematic error by setting 'end' to nullptr and then call delete. Deleting a nullptr is a noOp and will do nothing. So, although you have a semantic error, this will not cause any trouble.

There is more:

For a pointer to Null you should always use nullptr.

And, your

```<code>if (n == NULL)
</code>```

is always false. Before that, you assigned this to n. This is never NULL. You can delete the if else. Keep the statements from the else, except the

```<code>n->next->next = NULL;
</code>```

That's not necessary. The constructor did that already for you. As explained, the next 2 statements should also be elimanted.

Additionally you may want to read a little more on the concept of linked lists.

I hope I could help a little

Title: Linked Lists Append To Tail

Body:
I am trying to create an appendToTail function which will add a node to the end of a singly linked list.

I am having trouble in adding a node if the head is NULL(the linked list is empty)

class Node {
private:
    Node* next;
    int data;

public:
    Node(int d, Node* n = NULL)
        : data(d)
        , next(n)
    {
    }
    void appendToTail(int);
    //other trivial functions(getters and setters etc. ) defined and
    //declared
};

void Node::appendToTail(int d)
{
    Node* end = new Node(d);

    Node* n = this;

    if (n == NULL)
        n = end;

    else {
        while (n->next != NULL)
            n = n->next;
        n->next = end;
        n->next->next = NULL;
    }

    end = NULL;
    delete end;
}

int main()
{
    Node* n = NULL;
    n->appendToTail(5);
    std::cout << n->getData(); //getData() is a function which
    //retrieves the Data member variable
}

I am expecting to get 5 but I am getting an error which appears to be caused because my node remains null.

Body:
Unfortunately there several errors with your approach. Semantic errors and a logical error with your interpretation of a linked list. Let's start with your initial misunderstanding. You cannot add a new tail to an empty list. Because it is emtpy. Meaning, not yet existing. Only if some object is existing/instantiated you can add a tail. You cannot add something to not existing stuff. So your idea to start with a Node* n = nullptr cannot work logically.

Additionally you are dereferencing a nullptr (major bug). That is also the main problem of your code. Nothing works. You need an instantiated object, before you can call it's member functions.

So before you can populate the list, you need to create/instantiate it initially. So you need to explicitly create the first node in your main function with

 Node* n = new Node (5)

Then the list is existing and from now on you can add new members with calling appendToTail.

There are more semantic errors in your code which have luckily no side effects.

You must not delete the 'end' variable in your function. You want to keep the newly allocated memory for the new tail. But you introduced an additional sematic error by setting 'end' to nullptr and then call delete. Deleting a nullptr is a noOp and will do nothing. So, although you have a semantic error, this will not cause any trouble.

There is more:

For a pointer to Null you should always use nullptr.

And, your

if (n == NULL)

is always false. Before that, you assigned this to n. This is never NULL. You can delete the if else. Keep the statements from the else, except the

n->next->next = NULL;

That's not necessary. The constructor did that already for you. As explained, the next 2 statements should also be elimanted.

Additionally you may want to read a little more on the concept of linked lists.

I hope I could help a little


问:
jquery select table columns
I am working on selecting a specific table's cells.

Some cells have a class of "testOff", and I'm attempting to change the table row to a different color, if the class exists.

here's what I have so far:

```<code>$("table#customersTable td.testOff").each(function(){

    $(this).closest("tr").css("background-color","#F6CCDA");

});
</code>```

I must be missing something, since it's not showing the background color for any of the cells.
Does anyone see an error with how I'm selecting?

答:
You can use the :has selector:</p>

```<code>$('#customersTable tr:has(td.testOff)').css('background-color', '#f6ccda');
</code>```

Title: jquery select table columns

Body:
I am working on selecting a specific table's cells.

Some cells have a class of "testOff", and I'm attempting to change the table row to a different color, if the class exists.

here's what I have so far:

$("table#customersTable td.testOff").each(function(){

    $(this).closest("tr").css("background-color","#F6CCDA");

});

I must be missing something, since it's not showing the background color for any of the cells.
Does anyone see an error with how I'm selecting?

Body:
You can use the :has selector:

$('#customersTable tr:has(td.testOff)').css('background-color', '#f6ccda');


问:
Arrange a matrix by rownames
I have a matrix with 40 rows. It looks like this :

```<code>Sample_10.rare       0       0
Sample_11.rare       0      42
Sample_12.rare       0       0
Sample_13.rare     762     550
Sample_14.rare     847     508
Sample_15.rare    1143     593
Sample_16.rare    5630    5291
Sample_17.rare    4064    3683
Sample_18.rare    5969    4318
Sample_19.rare      42     212
Sample_1.rare     5037    3598
Sample_20.rare     127     381
Sample_21.rare     127       0
Sample_22.rare     339     254
Sample_23.rare       0      85
Sample_24.rare       0       0
Sample_25.rare      42      42
Sample_26.rare     339     339
Sample_27.rare    5376    4741
Sample_28.rare   11006    8678
Sample_29.rare     339     296
Sample_2.rare     6815    5164
Sample_30.rare     212     466
</code>```

I would like to rearrange the order of the rows. From the row Sample_1.rare to the row Sample_40.rare , in the good order. Is there a solution?

答:
Try mixedorder from gtools package,i.e.

```<code>m2[gtools::mixedorder(rownames(m2)),]
</code>```

which gives,

```<code>                  V2   V3
Sample_1.rare   5037 3598
Sample_2.rare   6815 5164
Sample_10.rare     0    0
Sample_11.rare     0   42
Sample_12.rare     0    0
Sample_13.rare   762  550
Sample_14.rare   847  508
Sample_15.rare  1143  593
Sample_16.rare  5630 5291
Sample_17.rare  4064 3683
Sample_18.rare  5969 4318
Sample_19.rare    42  212
Sample_20.rare   127  381
Sample_21.rare   127    0
Sample_22.rare   339  254
Sample_23.rare     0   85
Sample_24.rare     0    0
Sample_25.rare    42   42
Sample_26.rare   339  339
Sample_27.rare  5376 4741
Sample_28.rare 11006 8678
Sample_29.rare   339  296
Sample_30.rare   212  466
</code>```

DATA

```<code>dput(m2)
structure(c(0L, 0L, 0L, 762L, 847L, 1143L, 5630L, 4064L, 5969L,
42L, 5037L, 127L, 127L, 339L, 0L, 0L, 42L, 339L, 5376L, 11006L,
339L, 6815L, 212L, 0L, 42L, 0L, 550L, 508L, 593L, 5291L, 3683L,
4318L, 212L, 3598L, 381L, 0L, 254L, 85L, 0L, 42L, 339L, 4741L,
8678L, 296L, 5164L, 466L), .Dim = c(23L, 2L), .Dimnames = list(
    c("Sample_10.rare", "Sample_11.rare", "Sample_12.rare", "Sample_13.rare",
    "Sample_14.rare", "Sample_15.rare", "Sample_16.rare", "Sample_17.rare",
    "Sample_18.rare", "Sample_19.rare", "Sample_1.rare", "Sample_20.rare",
    "Sample_21.rare", "Sample_22.rare", "Sample_23.rare", "Sample_24.rare",
    "Sample_25.rare", "Sample_26.rare", "Sample_27.rare", "Sample_28.rare",
    "Sample_29.rare", "Sample_2.rare", "Sample_30.rare"), c("V2",
    "V3")))
</code>```

Title: Arrange a matrix by rownames

Body:
I have a matrix with 40 rows. It looks like this :

Sample_10.rare       0       0
Sample_11.rare       0      42
Sample_12.rare       0       0
Sample_13.rare     762     550
Sample_14.rare     847     508
Sample_15.rare    1143     593
Sample_16.rare    5630    5291
Sample_17.rare    4064    3683
Sample_18.rare    5969    4318
Sample_19.rare      42     212
Sample_1.rare     5037    3598
Sample_20.rare     127     381
Sample_21.rare     127       0
Sample_22.rare     339     254
Sample_23.rare       0      85
Sample_24.rare       0       0
Sample_25.rare      42      42
Sample_26.rare     339     339
Sample_27.rare    5376    4741
Sample_28.rare   11006    8678
Sample_29.rare     339     296
Sample_2.rare     6815    5164
Sample_30.rare     212     466

I would like to rearrange the order of the rows. From the row Sample_1.rare to the row Sample_40.rare , in the good order. Is there a solution?

Body:
Try mixedorder from gtools package,i.e.

m2[gtools::mixedorder(rownames(m2)),]

which gives,

                  V2   V3
Sample_1.rare   5037 3598
Sample_2.rare   6815 5164
Sample_10.rare     0    0
Sample_11.rare     0   42
Sample_12.rare     0    0
Sample_13.rare   762  550
Sample_14.rare   847  508
Sample_15.rare  1143  593
Sample_16.rare  5630 5291
Sample_17.rare  4064 3683
Sample_18.rare  5969 4318
Sample_19.rare    42  212
Sample_20.rare   127  381
Sample_21.rare   127    0
Sample_22.rare   339  254
Sample_23.rare     0   85
Sample_24.rare     0    0
Sample_25.rare    42   42
Sample_26.rare   339  339
Sample_27.rare  5376 4741
Sample_28.rare 11006 8678
Sample_29.rare   339  296
Sample_30.rare   212  466

DATA

dput(m2)
structure(c(0L, 0L, 0L, 762L, 847L, 1143L, 5630L, 4064L, 5969L,
42L, 5037L, 127L, 127L, 339L, 0L, 0L, 42L, 339L, 5376L, 11006L,
339L, 6815L, 212L, 0L, 42L, 0L, 550L, 508L, 593L, 5291L, 3683L,
4318L, 212L, 3598L, 381L, 0L, 254L, 85L, 0L, 42L, 339L, 4741L,
8678L, 296L, 5164L, 466L), .Dim = c(23L, 2L), .Dimnames = list(
    c("Sample_10.rare", "Sample_11.rare", "Sample_12.rare", "Sample_13.rare",
    "Sample_14.rare", "Sample_15.rare", "Sample_16.rare", "Sample_17.rare",
    "Sample_18.rare", "Sample_19.rare", "Sample_1.rare", "Sample_20.rare",
    "Sample_21.rare", "Sample_22.rare", "Sample_23.rare", "Sample_24.rare",
    "Sample_25.rare", "Sample_26.rare", "Sample_27.rare", "Sample_28.rare",
    "Sample_29.rare", "Sample_2.rare", "Sample_30.rare"), c("V2",
    "V3")))


问:
argument of type 'elementfinder' is not assignable to parameter of type 'boolean'
I am trying to make function if check box is not checked then click on it when I call this function I am getting error message
"argument of type 'elementfinder' is not assignable to parameter of type 'boolean'"

//variable

```<code>md5hash_checkbox = element(by.id('md5hash'));
 //To check check box if not selected
  selectCheckBox(checkValue: boolean){
        this.checkValue.isSelected().then(selected => {
            if (selected) {
                console.log(checkValue+': Is Already selected');
            } else {
                this.checkValue.click();
            }
        });
</code>```

on calling function like this.selectCheckBox(this.sha1hash_checkbox);
Getting error message "argument of type 'elementfinder' is not assignable to parameter of type 'boolean'"

答:
selectCheckBox() expects to accept a web element, thus you should declare the argument type to ElementFinder, rather than boolean.  It should be like:

```<code>selectCheckBox(targetElement: ElementFinder) {
  // only when check box is not selected, then click it
  targetElement.isSelected().then(selected => {
    if (selected) {
      console.log('Already selected');
    } else {
      targetElement.click();
    }
  });
}

md5hash_checkbox = element(by.id('md5hash'));;
selectCheckBox(md5hash_checkbox);
</code>```

Body:
I am trying to make function if check box is not checked then click on it when I call this function I am getting error message
"argument of type 'elementfinder' is not assignable to parameter of type 'boolean'"

//variable

md5hash_checkbox = element(by.id('md5hash'));
 //To check check box if not selected
  selectCheckBox(checkValue: boolean){
        this.checkValue.isSelected().then(selected => {
            if (selected) {
                console.log(checkValue+': Is Already selected');
            } else {
                this.checkValue.click();
            }
        });

on calling function like this.selectCheckBox(this.sha1hash_checkbox);
Getting error message "argument of type 'elementfinder' is not assignable to parameter of type 'boolean'"

Body:
selectCheckBox() expects to accept a web element, thus you should declare the argument type to ElementFinder, rather than boolean.  It should be like:

selectCheckBox(targetElement: ElementFinder) {
  // only when check box is not selected, then click it
  targetElement.isSelected().then(selected => {
    if (selected) {
      console.log('Already selected');
    } else {
      targetElement.click();
    }
  });
}

md5hash_checkbox = element(by.id('md5hash'));;
selectCheckBox(md5hash_checkbox);


问:
Kivy Label to display variable value
The label is not displaying the value of price, can someone help me out on why its not working?

The code is as it follows

```<code>Builder.load_string("""
<Mngr>:
    Tela2:
        name: 'tela2'

    Tela5:
        name: 'tela5'

<Tela2>:
    ngd_input: input1
    BoxLayout:
        spacing: 20
        orientation: 'vertical'
        Spinner:
            id: spinner_1
            text: "Regiao"
            values: "Norte", "Nordeste", "Centro-Oeste", "Sudeste", "Sul"
            on_text: root.region_define(spinner_1.text)
        TextInput:
            id: input1
            text: "Necessidade de Geracao (W)"
            on_text: root.ngd_define()

        Button:
            text:  'go to tela5'
            on_press: root.op_dimoff()
            on_release: app.root.current = 'tela5'

<Tela5>:
    cost_output: costa
    Label:
        id: costa
""")

class Mngr (ScreenManager):
    pass

class Tela2(Screen):

    ngd = ObjectProperty()

    def region_define(self, text):

        # valores de irradiação global para as regiões (em KWh/m²*dia)
        inorte: float = 4.825
        inordeste: float = 5.483
        icentro: float = 5.082
        isudeste: float = 4.951
        isul: float = 4.444

        # valores médios do KWh para cada região (em R$/kWh)
        kwh_norte: float = 0.871
        kwh_nordeste: float = 0.308
        kwh_centro: float = 0.290
        kwh_sudeste: float = 0.322
        kwh_sul: float = 0.320

        if text == 'Norte':
            self.irrad = inorte
            self.kwh = kwh_norte

        elif text == 'Nordeste':
            self.irrad = inordeste
            self.kwh = kwh_nordeste

        elif text == 'Centro-Oeste':
            self.irrad = icentro
            self.kwh = kwh_centro

        elif text == 'Sudeste':
            self.irrad = isudeste
            self.kwh = kwh_sudeste

        else:
            self.irrad = isul
            self.kwh = kwh_sul

    def ngd_define(self):

        self.ngd = int(self.ngd_input.text)

    def op_dimoff(self):

        self.gmin = float(self.ngd / self.irrad)

        # dimensionamento potência do inversor
        self.pot_seg = self.gmin * 1.3
        self.inv = (600, 1000, 1500, 2000, 3000)
        self.pri_inv = (1434, 1852.2, 1924, 2604, 3899)
        x = 0
        for x in range(0, len(self.inv)):
            if self.pot_seg <= self.inv[int(x)]:
                self.pot_inv = self.inv[int(x)]
                self.price_inv = self.pri_inv[int(x)]
                break
            else:
                self.x += 1

        self.price = float((int(self.ngd) * 0.87 * 1.75) + self.price_inv)

        cost_v = str(self.price)

        n1 = Tela5()
        n1.catch_values(cost_v)

class Tela5 (Screen):

    cost = StringProperty()

    def catch_values(self, cost):
        self.cost = cost
        self.cost_output.text = self.cost
        print(cost)
        print(self.cost)

class Doideira(App):
    def build(self):
        return Mngr()

if __name__ == "__main__":
    Doideira().run()
</code>```

答:
Root cause

You have instantiated another instance of screen, Tela5 which is different from the other instance instantiated in the kv file. Your second instance of Tela5 does not has a view. Therefore, the updated value is not visible.

Solution

Replace n1 = Tela5() with n1 = self.manager.get_screen("tela5") to get that instance of Tela5 instantiated in the kv file.

Snippets - py file

```<code>    self.price = float((int(self.ngd) * 0.87 * 1.75) + self.price_inv)

    cost_v = str(self.price)

    n1 = self.manager.get_screen("tela5")
    n1.catch_values(cost_v)
</code>```

Output

Title: Kivy Label to display variable value

Body:
The label is not displaying the value of price, can someone help me out on why its not working?

The code is as it follows

Builder.load_string("""
<Mngr>:
    Tela2:
        name: 'tela2'

    Tela5:
        name: 'tela5'

<Tela2>:
    ngd_input: input1
    BoxLayout:
        spacing: 20
        orientation: 'vertical'
        Spinner:
            id: spinner_1
            text: "Regiao"
            values: "Norte", "Nordeste", "Centro-Oeste", "Sudeste", "Sul"
            on_text: root.region_define(spinner_1.text)
        TextInput:
            id: input1
            text: "Necessidade de Geracao (W)"
            on_text: root.ngd_define()

        Button:
            text:  'go to tela5'
            on_press: root.op_dimoff()
            on_release: app.root.current = 'tela5'

<Tela5>:
    cost_output: costa
    Label:
        id: costa
""")

class Mngr (ScreenManager):
    pass

class Tela2(Screen):

    ngd = ObjectProperty()

    def region_define(self, text):

        # valores de irradiação global para as regiões (em KWh/m²*dia)
        inorte: float = 4.825
        inordeste: float = 5.483
        icentro: float = 5.082
        isudeste: float = 4.951
        isul: float = 4.444

        # valores médios do KWh para cada região (em R$/kWh)
        kwh_norte: float = 0.871
        kwh_nordeste: float = 0.308
        kwh_centro: float = 0.290
        kwh_sudeste: float = 0.322
        kwh_sul: float = 0.320

        if text == 'Norte':
            self.irrad = inorte
            self.kwh = kwh_norte

        elif text == 'Nordeste':
            self.irrad = inordeste
            self.kwh = kwh_nordeste

        elif text == 'Centro-Oeste':
            self.irrad = icentro
            self.kwh = kwh_centro

        elif text == 'Sudeste':
            self.irrad = isudeste
            self.kwh = kwh_sudeste

        else:
            self.irrad = isul
            self.kwh = kwh_sul

    def ngd_define(self):

        self.ngd = int(self.ngd_input.text)

    def op_dimoff(self):

        self.gmin = float(self.ngd / self.irrad)

        # dimensionamento potência do inversor
        self.pot_seg = self.gmin * 1.3
        self.inv = (600, 1000, 1500, 2000, 3000)
        self.pri_inv = (1434, 1852.2, 1924, 2604, 3899)
        x = 0
        for x in range(0, len(self.inv)):
            if self.pot_seg <= self.inv[int(x)]:
                self.pot_inv = self.inv[int(x)]
                self.price_inv = self.pri_inv[int(x)]
                break
            else:
                self.x += 1

        self.price = float((int(self.ngd) * 0.87 * 1.75) + self.price_inv)

        cost_v = str(self.price)

        n1 = Tela5()
        n1.catch_values(cost_v)

class Tela5 (Screen):

    cost = StringProperty()

    def catch_values(self, cost):
        self.cost = cost
        self.cost_output.text = self.cost
        print(cost)
        print(self.cost)

class Doideira(App):
    def build(self):
        return Mngr()

if __name__ == "__main__":
    Doideira().run()

Body:
Root cause

You have instantiated another instance of screen, Tela5 which is different from the other instance instantiated in the kv file. Your second instance of Tela5 does not has a view. Therefore, the updated value is not visible.

Solution

Replace n1 = Tela5() with n1 = self.manager.get_screen("tela5") to get that instance of Tela5 instantiated in the kv file.

Snippets - py file

    self.price = float((int(self.ngd) * 0.87 * 1.75) + self.price_inv)

    cost_v = str(self.price)

    n1 = self.manager.get_screen("tela5")
    n1.catch_values(cost_v)

Output


问:
Filter duplicate values from array using javascript/typescript
I have an array of Days as follows:
[monday 3sep,tuesday 4sep, monday 10sep]

I want to get only unique days of the week in my filtered array that should be:
[monday 3sep,tuesday 4sep]

how can i filter this array using ES6 map() and filter()

答:
I am assuming that your array is an array of strings

```<code>var arry = ['monday 3sep','tuesday 4sep', 'monday 10sep']
</code>```

if so you can solve this by using a second array

```<code>var secondarray = []
var filtered = arry.filter(i=>{
  var split = i.split(' ');
  if(secondarray.indexOf(split[0])==-1){
     secondarray.push(split[0]);
     return true;
  }
  return false;
});
</code>```

Body:
I am assuming that your array is an array of strings

var arry = ['monday 3sep','tuesday 4sep', 'monday 10sep']

if so you can solve this by using a second array

var secondarray = []
var filtered = arry.filter(i=>{
  var split = i.split(' ');
  if(secondarray.indexOf(split[0])==-1){
     secondarray.push(split[0]);
     return true;
  }
  return false;
});


问:
How can I ignore a parameter in a URL?
My app decodes URLs and I've noticed that when it hits an "&", the process stops and ignores the rest of the URL. It appears that URLComponents is breaking up the URL into pieces - my required parameter and the one that it believes to be a parameter.

```<code> hxxp://www.g.com/url?u=http://a.com/test&d=another
  - scheme : "hxxp"
  - host : "www.g.com"
  - path : "/url"
  ▿ queryItems : 2 elements
    ▿ 0 : u=http://a.com/test
      - name : "u"
      ▿ value : Optional<String>
        - some : "http://a.com/test"
    ▿ 1 : d=another
      - name : "d"
      ▿ value : Optional<String>
        - some : "another"
</code>```

What I need from above is the full URL after "u=".

Here is the initial call to the function that decodes the string:

```<code>if (fullDecode.contains("?u=")) {
            initialDecode = getQueryStringParameter(urlToAttempt: fullDecode, param: "u")!
</code>```

Here is the function that returns the decoded string:

```<code>func getQueryStringParameter(urlToAttempt: String, param: String) -> String? {
        guard let urlDecoded = URLComponents(string: urlToAttempt) else { return nil }
        print(urlDecoded)
        return urlDecoded.queryItems?.first(where: { $0.name == param })?.value
    }
</code>```

For this code, if the url was "http://www.g.com/url?u=http://a.com/test&d=another", it would return "http://a.com/test" - everything else is stripped away. I'd like it to return "http://a.com/test&d=another"

Is there a way that I'm able to do this with URLComponents, or do I need to do custom code to support this?

Update
If I change the url that's being passed to " hxxp://www.g.com/url?u=http://a.com/test%26d=another", URLComponents returns the full url back with the &d=another intact. I'm now going to try to percent encode the special character before sending to the function and see if that fixes the issue.

Second Update

Here is a heavily modified type of link I need to decode:

```<code>hxxps://ue.pt.com/v2/url?u=https-3A__oe.le.com_-3Fauthkey-3D-2521IB-2DCRV-2DqQ88-26cid-3DBACDF2ED353D-26id-3DBACDF2EFB61D353D-2521549-26parId-3Droot-26o-3DOneUp&d=DwMGaQ&c=WNpQK9bFmT89misLWAzsd66s44iGV-VujF_o4whjrfc&r=Ej_UhLznQMBqt3H3IYBQkjyx4xqdnS9mLiYA&m=HOBrLfxamFr4PYdACIR-A49th_oIe3MW69N7X-E&s=bXWSJ8gaSbKSlNuIf30S7Qsa6RcMKA-EOvP577XUyq0&e=
</code>```

These links are generated, which is why I have no control of how the link is built. I need to be able to decode this link to a legible URL. I have dictionaries for the special obfuscation like "-3A__" is "://" Where the above fails is where you see &d=DwM... It's not encoded, and that's where URLComponents is failing:

```<code>https://oe.le.com/?authkey=!IB-CRV-qQ88&cid=BACDF2ED353D&id=BACDF2EFB6353D!549&parId=root&o=OneUp
</code>```

Does this help?

答:
If your revised question, you give us a URL of the following:

```<code>let string = "hxxps://ue.pt.com/v2/url?u=https-3A__oe.le.com_-3Fauthkey-3D-2521IB-2DCRV-2DqQ88-26cid-3DBACDF2ED353D-26id-3DBACDF2EFB61D353D-2521549-26parId-3Droot-26o-3DOneUp&d=DwMGaQ&c=WNpQK9bFmT89misLWAzsd66s44iGV-VujF_o4whjrfc&r=Ej_UhLznQMBqt3H3IYBQkjyx4xqdnS9mLiYA&m=HOBrLfxamFr4PYdACIR-A49th_oIe3MW69N7X-E&s=bXWSJ8gaSbKSlNuIf30S7Qsa6RcMKA-EOvP577XUyq0&e="
</code>```

Clearly -3A__ is ://, _-3F is /?, -26 is &, -3D is =, etc. So if you do:

```<code>let replacements = [
    "-3A__": "%3A//",
    "_-3F": "/%3F",
    "-26": "%26",
    "-3D": "%3D",
    "-2D": "%2D",
    "-25": "%25"
]

let result = replacements.reduce(string) { (string, tuple) -> String in
    return string.replacingOccurrences(of: tuple.key, with: tuple.value)
}

let components = URLComponents(string: result)!
for item in components.queryItems! {
    print(item.name, item.value!)
}
</code>```

You end up with call to hxxps://ue.pt.com/v2/url with the following parameters:

u https://oe.le.com/?authkey=%21IB-CRV-qQ88&cid=BACDF2ED353D&id=BACDF2EFB61D353D%21549&parId=root&o=OneUp
d DwMGaQ
c WNpQK9bFmT89misLWAzsd66s44iGV-VujF_o4whjrfc
r Ej_UhLznQMBqt3H3IYBQkjyx4xqdnS9mLiYA
m HOBrLfxamFr4PYdACIR-A49th_oIe3MW69N7X-E
s bXWSJ8gaSbKSlNuIf30S7Qsa6RcMKA-EOvP577XUyq0
e
```

<p>The key here is that the parameters <code>authkey</code>, <code>cid</code>, <code>id</code>, <code>parId</code>, and <code>o</code> are for the <code>oe.le.com</code> URL, but all the other parameters, <code>d</code>, <code>c</code>, <code>r</code>, <code>m</code>, <code>s</code>, and <code>e</code> are <em>not</em> part of the URL encoded as part of <code>u</code>, but rather are separate parameters for the <code>ue.pt.com</code> URL. You do not want to include them as part of the URL for <code>oe.le.com</code>.</p>

<p>My original answer is below.</p>

<hr>

<p>Let’s try approaching this problem from the other direction.</p>

<p>Consider these two scenarios where I’m building a URL. In the first, I have a single parameter to <code>g.com</code> which is <code>u</code>, which is a URL that has parameters:</p>

```var components = URLComponents(string: "http://g.com")!
components.queryItems = [
    URLQueryItem(name: "u", value: "http://a.com/test?d=foo&e=bar")
]
let url = components.url
```

<p>You’ll see that url is</p>

<blockquote>
  <p><code>http://g.com/?u=http://a.com/test?d%3Dfoo%26e%3Dbar</code> </p>
</blockquote>

<p>Note that the <code>=</code> and the <code>&</code> are percent escaped as <code>%3D</code> and <code>%26</code>, respectively because they are parameters to the URL buried inside the value associated with the <code>u</code> parameter, not actually parameters of the <code>g.com</code> URL itself.</p>

<p>The alternative scenario is that <code>g.com</code>’s URL has three parameters, <code>u</code>, <code>d</code>, and <code>e</code>:</p>

```var components2 = URLComponents(string: "http://g.com")!
components2.queryItems = [
    URLQueryItem(name: "u", value: "http://a.com/test"),
    URLQueryItem(name: "d", value: "foo"),
    URLQueryItem(name: "e", value: "bar")
]
let url2 = components2.url
```

That yields:

http://g.com/?u=http://a.com/test&d=foo&e=bar

Note that the = and the & are not percent escaped because they are parameters of g.com URL, not parameters of the a.com URL contained with the u value.

You appear to be giving us a URL like generated by the second scenario, but insisting that it really is like the first scenario. If that’s true, the original URL has not been percent encoded correctly and is invalid. More likely, the second scenario applies and the parameters are of the g.com URL, not intended to be part of the u value.

For what it’s worth, note that you’ve given us a URL of:

hxxp://www.g.com/url?u=http://a.com/test&d=another

If d was really a parameter of the a.com URL, that URL would be http://a.com/test?d=another, not http://a.com/test&d=another (Note the ?, not &.)

So this is further evidence that the d parameter is really a parameter of the g.com url, and that the u parameter really is just http://a.com/test.

Title: How can I ignore a parameter in a URL?

Body:
My app decodes URLs and I've noticed that when it hits an "&", the process stops and ignores the rest of the URL. It appears that URLComponents is breaking up the URL into pieces - my required parameter and the one that it believes to be a parameter.

 hxxp://www.g.com/url?u=http://a.com/test&d=another
  - scheme : "hxxp"
  - host : "www.g.com"
  - path : "/url"
  ▿ queryItems : 2 elements
    ▿ 0 : u=http://a.com/test
      - name : "u"
      ▿ value : Optional<String>
        - some : "http://a.com/test"
    ▿ 1 : d=another
      - name : "d"
      ▿ value : Optional<String>
        - some : "another"

What I need from above is the full URL after "u=".

Here is the initial call to the function that decodes the string:

if (fullDecode.contains("?u=")) {
            initialDecode = getQueryStringParameter(urlToAttempt: fullDecode, param: "u")!

Here is the function that returns the decoded string:

func getQueryStringParameter(urlToAttempt: String, param: String) -> String? {
        guard let urlDecoded = URLComponents(string: urlToAttempt) else { return nil }
        print(urlDecoded)
        return urlDecoded.queryItems?.first(where: { $0.name == param })?.value
    }

For this code, if the url was "http://www.g.com/url?u=http://a.com/test&d=another", it would return "http://a.com/test" - everything else is stripped away. I'd like it to return "http://a.com/test&d=another"

Is there a way that I'm able to do this with URLComponents, or do I need to do custom code to support this?

Update
If I change the url that's being passed to " hxxp://www.g.com/url?u=http://a.com/test%26d=another", URLComponents returns the full url back with the &d=another intact. I'm now going to try to percent encode the special character before sending to the function and see if that fixes the issue.

Second Update

Here is a heavily modified type of link I need to decode:

hxxps://ue.pt.com/v2/url?u=https-3A__oe.le.com_-3Fauthkey-3D-2521IB-2DCRV-2DqQ88-26cid-3DBACDF2ED353D-26id-3DBACDF2EFB61D353D-2521549-26parId-3Droot-26o-3DOneUp&d=DwMGaQ&c=WNpQK9bFmT89misLWAzsd66s44iGV-VujF_o4whjrfc&r=Ej_UhLznQMBqt3H3IYBQkjyx4xqdnS9mLiYA&m=HOBrLfxamFr4PYdACIR-A49th_oIe3MW69N7X-E&s=bXWSJ8gaSbKSlNuIf30S7Qsa6RcMKA-EOvP577XUyq0&e=

These links are generated, which is why I have no control of how the link is built. I need to be able to decode this link to a legible URL. I have dictionaries for the special obfuscation like "-3A__" is "://" Where the above fails is where you see &d=DwM... It's not encoded, and that's where URLComponents is failing:

https://oe.le.com/?authkey=!IB-CRV-qQ88&cid=BACDF2ED353D&id=BACDF2EFB6353D!549&parId=root&o=OneUp

Does this help?

Body:
If your revised question, you give us a URL of the following:

let string = "hxxps://ue.pt.com/v2/url?u=https-3A__oe.le.com_-3Fauthkey-3D-2521IB-2DCRV-2DqQ88-26cid-3DBACDF2ED353D-26id-3DBACDF2EFB61D353D-2521549-26parId-3Droot-26o-3DOneUp&d=DwMGaQ&c=WNpQK9bFmT89misLWAzsd66s44iGV-VujF_o4whjrfc&r=Ej_UhLznQMBqt3H3IYBQkjyx4xqdnS9mLiYA&m=HOBrLfxamFr4PYdACIR-A49th_oIe3MW69N7X-E&s=bXWSJ8gaSbKSlNuIf30S7Qsa6RcMKA-EOvP577XUyq0&e="

Clearly -3A__ is ://, _-3F is /?, -26 is &, -3D is =, etc. So if you do:

let replacements = [
    "-3A__": "%3A//",
    "_-3F": "/%3F",
    "-26": "%26",
    "-3D": "%3D",
    "-2D": "%2D",
    "-25": "%25"
]

let result = replacements.reduce(string) { (string, tuple) -> String in
    return string.replacingOccurrences(of: tuple.key, with: tuple.value)
}

let components = URLComponents(string: result)!
for item in components.queryItems! {
    print(item.name, item.value!)
}

You end up with call to hxxps://ue.pt.com/v2/url with the following parameters:

u https://oe.le.com/?authkey=%21IB-CRV-qQ88&cid=BACDF2ED353D&id=BACDF2EFB61D353D%21549&parId=root&o=OneUp
d DwMGaQ
c WNpQK9bFmT89misLWAzsd66s44iGV-VujF_o4whjrfc
r Ej_UhLznQMBqt3H3IYBQkjyx4xqdnS9mLiYA
m HOBrLfxamFr4PYdACIR-A49th_oIe3MW69N7X-E
s bXWSJ8gaSbKSlNuIf30S7Qsa6RcMKA-EOvP577XUyq0
e

The key here is that the parameters authkey, cid, id, parId, and o are for the oe.le.com URL, but all the other parameters, d, c, r, m, s, and e are not part of the URL encoded as part of u, but rather are separate parameters for the ue.pt.com URL. You do not want to include them as part of the URL for oe.le.com.

My original answer is below.

Let’s try approaching this problem from the other direction.

Consider these two scenarios where I’m building a URL. In the first, I have a single parameter to g.com which is u, which is a URL that has parameters:

var components = URLComponents(string: "http://g.com")!
components.queryItems = [
    URLQueryItem(name: "u", value: "http://a.com/test?d=foo&e=bar")
]
let url = components.url

You’ll see that url is

http://g.com/?u=http://a.com/test?d%3Dfoo%26e%3Dbar

Note that the = and the & are percent escaped as %3D and %26, respectively because they are parameters to the URL buried inside the value associated with the u parameter, not actually parameters of the g.com URL itself.

The alternative scenario is that g.com’s URL has three parameters, u, d, and e:

var components2 = URLComponents(string: "http://g.com")!
components2.queryItems = [
    URLQueryItem(name: "u", value: "http://a.com/test"),
    URLQueryItem(name: "d", value: "foo"),
    URLQueryItem(name: "e", value: "bar")
]
let url2 = components2.url

That yields:

http://g.com/?u=http://a.com/test&d=foo&e=bar

Note that the = and the & are not percent escaped because they are parameters of g.com URL, not parameters of the a.com URL contained with the u value.

You appear to be giving us a URL like generated by the second scenario, but insisting that it really is like the first scenario. If that’s true, the original URL has not been percent encoded correctly and is invalid. More likely, the second scenario applies and the parameters are of the g.com URL, not intended to be part of the u value.

For what it’s worth, note that you’ve given us a URL of:

hxxp://www.g.com/url?u=http://a.com/test&d=another

If d was really a parameter of the a.com URL, that URL would be http://a.com/test?d=another, not http://a.com/test&d=another (Note the ?, not &.)

So this is further evidence that the d parameter is really a parameter of the g.com url, and that the u parameter really is just http://a.com/test.


问:
Default size for database fields
What the size that you use for common database fields, like firstName, lastName, Email, password, etc? I see these common fields in a lot of databases of blogs, forums, e-commerces, etc. But I don't know if there is some reference or default for the size for that common fields. So, I want to know what the method/reference/basis that you to use for selecting size for common fields.</p>

答:
Try to think this out in reverse: I've used existing data to get reasonable field lengths. Assuming you have access to a good-sized database filled with real data, a quick query like:

```<code>SELECT MAX(LEN(lastname)) FROM dbo.MyDatabase
</code>```

will give you everything you need.

UPDATE: Don't use the number you get exactly. Obviously, pad it up a little depending on your uncertainty, unless you have a very large sample set.

OwnerDisplayName: Click Ok

ContentLicense: CC BY-SA 2.5

Title: Default size for database fields

Body:
Try to think this out in reverse: I've used existing data to get reasonable field lengths. Assuming you have access to a good-sized database filled with real data, a quick query like:

SELECT MAX(LEN(lastname)) FROM dbo.MyDatabase

will give you everything you need.

UPDATE: Don't use the number you get exactly. Obviously, pad it up a little depending on your uncertainty, unless you have a very large sample set.

OwnerDisplayName: alphadogg

LastEditorDisplayName: alphadogg


问:
Alert for reminding the user to rate the app
As you may have seen in some apps an alert pops up asking the user to rate the app in itunes and usually the alternatives you get to choose from is something like: Sure which opens the rate page for the app. The second option is No Thanks which closes the alert and the third option usually is maybe later which displays the alert later.

I was wondering how to do this.
I want the alert to be displayed after say the app has launched 20 times if that would be possible.
And how can I create an maybe later alternative which displays the alert maybe 15 launches of the app later?

And a final question is there a special link for the apps rate page? So when you click the sure button or whatever it will take your directly to the rate page.

答:
You can use NSUserDefaults to save the launch count (increment it in application:didFinishLaunchingWithOptions:), then save the user's choice another preference key. If the user says later, you could reset the counter back to zero.

<s>I don't think there is a special rating link, but you can link to your app's specific App Store page.</s> This was incorrect, as TomSwift points out; see Direct "rate in iTunes" link in my app?


问:
Running postgres 9.5 and django in one container for CI (Bamboo)
I am trying to configure a CI job on Bamboo for a Django app, the tests to be run rely on a database (postgres 9.5). It seems that a prudent way to go about is it run the whole test in a docker container, as I do not control the agent environment so I cannot install Postgres there.

Most guides I found recommend running postgres and django in two separate containers and using docker-compose to easily manage them. In this scenario each docker image runs just one service, started with CMD. In Bamboo I cannot use docker-compose however, I need to use just one image, so I am trying to get Postgres and Django to run nicely together in one container but with little success so far.

My problem is that I see no easy way to start Postgres as a service inside docker but NOT as a docker CMD command, official postgre image uses an entrypoint.sh approach, also described in the official docker docs
But it is not clear to me how to implement that. I would appreciate your help!

答:
Your only other option is to add in a startup script in your Dockerfile, or kick it off as part of your docker run ... commands.  We don't generally use the "Docker" tasks, as I find them ... distasteful (also why I usually just fall back to running a "Script" task, and directly calling docker run in that script task)

Anyway, you'd have to have your Docker container execute a script that would:

Start up Postgres (like a sudo systemctl start postgresql)

Execute your tests.

Your Dockerfile will have to install Postgresql and do some minor setup work I imagine (like create relevant users and databases with the proper owner).  Since we're all good citizens, we remember to never run your containers as root, right?

Note - you can always hack around getting two containers to talk to each other without using docker-compose.  It's a bit less convenient, but you could do something like:

```<code>docker run --detach --cidfile=db_cidfile --name ci_db postgresql_image
...
docker run --link ci_db testing_image
</code>```

Make sure that you EXPOSE the right ports on the postgresql image to the testing_image container.

EDIT:  I'm looking more at my specific case - we just install Postgresql into a base CentOS host rather than use the postgresql default image (using yum install http://yum.postgresql.org/..../pgdg-centos...rpm and then just install postgresql-server and postgresql-contrib packages from there).  There is a CMD [ "/usr/pgsql-ver/bin/postgres", "-D", "/var/lib/pgsql/ver/data"] in our Dockerfile, too.  We don't do anything fancy with the docker container, though.  NOTE: we don't use this in production at all, this is strictly for local and CI testing.

Body:
Your only other option is to add in a startup script in your Dockerfile, or kick it off as part of your docker run ... commands.  We don't generally use the "Docker" tasks, as I find them ... distasteful (also why I usually just fall back to running a "Script" task, and directly calling docker run in that script task)

Anyway, you'd have to have your Docker container execute a script that would:

Start up Postgres (like a sudo systemctl start postgresql)

Execute your tests.

Your Dockerfile will have to install Postgresql and do some minor setup work I imagine (like create relevant users and databases with the proper owner).  Since we're all good citizens, we remember to never run your containers as root, right?

Note - you can always hack around getting two containers to talk to each other without using docker-compose.  It's a bit less convenient, but you could do something like:

docker run --detach --cidfile=db_cidfile --name ci_db postgresql_image
...
docker run --link ci_db testing_image

Make sure that you EXPOSE the right ports on the postgresql image to the testing_image container.

EDIT:  I'm looking more at my specific case - we just install Postgresql into a base CentOS host rather than use the postgresql default image (using yum install http://yum.postgresql.org/..../pgdg-centos...rpm and then just install postgresql-server and postgresql-contrib packages from there).  There is a CMD [ "/usr/pgsql-ver/bin/postgres", "-D", "/var/lib/pgsql/ver/data"] in our Dockerfile, too.  We don't do anything fancy with the docker container, though.  NOTE: we don't use this in production at all, this is strictly for local and CI testing.


问:
Apache Storm 1.1.0
I have a topology that has been created using Apache storm. I have created different Bolts and spout in place to perform various activities. However, I am planning on creating an automated test suite for testing the functionalities of the topology.

Can some help me if you have done a similar thing or suggest me a tool/language that helps me to achieve it? Currently, my topology is in Java.

答:
The fastests tests are going to be unit tests. If you can write most of your business logic in a way that is decoupled from Storm's APIs, you can write your tests as regular JUnit tests, maybe with Mockito or a similar tool to stub collaborators. Basically your standard Java unit tests.

For integration testing where you need to check whether you're using Storm correctly, or need to do a full end to end test of your topology, you can look at the org.apache.storm.Testing class, which helps you start a LocalCluster. There are some examples at https://github.com/xumingming/storm-lib/blob/master/src/jvm/storm/TestingApiDemo.java. The basic idea is to boot up Storm in the same JVM as the test, and then deploy the topology into it.

As of 2.0.0 there's a LocalCluster builder class making it a little easier to instantiate LocalCluster from Java.

Just to give an idea of what LocalCluster offers:

Can run your topology in the same process as your tests

You can enable tuple tracking, which causes the cluster to track all emitted tuples from all components. This lets you e.g. assert that a certain tuple was emitted from a certain component.

Lets you replace your spouts with stubs. This can let you inject specific tuples into the topology easily, e.g. using a FixedTupleSpout or FeederSpout.

Lets you do assertions about which tuples were acked/failed

Some stubbed spouts are completable spouts, which means they have an API to indicate to Storm when they have emitted and acked/failed all tuples. This can let you e.g. start a topology in the test and ask for Storm to run it until all tuples are processed. This makes it easier to write tests that are not flaky, since you don't need to know how long it takes to finish processing your tuples.

For other examples of how to use LocalCluster, you can take a look at some of our own integration tests at https://github.com/apache/storm/blob/8f49e06998abb4dfc50f51d78b6784ebd04844fb/storm-core/test/jvm/org/apache/storm/integration/TopologyIntegrationTest.java. Please ignore the way the topologies are wired in these tests, you should just use TopologyBuilder in your own tests.

Title: Apache Storm 1.1.0


问:
I want to read from Properties file and put that value in a string based on a key from file
I am new learning python and I have to deal with the properties file in that file the value will be present in key value pair and some how I think managed to readFile but not able to store or print the value based on a key.

I have tried with the jproperties libraries installed through pip.I have read the values in the object but unable to fetch the records from it.
Have gone through https://pypi.org/project/jproperties/#parsing-a-property-file website for reference

```<code>from jproperties import Properties

class PropertiesReader:
    p = Properties()
    with open("foobar.properties", "rt") as f:
        p.load(f, "utf-8")

    s = p.__getitem__("name","value")
    z = p.__getattribute__("email","mail")
    print(s)
    print(z)
</code>```

and the properties file

```<code>foobar.properties
    name = Harsh
    email = abc.xyz
</code>```

and the output is

```<code>Traceback (most recent call last):
  File "/home/harshk/PycharmProjects/demoPythonPOC/scratch.py", line 4, in <module>
    class PropertiesReader:
  File "/home/harshk/PycharmProjects/demoPythonPOC/scratch.py", line 7, in PropertiesReader
    p.load(f, "utf-8")
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 804, in load
    self._parse()
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 731, in _parse
    while self._parse_logical_line():
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 686, in _parse_logical_line
    self._skip_whitespace()
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 438, in _skip_whitespace
    c = self._peek()
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 378, in _peek
    c = self._source_file.read(1)
  File "/usr/local/lib/python3.7/codecs.py", line 500, in read
    data = self.bytebuffer + newdata
TypeError: can't concat str to bytes

Process finished with exit code 1
</code>```

I want to print like

```<code>Harsh
abc.xyz
</code>```

答:
You're opening the file as if it's a text file:

```<code>with open("foobar.properties", "rt") as f:
    p.load(f, "utf-8")
</code>```

But the jproperties docs shows that you need to open the file in binary mode:

```<code>with open("foobar.properties", "rb") as f:
    p.load(f, "utf-8")
</code>```

Body:
I am new learning python and I have to deal with the properties file in that file the value will be present in key value pair and some how I think managed to readFile but not able to store or print the value based on a key.

I have tried with the jproperties libraries installed through pip.I have read the values in the object but unable to fetch the records from it.
Have gone through https://pypi.org/project/jproperties/#parsing-a-property-file website for reference

from jproperties import Properties

class PropertiesReader:
    p = Properties()
    with open("foobar.properties", "rt") as f:
        p.load(f, "utf-8")

    s = p.__getitem__("name","value")
    z = p.__getattribute__("email","mail")
    print(s)
    print(z)

and the properties file

foobar.properties
    name = Harsh
    email = abc.xyz

and the output is

Traceback (most recent call last):
  File "/home/harshk/PycharmProjects/demoPythonPOC/scratch.py", line 4, in <module>
    class PropertiesReader:
  File "/home/harshk/PycharmProjects/demoPythonPOC/scratch.py", line 7, in PropertiesReader
    p.load(f, "utf-8")
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 804, in load
    self._parse()
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 731, in _parse
    while self._parse_logical_line():
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 686, in _parse_logical_line
    self._skip_whitespace()
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 438, in _skip_whitespace
    c = self._peek()
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 378, in _peek
    c = self._source_file.read(1)
  File "/usr/local/lib/python3.7/codecs.py", line 500, in read
    data = self.bytebuffer + newdata
TypeError: can't concat str to bytes

Process finished with exit code 1

I want to print like

Harsh
abc.xyz

Body:
You're opening the file as if it's a text file:

with open("foobar.properties", "rt") as f:
    p.load(f, "utf-8")

But the jproperties docs shows that you need to open the file in binary mode:

with open("foobar.properties", "rb") as f:
    p.load(f, "utf-8")


问:
How to fix PyImport_Import in C++ (Exception in python35.dll)
I am trying a really basic "hello world" program, which should embedd a python script in my C++ console application, but it fails at pModule = PyImport_Import(pName); with an unspecified exception "Access violation reading location ..."

I was already able to run PyRun_SimpleFile() for a python script without definitions and returns, but for my future application I need a python method with returns, so PyRun_SimpleFile() is not an option.

My code, based on this Introduction is:

main.cpp

```<code>#include "stdafx.h"
#include <stdlib.h>
#include <Python.h>

int main(int argc, char *argv[])
{
    PyObject *pName, *pModule;
    PyObject *pFunc, *pValue;

    pName = PyUnicode_FromString("HelloWorld");
    pModule = PyImport_Import(pName);
    Py_XDECREF(pName);

    if (pModule)
    {
        pFunc = PyObject_GetAttrString(pModule, "getInteger");
        if (pFunc && PyCallable_Check(pFunc))
        {
            pValue = PyObject_CallObject(pFunc, NULL);
            printf_s("C: getInteger() = %ld\n", PyLong_AsLong(pValue));
            Py_XDECREF(pValue);
        }
        else
        {
            printf("ERROR: function getInteger()\n");
        }
        Py_XDECREF(pFunc);
    }
    else
    {
        printf_s("ERROR: Module not imported\n");
    }

    Py_XDECREF(pModule);

    Py_Finalize();
    return 0;
}
</code>```

HelloWorld.py (in Debug Location of my VS2015 Solution):

def getInteger():
    print('Python function getInteger() called')
    c = 100*2
    return c
```

答:
Well, I believe some instructions is lacking in your code, like Py_Initialize. I also would use PyImport_ImportModule instead of PyImport_Import. See this sequence that you could be trying:

```<code>int main(int argc, char *argv[])
{
    Py_SetPythonHome(L"path/to/python/folder");
    Py_Initialize();
    //PySys_SetArgv(argc, argv); //optional, argv must be wchar_t
    PyObject *pFunc, *pValue;

    pModule = PyImport_ImportModule("HelloWorld");

    if (pModule)
    {
        pFunc = PyObject_GetAttrString(pModule, "getInteger");
        if (pFunc && PyCallable_Check(pFunc))
        {
            pValue = PyObject_CallObject(pFunc, NULL);
            printf_s("C: getInteger() = %ld\n", PyLong_AsLong(pValue));
            Py_XDECREF(pValue);
        }
        else
        {
            printf("ERROR: function getInteger()\n");
        }
        Py_XDECREF(pFunc);
    }
    else
    {
        printf_s("ERROR: Module not imported\n");
    }

    Py_XDECREF(pModule);

    Py_Finalize();
    return 0;
}
</code>```

If still not working, try adding this after PyInitialize:

```<code>PyRun_SimpleString(
    "import os, sys \n"
    "sys.path.append(os.getcwd()) \n"
);
</code>```

Also after PyInitialize, you can check if it's initialized with Py_IsInitialized.

Body:
I am trying a really basic "hello world" program, which should embedd a python script in my C++ console application, but it fails at pModule = PyImport_Import(pName); with an unspecified exception "Access violation reading location ..."

I was already able to run PyRun_SimpleFile() for a python script without definitions and returns, but for my future application I need a python method with returns, so PyRun_SimpleFile() is not an option.

My code, based on this Introduction is:

main.cpp

#include "stdafx.h"
#include <stdlib.h>
#include <Python.h>

int main(int argc, char *argv[])
{
    PyObject *pName, *pModule;
    PyObject *pFunc, *pValue;

    pName = PyUnicode_FromString("HelloWorld");
    pModule = PyImport_Import(pName);
    Py_XDECREF(pName);

    if (pModule)
    {
        pFunc = PyObject_GetAttrString(pModule, "getInteger");
        if (pFunc && PyCallable_Check(pFunc))
        {
            pValue = PyObject_CallObject(pFunc, NULL);
            printf_s("C: getInteger() = %ld\n", PyLong_AsLong(pValue));
            Py_XDECREF(pValue);
        }
        else
        {
            printf("ERROR: function getInteger()\n");
        }
        Py_XDECREF(pFunc);
    }
    else
    {
        printf_s("ERROR: Module not imported\n");
    }

    Py_XDECREF(pModule);

    Py_Finalize();
    return 0;
}

HelloWorld.py (in Debug Location of my VS2015 Solution):

def getInteger():
    print('Python function getInteger() called')
    c = 100*2
    return c

Body:
Well, I believe some instructions is lacking in your code, like Py_Initialize. I also would use PyImport_ImportModule instead of PyImport_Import. See this sequence that you could be trying:

int main(int argc, char *argv[])
{
    Py_SetPythonHome(L"path/to/python/folder");
    Py_Initialize();
    //PySys_SetArgv(argc, argv); //optional, argv must be wchar_t
    PyObject *pFunc, *pValue;

    pModule = PyImport_ImportModule("HelloWorld");

    if (pModule)
    {
        pFunc = PyObject_GetAttrString(pModule, "getInteger");
        if (pFunc && PyCallable_Check(pFunc))
        {
            pValue = PyObject_CallObject(pFunc, NULL);
            printf_s("C: getInteger() = %ld\n", PyLong_AsLong(pValue));
            Py_XDECREF(pValue);
        }
        else
        {
            printf("ERROR: function getInteger()\n");
        }
        Py_XDECREF(pFunc);
    }
    else
    {
        printf_s("ERROR: Module not imported\n");
    }

    Py_XDECREF(pModule);

    Py_Finalize();
    return 0;
}

If still not working, try adding this after PyInitialize:

PyRun_SimpleString(
    "import os, sys \n"
    "sys.path.append(os.getcwd()) \n"
);

Also after PyInitialize, you can check if it's initialized with Py_IsInitialized.