text:
Q: SpriteKit detecting multiple collision instead of once ( Swift 3) There are 3 SKSpriteNode in my SKScene Class. One of them is player and the other ones are gold and unvisible finish object such as when player touch it, game is finished. My problem is that when player collide the gold, his gold budget should increase just 50 gold. However, Xcode detect multiple collision and gold budget increasing multiple times. 50-60 collision is detected instead of one collision. I researched how to solve this problem. I found that I should use Bool, I tried to set bool but it didn't solve my problem. Is there anyone can help me about how to detect just one collision? Here is the my GameScene class codes :
import SpriteKit
import GameplayKit

class level3: SKScene, SKPhysicsContactDelegate {

    let playerFileName = "player"
    let starFileName = "50Gold"
    let goalFileName = "goal"
    let playerCategory   : UInt32 = 0x1 << 1
    let goalCategory : UInt32 = 0x1 << 2
    let starCategory : UInt32 = 0x1 << 3

    override func didMove(to view: SKView) {
        super.didMove(to: view)
        physicsWorld.contactDelegate = self

        let goal = childNode(withName: goalFileName) as! SKSpriteNode
        let player = childNode(withName: playerFileName) as! SKSpriteNode
        let star = childNode(withName: starFileName) as! SKSpriteNode

        player.physicsBody!.categoryBitMask = playerCategory
        goal.physicsBody!.categoryBitMask = goalCategory

        star.physicsBody?.collisionBitMask = 1
        player.physicsBody?.collisionBitMask = 1
        goal.physicsBody?.collisionBitMask = 1
        goal.physicsBody?.isDynamic = true

        goal.physicsBody!.contactTestBitMask = playerCategory

        player.physicsBody?.isDynamic = true
        star.physicsBody?.isDynamic = true
        player.physicsBody?.contactTestBitMask = starCategory

        star.physicsBody?.categoryBitMask = starCategory

        func didBegin(_ contact: SKPhysicsContact) {

            // 1
            var firstBody: SKPhysicsBody
            var secondBody: SKPhysicsBody
            // 2
            if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
                firstBody = contact.bodyA
                secondBody = contact.bodyB
            } else {
                firstBody = contact.bodyB
                secondBody = contact.bodyA
            }

            if firstBody.categoryBitMask == playerCategory && secondBody.categoryBitMask == goalCategory {

                contact.bodyB.node?.removeFromParent()

            }

            if firstBody.categoryBitMask == playerCategory && secondBody.categoryBitMask == starCategory {

                PlaySceneViewController.instance.gold += 50
                print(PlaySceneViewController.instance.gold)

                contact.bodyB.node?.removeFromParent()

            }

        }
    }
}

A: Yep - this happens. The way to handle it (you can't get sprite-kit to NOT call didBegin multiple times in some circumstances) is to make sure that your contact code accommodates this and that handling the contract multiple times does not cause a problem (such as adding to the score multiple times, removing multiple lives, trying to access a node or physicsBody that has been removed etc).
For more detail and possible solutions, see this answer : https://stackoverflow.com/a/44384390/1430420


text:
Q: mvc forms authentication landing page I have an MVC website that uses Forms Authentication.
I am attempting to add a default landing page to my site ( landing.html ) that each user hitting
http://mywebsite.com for example will be redirected to.
I tried setting the default document in the web.config, but I always get redirected to the Account/Login page.
I do not want to change the login url because that will make the user's whose session has expired to go to the landing page, which is not what I want.
Any help would be appreciated.
Thanks

A: Update your "default" route.  MVC projects have the following route defined in the RouteConfig class and is called in the Global.asax during application startup.
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

Just replace "Home" and "Index" with the controller and method you want to use as your default landing page.
Also be sure that if the controller has the [Authorize] attribute added to it then you need to add the [AllowAnonymous] attribute to the method you want to use.

redpajama_set_name: RedPajamaStackExchange


text:
Q: decomposing a measure into relative atom and atomless parts Let $(X,\mathcal{X},\mu)$ be a standard probability space. A measure $\mu$ is atomic if $\mu$ is supported on at most countable many atoms, and is atomless if $\mu$ has no atom (a point x is an atom if $\mu(\{x\})>0$).
Now let $(X,\mathcal{X},\mu)$ be an extension of $(Y,\mathcal{Y},\nu)$ and $\mu=\int_{Y}\mu_{y}d\nu(y)$ be the disintegration of $\mu$ with respect of $\nu$. Then for each $\mu_{y}$, there is a unique way to write $\mu_{y}=\mu_{y,c}+\mu_{y,d}$, where $\mu_{y,c}$ is an atomless and $\mu_{y,d}$ is an atomic measure on  $(X,\mathcal{X})$.
Question: let $\mu_{c}=\int_{Y}\mu_{y,c}d\nu(y)$ and $\mu_{d}=\int_{Y}\mu_{y,d}d\nu(y)$. Is the decomposition $\mu=\mu_{c}+\mu_{d}$ well defined? i.e. Is $A$ measurable for $\mu_{c}$ and $\mu_{d}$ for all $A\in\mathcal{X}$?

A: It is generally true that if $(X,\mathcal{X})$ is a measurable space,  $(Y,\mathcal{Y})$ a standard Borel space, and $\kappa:X\to\mathcal{P}(X)$ a transition probability, then the measure-valued function that maps $x$ to the atomic part of $\kappa(x)$ is measurable. The rest is a red herring.
With the usual $\sigma$-algebra on $\mathcal{P}(X)$ (the space of probability measures on $X$) generated by evaluation of measurable sets, the function $j:\mathcal{P}(X)\times X\to [0,1]$ given by $j(\mu,x)=\mu\big(\{x\}\big)$ is measurable. You can find the details in Appendix A of "Fundamentals of Nonparametric Bayesian Inference" (2017) by Ghosal and van der Vaart. Let $C\subseteq\mathcal{P}(X)\times X$ be the set on which $j$ is strictly positive. Let $g_\mu$ be the $\mu$-section of $C$. By a standard generalization of Fubini's theorem for transition probabilities, the function $\mu\mapsto \int g_\mu~\mathrm d\mu$ is measurable and so is the function $\mu\mapsto \int_A g_\mu~\mathrm d\mu$, which gives you the desired measurability.
For another approach, look at Theorem 2.12 of

Dubins, Lester, and David Freedman. "Measurable sets of measures."
  Pacific Journal of Mathematics 14.4 (1964): 1211-1222.

A: This fact is one of the consequences of Rokhlin's theory of Lebesgue probability spaces (also known as standard probability spaces, or Lebesgue–Rokhlin probability spaces), see the exceptionally well written Wikipedia article Standard probability space and the references therein or the 1952 English translation of Rokhlin's original paper (MR22591 and MR30584). Section 4.1 of Rokhlin's paper (pp.40-43 of the English tranlation) explicitly contains the statement you are asking about. Alas, this theory is virtually unknown in the probabilistic community.


text:
Q: Converting Kinect depth to png (python) I try to verify a segmenting algorithm and therefore i need some good data. I want to use the NYU Depth V2 dataset (http://cs.nyu.edu/~silberman/datasets/nyu_depth_v2.html). Now i want to create some pcd-data, with the point-cloud-library png2pcd method. But I need a color- and a depth-image. The colored one is no problem, but the depth is saved as float in meter. So basically values like these:
[[ 2.75201321  2.75206947  2.75221062 ...
Is there a possibility to save those values in a png-file, without scaling them in python?

A: No. It is not possible to store floating point values in a PNG. The highest resolution data you can store in a PNG is a 16-bit unsigned integer per sample, in the range 0..65535.
If you want to store floating point distances you need to look to:

*

*TIFF, which can store 32 and 64-bit floats, or

*PFM which can store 32-bit floats, or

*OpenEXR which can store 32-bit floats

A: If you are asking about extracting NYUv2 subset of 1449 labeled dataset, the following conversion will work. I am not sure for raw depth values since I am also having similar issue but my depth value ranges from 0-2047. Do you know some way to save this in .png format?
    for i, (image, depth) in enumerate(zip(f['images'], f['depths'])):
    print("SHAPE::", np.shape(image), np.shape(depth), np.max(depth),np.min(depth))
    ra_image = image.transpose(2, 1, 0)
    ra_depth = depth.transpose(1, 0)
    re_depth = (ra_depth/np.max(ra_depth))*255.0
    print("AFTER--", np.shape(image), np.shape(depth), np.max(re_depth), np.min(re_depth))
    image_pil = Image.fromarray(np.uint8(ra_image))
    depth_pil = Image.fromarray(np.uint8(re_depth))
    image_name = os.path.join("data", "nyu_datasets", "%05d.jpg" % (i))
    # image_pil.save(image_name)
    depth_name = os.path.join("data", "nyu_datasets", "%05d.png" % (i))
    # depth_pil.save(depth_name)

A: Yes. In OpenCV python:
depthMap = numpy.array([your depth value array])
cv2.imwrite('xxx.png', depthMap)

A: Yes, this is possible! The PNG-Format is able to save 16 Bit per pixel for One-Channel pictures. You can save the depth information in meters with integer.
depth_image_as_array = np.assaray(depth_image, dtype=float16)
depth_image_as_array = depth_image_as_array * 1000
depth_image = Image.fromarray(depth_image_as_array)
depth_image.save("depth_image.png")


text:
Q: how to speed up a 'unique' dataframe search I have a dataframe which is has dimension of 2377426 rows by 2 columns, which looks something like this:
                   Name                                            Seq
428293 ENSE00001892940:ENSE00001929862 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
431857 ENSE00001892940:ENSE00001883352 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGGAAGTAAATGAGCTGATGGAAGAGC
432253 ENSE00001892940:ENSE00003623668 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGGAAGTAAATGAGCTGATGGAAGAGC
436213 ENSE00001892940:ENSE00003534967 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGGAAGTAAATGAGCTGATGGAAGAGC
429778 ENSE00001892940:ENSE00002409454 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAGCTGGGAACCTTTGCTCAAAGCTCC
431263 ENSE00001892940:ENSE00001834214 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAGCTGGGAACCTTTGCTCAAAGCTCC

All the value in the first column (Name) are unique but there are many duplicates in the column 'Seq'.
I want a data.frame which only contains unique sequences and a name. I have tried unique but this is too slow. I have also tried ordering the database and using the following code:
dat_sorted = data[order(data$Seq),]
    m = dat_sorted[1,]
    x =1;for(i in 1:length(dat_sorted[,1])){if(dat_sorted[i,2]!=m[x,2]){x=x+1;m[x,]=dat_sorted[i,]}}

Again this is too slow!
Is there a faster way to find unique value in one column of a dataframe?

A: data[!duplicated(data$Seq), ]

should do the trick.

A: library(dplyr)
data %>% distinct

Should be worth for it, especially if your data is too big to your machine.

A: For the fastest, you can try:
data[!kit::fduplicated(data$Seq), ]

here are some benchmark taken directly from the documentation:
x = sample(c(1:10,NA_integer_),1e8,TRUE) # 382 Mb
microbenchmark::microbenchmark(
  duplicated(x),
  fduplicated(x),
  times = 5L
)
# Unit: seconds
#           expr  min   lq  mean  median   uq   max neval
# duplicated(x)  2.21 2.21  2.48    2.21 2.22  3.55     5
# fduplicated(x) 0.38 0.39  0.45    0.48 0.49  0.50     5

kit also has a funique function.


text:
Q: Can I adjust the baseline in an NSAttributedString without increasing the line height? In the San Francisco font, brackets are a bit low if they surround numbers. An example from the app I'm making, using an NSAttributedString:

I'd like to increase the baseline for the brackets by a pixel or two, but when I do that using the NSBaselineOffsetAttributeName attribute, the line height is increased by two pixels as well. The text is inside a UITextView, and I really wouldn't like the line height to change. Is there anything I can do?

A: A possible way to do it is to force the maximum line height with NSParagraphAttributeName.
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setMaximumLineHeight:maxHeightWanted];

NSDictionary *parenthesisAttributes = @{NSParagraphStyleAttributeName:style,
                                        NSBaselineOffsetAttributeName:@(baselineWanted),
                                        NSFontAttributeName:sameFontWithBiggerPointSize};


text:
Q: Two circles and their distance having quite the trouble with my homework this day. Heres the Exercise text:

(Two circles and their distance) Write a programthat draws two pilled circles with radius 15 pixels, centered at random location, with a line connecting the two circles. The distance between the two centers is displayed on the line. Whenever you resize the frame, the circles are redisplayed in new random locations.

Okay, so the code i have at this moment is:
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;

 public class Exercise13_29 extends JFrame {

public Exercise13_29() {

}

public static void main(String[] args) {
    Exercise13_29 frame = new Exercise13_29();
    frame.setSize(200, 200);
    frame.setTitle("Exercise13_29");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

class Circles extends JPanel {

}

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
 }
}

I know this isn't much at all but I'm really stuck here.
I dont even know if i should use drawOval or if something else is more appropriate.
I also can't seem to find out what code is used to make the circles appear randomly when the frame is resized.
Please help me out here.

A: There's a couple of smaller problems that you need to solve first.

*

*Getting a random position. How do I generate random integers within a specific range in Java?

*Finding the distance between 2 points. Calculating the distance between two points

*Drawing circles centered at a point http://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html#drawOval(int,%20int,%20int,%20int) should help

*Drawing a line between 2 points http://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html#drawLine(int,%20int,%20int,%20int)
After you've solved each of these individually, putting them together shouldn't be too difficult.

A: To relocate on window resize, add an event listener on resize events on the frame.


text:
Q: How do I find the volume of this sliced cylinder? This is hard to explain but I'll do my best.  I hope I'm clear.
Imagine you have a donut.  You want to find the volume of it and the method you want to use is to imagine slicing one side of that donut and opening it out into a cylinder.  Only, it's not exactly a cylinder as it has two pointed ends: one side of the cylinder has the length of the inner circumference of the donut, the other side has the length of the outer circumference.
The 'middle part' is a simple cylinder. I want to find the volume of each end part.
There's an easy trick to it, but that's not the solution I'm looking for; the easy trick being putting the two end parts together to make a smaller cylinder.
But, how I want to do this is to find the volume of one of these pointy cylindrical endparts with an integral.  However, I can't seem to hit the right answer.
Let's say my stretched out donut has a left side of length
$2\pi(R-r)$
and a right side of length
$2\pi(R+r)$ and a radius of $r$.  Let's say I slice the top and bottom pointed end parts off.  I now have the middle part, a cylinder with a radius of $r$ and a height of $2\pi(R-r)$ and two pointed endparts.  Each endpart has a radius of $r$, and a height of $2\pi r$.
If I cut an endpart into triangle wedge-shaped cross sections, each wedge will have a length of $2\sqrt{r^2-y^2}$, a height of $2\pi\sqrt{r^2-y^2}$ and a depth of $dy$.  So the volume of each wedge is $2\pi(r^2-y^2)dy$
If I integrate this with limits $-r$ and $r$ I get
$2\pi\int_{-r}^r (r^2-y^2)dy = 2\pi (4r^3/3)$
Assuming that's right, I can double that and add it to the volume of my cylinder to get the donut volume.  So:
$4\pi (\frac{4r^3}{3}) + 2\pi^2r^2(R-r) = \frac{16\pi r^3}{3} + 2\pi^2 r^2(R-r)$
The volume of the donut is actually $2\pi^2 r^2R$ (using the solid of revolution approach) so looks like I picked up some extra dough somewhere... $16\pi \frac{r^3}{3} - 2\pi^2 r^3$ cubic units of extra dough to be precise.
Is my arithmetic wrong?  Is my method wrong?  Can you spot what I messed up?
Sketch:

A: @Brian M. Scott.  Ok, your info gave me what I needed to understand.  I didn't understand why you said I didn't need to calculate h, so I went ahead and did the calculation with h and, after too much bad arithmetic, found the answer.
So the cross-sections are trapezoids, not triangles.  Thinking that they might have been triangles before now seems ridiculous.
So the lengths of the sides of the trapezoids are $\pi(r-x)$ and $\pi(r+x)$ and the bottom is $2x$.  The area of the trapezoid is then $2\pi rx$.  The volume of the trapezoidal wedge is $2\pi rx dy$.  The sum of the wedges is the integral $2\pi r\int_{-r}^{r} x dy$, where x is $\sqrt{r^2-y^2}$.  The answer to that is $\pi^2r^3$.
Two of those plus the volume of the cylinder is:
$2\pi^2r^3 + \pi r^2(2\pi(R-r)) = 2\pi^2r^2R$
Which is the volume of the donut.  Thanks for your help everyone!

A: When you slice the endcaps in the direction that you've chosen, you get trapezoidal cross-sections, not triangular ones: the triangle in your illustration should be cut off vertically at the lefthand end, because the cylinder wraps around. The mean height of each of the trapezoidal cross-sections is the mean height of the endcap, which is $\pi r$, and the depth is $2\sqrt{r^2-y^2}$, so the volume is $$4\pi r\int_0^r\sqrt{r^2-y^2}dy\;.$$ There's no need to do the trig substitution, since the integral clearly gives the area of a quarter-circle of radius $r$, or $\pi r^2/4$, and the volume of the endcap is therefore $\pi^2 r^3$. Two of them give you exactly what you need: $$2\pi^2 r^2(R-r)+2\pi^2 r^3=2\pi^2 r^2 R\;.$$


text:
Q: Error deleting file in IIS I'm getting this error while deleting files from archive folder. I'm trying to delete the archived folders/files created by IIS Media Services using Expression Encoder 4 Pro SP2.
When I delete these file by C# code or manually I'm getting file is open in IIS Worker Process.
I tried to move this file and then delete it, set the file length to 0 using FileStream's SetLength function, but no success.
I tried THIS but it needs restart and I can not restart my machine. Restart my machine will stop my other smooth streaming videos.
My machine is Azure Virtual Machine and has limited storage. At present there are 0 bytes free and I can not start my encoding.
Can you please tell me how can I solve this problem?

A: Thanks Silvermind.
Finally I solved it. But, unfortunately I restarted my virtual machine before this solution.
IIS Worker Process was locking the files, which I wanted to delete. To delete these files I stopped the IIS media services publish-points from IIS and then tried to delete files and it worked!!! for me.

A: I am also having the same issue just restarted website and everything goes well, now I can do from what i am prevented to.

A: You Need not to restart your website. there is a simple solution. find the below image.

You have to click the stop site. still its not working, click show all applications and click on stop all.

A: For .Net Core applications you need to Stop corresponding Application Pool in IIS


text:
Q: Call contextMenuConfigurationForRowAt on Click instead of Long Press I took my lead from this tutorial: https://kylebashour.com/posts/context-menu-guide
I thought I had everything, yet when I click on the row, nothing happens
UPDATE: Thanks a comment I learned that contextMenuConfigurationForRowAt is called on a long press. Is there a way to call this on a click? I wanted to give users several options for contacting the people listed. But buttons in UITableViewCell doesn't seem to work, so a context menu is the best I can think of, but a long press isn't obvious for interacting with this table view.
import UIKit

class PeerSupportVC: UIViewController {

@IBOutlet weak var peerSupportTableView: UITableView!
var supportArray: NSArray = [];
fileprivate var configuration = Configuration.sharedInstance;

override func viewDidLoad() {
    super.viewDidLoad()
    self.peerSupportTableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    self.peerSupportTableView.delegate = self;
    self.peerSupportTableView.dataSource = self;
    self.peerSupportTableView.rowHeight = 200.0
    getPeerSupport();

}

func getPeerSupport(){

    self.supportArray = ["One","Two","Three"]
    DispatchQueue.main.async(execute: {
        self.peerSupportTableView.reloadData()
    });
}

}

extension PeerSupportVC: UITableViewDelegate {

func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
        let item = self.supportArray[indexPath.row]

        return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { suggestedActions in

            let phoneAction = UIAction(title: "Phone Call", image: UIImage(systemName: "person.fill")) { (action) in
                DispatchQueue.main.async(execute: {
                    print("Wants to Phone Call");
                });

            }

            let textAction = UIAction(title: "Text Messsage", image: UIImage(systemName: "person.badge.plus")) { (action) in

                DispatchQueue.main.async(execute: {
                    print("Wants to Text Message");
                });
            }

            return UIMenu(title: "Contact Options", children: [phoneAction, textAction])
        }
    }

}

extension PeerSupportVC: UITableViewDataSource{

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    print("Count of Support Array:",self.supportArray.count);
    return self.supportArray.count;
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath);
    for viewToRemove in cell.subviews {
        viewToRemove.removeFromSuperview();
    }
    let width = self.peerSupportTableView.frame.width;

    if let result = self.supportArray[indexPath.row] as? String{
        print(result);

        let NameLabel = UILabel(frame: CGRect(x: 180, y: 0, width: width-155, height: 30));
        NameLabel.textColor = .black;
        NameLabel.text = " "+(result);
        NameLabel.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight(rawValue: 400));
        NameLabel.adjustsFontSizeToFitWidth = true;
        cell.addSubview(NameLabel);

    }

    return cell;
}

}

I dumbed the code down to share, but this lesser version still doesn't work.
What I want to happen is a menu to pop up on the line that was selected and give the user options on how to contact the person they selected. Any help on displaying the menu would be greatly appreciated.

A: For reference, here's your code, modified to use a reusable cell:
// simple cell class, based on your code
class PeerCell: UITableViewCell {

    let nameLabel = UILabel()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    func commonInit() {
        nameLabel.translatesAutoresizingMaskIntoConstraints = false
        nameLabel.font = .systemFont(ofSize: 12, weight: UIFont.Weight(rawValue: 400))
        contentView.addSubview(nameLabel)
        let g = contentView.layoutMarginsGuide
        NSLayoutConstraint.activate([
            nameLabel.topAnchor.constraint(equalTo: g.topAnchor),
            nameLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 180.0),
            nameLabel.trailingAnchor.constraint(equalTo: g.trailingAnchor),
            nameLabel.heightAnchor.constraint(equalToConstant: 30.0),
        ])
    }

}

class PeerSupportVC: UIViewController {

    @IBOutlet var peerSupportTableView: UITableView!
    var supportArray: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        // register our custom cell
        self.peerSupportTableView.register(PeerCell.self, forCellReuseIdentifier: "Cell")
        self.peerSupportTableView.delegate = self;
        self.peerSupportTableView.dataSource = self;
        self.peerSupportTableView.rowHeight = 200.0
        getPeerSupport();
    }

    func getPeerSupport(){
        self.supportArray = ["One","Two","Three"]
    }

}

extension PeerSupportVC: UITableViewDelegate {

    func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
        let item = self.supportArray[indexPath.row]

        return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { suggestedActions in
            let phoneAction = UIAction(title: "Phone Call", image: UIImage(systemName: "person.fill")) { (action) in
                print("Wants to Phone Call");
            }

            let textAction = UIAction(title: "Text Messsage", image: UIImage(systemName: "person.badge.plus")) { (action) in
                print("Wants to Text Message");
            }

            return UIMenu(title: "Contact Options", children: [phoneAction, textAction])
        }
    }

}

extension PeerSupportVC: UITableViewDataSource{

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("Count of Support Array:",self.supportArray.count);
        return self.supportArray.count;
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! PeerCell

        let result = self.supportArray[indexPath.row]
        print(result)
        cell.nameLabel.text = result

        return cell;
    }

}

As I said in my comment, though, your contextMenuConfigurationForRowAt was working as-is -- just need to long-press on the cell to trigger the call.


text:
Q: Which algorithm is more efficient? Which algorithm is more efficient. Is it a or b?
a. $O(n^{2.81})$
b. $O((n^3 )/ \ln n)$
I want to solve this problem using l'Hospital's rule, $\lim(f(n)/g(n)) = \lim(f'(n)/g'(n))$
L'Hospital's Rule (1696): If $f(n)$ and $g(n)$ are both differentiable with derivatives $f'(n)$ and $g'(n)$, respectively, and if $\lim f(n) = \lim g(n) = \infty$, then $\lim \frac{f(n)}{g(n)} = \lim \frac{f'(n)}{g'(n)}$, whenever the limit on the right exists.
Example (1) $f(n) = n^3$ and $g(n) = \ln n$? $f'(n)=3n^2$ and $g'(n)=1/n$ so $\lim \frac{n^3}{\ln n}=\lim \frac{3n^2}{1/n}=\infty$. therefore, $g(n)$ is more efficient than $f(n)$.

A: $$\lim_{n\to\infty} \frac{(\frac{n^3}{\ln{n}})}{n^{2.81}}=\lim_{n\to\infty} \frac{n^{0.19}}{\ln{n}}=\lim_{n\to\infty} \frac{0.19\cdot n^{-0.81}}{n^{-1}}=\lim_{n\to\infty} 0.19\cdot n^{0.19}=\infty$$
So the more efficient algorithm is the one which is $O(n^{2.81})$ as $O(\frac{n^3}{\ln{n}})$ has an infinitely greater complexity.

A: L'Hospital's rule is for quotient of functions with limit $0$. Here all you have to do is divide and simplify :
$$\frac{n^{2.81}}{\frac{n^3}{\ln n}} = n^{2.81}\frac{\ln n}{n^3} = \frac{\ln n}{n^{0.19}} \xrightarrow[n\to\infty]{} 0$$
so $O\left(n^{2.81}\right)$ is more efficient than $O\left(\frac{n^3}{\ln n}\right)$.


text:
Q: Scala: How to design the high order function? I want to design a high order function in scala which may looks like flowing:

def process(data: Seq[Double], costFun: **): Double

costFun is a function which can be used to calculate the cost of a method, since I have serval cost functions, which may have different signatures, like:

def costGauss(data: Seq[Double], scalaShift: Boolean): Double
def costKernal(data: Seq[Double], theta: Int): Double

how should I design the process function to enable that cost functions which have different signatures can be passed to it as parameter costFun?

A: Seems that you need just Seq[Double] => Double there:
def processData(data: Seq[Double], lossFunc: Seq[Double] => Double): Double = ???

def lossGauss(data: Seq[Double], scalaShift: Boolean): Double = ???
def lossKernel(data: Seq[Double], theta: Int): Double = ???

val data: Seq[Double] = Seq(1.0, 2.0, 3.0)
processData(data, lossGauss(_, true))
processData(data, lossKernel(_, 1234))

Even better, use multiple argument lists with currying:
def processData(data: Seq[Double], lossFunc: Seq[Double] => Double): Double = ???

def lossGauss(scalaShift: Boolean)(data: Seq[Double]): Double = ???
def lossKernel(theta: Int)(data: Seq[Double]): Double = ???

val data: Seq[Double] = Seq(1.0, 2.0, 3.0)
processData(data, lossGauss(true))
processData(data, lossKernel(1234))

And by the way: don't use Floats, especially not for tiny results that take O(1) memory. Seq[Float] => Double would make some sense, but not the other way round.


text:
Q: Weird error, comparing a char to a string (p == "cancel") I'm trying to do a basic if statement and I'm getting this weird error with my string.
Error 1:

Comparison between pointer and integer ('int' and 'char *')

Error 2:

Result of comparison against a string literal is unspecified (use strncmp instead)

Here is a copy of the function is all occurs in.
int logOn(int *par)
{
    char p;
    printf("Log into student records system\nEnter password or type cancel to leave\n>");
    scanf("%s", &p);

        if(p == *PASSWORD1 | p ==  *PASSWORD2 | p ==  *PASSWORD3)
        {
            *par = 2;
        }
        else if (p = "cancel")
        {
            *par = 3;
        }
        else
        {
            printf("\nIncorrect password try again\n");
        }

    return 0;
}

The error is occurring on the else if statement line (p = "cancel").

A: There are a number of things wrong here.

*

*To compare values, use == not =.

*The logical or operator is || not |.

*char p makes room for a single character. You can't store a multi-character password in a char variable. You'll need a string.

*You can't compare strings with ==. p == *PASSWORD1 won't work. I'll leave it to you to figure out what does work. It's easy enough to search for.

A: Which function to use for comparison of strings lies in the error thrown by the compiler itself.
(look for the function in error no 2 that you posted and google for it.)


text:
Q: How to debug UnsupportedOperationException happening for Cordova-plugin-crosswalk-webview randomly We have developed a hybrid mobile application , Random crash of app is happining while it is in active state . Maybe the crash is happening due to the click event (randomly).
We are using Cordova-plugin-crosswalk-webview 2.3.0 and crosswalk lite version.
How to find the the root cause of the issue?
The following exception captured while app crash
java.lang.UnsupportedOperationException:
at org.xwalk.core.ReflectMethod.invoke (ReflectMethod.java:57)
at org.xwalk.core.XWalkView.onTouchEvent (XWalkView.java:878)
at android.view.View.dispatchTouchEvent (View.java:7791)
at android.view.ViewGroup.dispatchTransformedTouchEvent (ViewGroup.java:2316)
at android.view.ViewGroup.dispatchTouchEvent (ViewGroup.java:2013)
at android.view.ViewGroup.dispatchTransformedTouchEvent (ViewGroup.java:2322)
at android.view.ViewGroup.dispatchTouchEvent (ViewGroup.java:1985)
at android.view.ViewGroup.dispatchTransformedTouchEvent (ViewGroup.java:2322)
at android.view.ViewGroup.dispatchTouchEvent (ViewGroup.java:1985)
at android.view.ViewGroup.dispatchTransformedTouchEvent (ViewGroup.java:2322)
at android.view.ViewGroup.dispatchTouchEvent (ViewGroup.java:1985)
at android.view.ViewGroup.dispatchTransformedTouchEvent (ViewGroup.java:2322)
at android.view.ViewGroup.dispatchTouchEvent (ViewGroup.java:1985)
at android.view.ViewGroup.dispatchTransformedTouchEvent (ViewGroup.java:2322)
at android.view.ViewGroup.dispatchTouchEvent (ViewGroup.java:1985)
at android.view.ViewGroup.dispatchTransformedTouchEvent (ViewGroup.java:2322)
at android.view.ViewGroup.dispatchTouchEvent (ViewGroup.java:1985)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent (PhoneWindow.java:2145)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent (PhoneWindow.java:1577)
at android.app.Activity.dispatchTouchEvent (Activity.java:2505)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent (PhoneWindow.java:2093)
at android.view.View.dispatchPointerEvent (View.java:7982)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent (ViewRootImpl.java:4384)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess (ViewRootImpl.java:4255)
at android.view.ViewRootImpl$InputStage.deliver (ViewRootImpl.java:3801)
at android.view.ViewRootImpl$InputStage.onDeliverToNext (ViewRootImpl.java:3851)
at android.view.ViewRootImpl$InputStage.forward (ViewRootImpl.java:3820)
at android.view.ViewRootImpl$AsyncInputStage.forward (ViewRootImpl.java:3927)
at android.view.ViewRootImpl$InputStage.apply (ViewRootImpl.java:3828)
at android.view.ViewRootImpl$AsyncInputStage.apply (ViewRootImpl.java:3984)
at android.view.ViewRootImpl$InputStage.deliver (ViewRootImpl.java:3801)
at android.view.ViewRootImpl$InputStage.onDeliverToNext (ViewRootImpl.java:3851)
at android.view.ViewRootImpl$InputStage.forward (ViewRootImpl.java:3820)
at android.view.ViewRootImpl$InputStage.apply (ViewRootImpl.java:3828)
at android.view.ViewRootImpl$InputStage.deliver (ViewRootImpl.java:3801)
at android.view.ViewRootImpl.deliverInputEvent (ViewRootImpl.java:6116)
at android.view.ViewRootImpl.doProcessInputEvents (ViewRootImpl.java:6096)
at android.view.ViewRootImpl.enqueueInputEvent (ViewRootImpl.java:6050)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent (ViewRootImpl.java:6246)
at android.view.InputEventReceiver.dispatchInputEvent (InputEventReceiver.java:185)
at android.os.MessageQueue.nativePollOnce (Native Method)
at android.os.MessageQueue.next (MessageQueue.java:138)
at android.os.Looper.loop (Looper.java:150)
at android.app.ActivityThread.main (ActivityThread.java:5363)
at java.lang.reflect.Method.invokeNative (Native Method)
at java.lang.reflect.Method.invoke (Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:644)
at dalvik.system.NativeStart.main (Native Method)


text:
Q: Как подобрать просто решение для теста ниши? Подскажите плиз, хочу протестировать одну идею с минимальными трудо/финансо-затратами.
Нужен сайт с регистрацией, личным кабинетом (что-бы написать пиьсмо администратору) и возможностью пополнять баланс аккаунта.
Как / на чём это проще всего реализовать? Я фронтэндер, из cms работал только с WP, натягивал свои верстки.
Можно ли обойтись "малой кровью" ?)


text:
Q: Linear independence of iterates of a non-continuous function. Consider the function $f : x \mapsto \lfloor 100 \cos(x) \rfloor$ on the real numbers.
I would like to know whether the functions
$f_n := \underbrace{f \circ ... \circ f}_{n \text{ times }}$ (with $n \geq 1$) are linearly independent over $\Bbb R$ (in the real vector space $\Bbb R^{\Bbb R}$).

The answer to my previous question shows that if a map $f : \Bbb R \to \Bbb R$ can be extended into a holomorphic map $h : \Bbb C \to \Bbb C$ which is periodic and its image is uncountable, then the iterates of $f$ are linearly independent over $\Bbb R$.
But in my case, $f$ is not even continuous, so I can not apply the same idea. How would you proceed, then?

A: In your example (if you   study the integral part of $100\cos(x)$), the image of $\mathbb{R}$ by $f$ is a finite set, say $A_1$. Put $A_n=f_n(\mathbb{R})$. We have that $A_ {n+1}=f(A_n)$, and that $A_{n+1}\subset A_n$. As $A_1$ is a finite set, the intersection of all the $A_n$, say $A$, is also a finite not empty subset of $\mathbb{R}$, and we have that there exists $N$ such that $A_n=A$ for $n\geq N$. Now $f$ restricted to $A$ is an application from $A$ to $A$, let say this is $g_1$ and of course this is also the case for the iterates $ f_n$ restricted to $A$, say $g_n$. Now as $A$ is finite, the vector space of the functions from $A$ to $\mathbb{R}$ is finite dimensional, say of dimension $m$. Then there exist a non trivial linear combination of $g_1,\cdots, g_{m+1}$, ie $b_1g_1(y)+\cdots +b_{m+1}g_{m+1}(y)=0$ for all $y \in A$. But this show that we have $b_1f_{N+1}(x)+\cdots+b_{m+1}f_{m+1+N}(x)=0$ for all $x\in \mathbb{R}$.


text:
Q: CSS Make parent div not fit children size I have the following HTML :

    <canvas id="canvas" width="534" height="554"></canvas>

I'm setting the size of the canvas item using javascript in order to avoid scale issues in my animation... :
   $(window).resize(function() {
                RefreshCanvasSize();
                SetLayout();
            });

   function RefreshCanvasSize() {
            var ParentWidth, ParentHeight;

            ParentWidth = $(".AnimationParent").width();
            ParentHeight = $(".AnimationParent").height();

            $("#canvas").prop('width', ParentWidth);
            $("#canvas").prop('height', ParentHeight);
   }

The following code works when I'm expanding a page but not when it's shrinking. The parent div (AnimationParent) doesn't shrink.
here is the CSS for AnimationParent :
 width:100%;
 overflow:hidden;

can anyone help please ?
Regards,

A: Seems to be working fine. Can you provide a fiddle explaining the problem?
Obs.: note that as soon as you run it the first time, the canvas has a fixed size, and only resizes once the browser is resized. To make it always fit the parent, you need to call RefreshCanvasSize() on $(document).ready(...) as well.
(I would add this as a comment, but this way I can provide a snippet with the code example)

$(window).resize(function() {
  RefreshCanvasSize();
  //SetLayout();
});

function RefreshCanvasSize() {
  var ParentWidth, ParentHeight;

  ParentWidth = $(".AnimationParent").width();
  ParentHeight = $(".AnimationParent").height();

  $("#canvas").prop('width', ParentWidth);
  $("#canvas").prop('height', ParentHeight);
  console.log($("#canvas").prop('width'), $("#canvas").prop('height'))
}
canvas {
  background: red;
}
.AnimationParent {
  background: blue;
  width: 100%;
  overflow:hidden;
}

  <canvas id="canvas" width="534" height="554"></canvas>


text:
Q: __init__ not called when subcalssing dict and something else Consider the following code:
class Lockable(object):

    def __init__(self):
        self._lock = None

    def is_locked(self):
       return self._lock is None

class LockableDict(dict, Lockable):
     pass

And now:
In [2]: l = example.LockableDict(a=1, b=2, c=3)

In [3]: l.is_locked()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-3-4344e3948b9c> in <module>()
----> 1 l.is_locked()

/home/sven/utils/example.py in is_locked(self)
      8
      9     def is_locked(self):
---> 10         return self._lock is None

AttributeError: 'LockableDict' object has no attribute '_lock'

It looks as though Lockable.__init__ weren't called at all. Is that so? Why?
To make things more interesting, it turns out that it's sufficient to change the LockableDict class header like this:
class LockableDict(Lockable, dict):

to make it work. Why?

A: Your misunderstanding is clear from this comment:

I don't override __init__ in LockableDict, so it should generate an __init__ making automatic calls to base classes' __init__s, shouldn't it?

No!
First, nothing gets automatically generated; the method resolution happens at call time.
And at call time, Python won't call every base class's __init__, it will only call the first one it finds.*
This is why super exists. If you don't explicitly call super in an override, no base classes or even sibling classes will get their implementations called. And dict.__init__ doesn't call its super.
Neither does your Lockable.__init__. So, this means that reversing the order makes sure Lockable.__init__ gets called… but dict.__init__ now doesn't get called.

So, what do you actually want to do? Well, Python's MRO algorithm is designed to allow maximum flexibility for hierarchies of cooperating classes, with any non-cooperating classes thrown in at the end. So, you could do this:
class Lockable(object):

    def __init__(self):
        super().__init__() # super(Lockable, self).__init__() for 2.x
        self._lock = None

    def is_locked(self):
       return self._lock is None

class LockableDict(Lockable, dict):
     pass

Also notice that this allows you to pass initializer arguments along the chain through all your cooperating classes, and then just call the unfriendly class's __init__ with the arguments you know it needs.
In a few cases, you have to put an unfriendly class first.** In that case, you have to explicitly call around them:
class LockableDict(dict, Lockable):
    def __init__(self):
        dict.__init__(self)
        Lockable.__init__(self)

But fortunately, this doesn't come up very often.

* In standard method resolution order, which is slightly more complicated than you'd expect. The same MRO rule is applied when you call super to find the "next" class—which may be a base class, or a sibling, or even a sibling of a subclass. You may find the Wikipedia article on C3 linearization more approachable.
** Especially for built-in classes, because they're special in a few ways that aren't worth getting into here. Then again, many built-in classes don't actually do anything in their __init__, and instead do all the initialization inside the __new__ constructor.


text:
Q: How to edit logs directory and save? I have this code and can successfully load loss information. I want to edit this information and save again so later I can load with tensorboard for display, how can I achieve that?
from tensorflow.python.summary import event_accumulator as ea

acc = ea.EventAccumulator("train")
acc.Reload()

# Print tags of contained entities, use these names to retrieve entities as below
print(acc.Tags())

xy_l2_loss = [(s.step, s.value) for s in acc.Scalars('seq2seq/loss/loss')]

print(xy_l2_loss)

A: Assuming that you want to store it in a file:
import pickle
from tensorflow.python.summary import event_accumulator as ea

acc = ea.EventAccumulator("train")
acc.Reload()

# Print tags of contained entities, use these names to retrieve entities as below
print(acc.Tags())

xy_l2_loss = [(s.step, s.value) for s in acc.Scalars('seq2seq/loss/loss')]

print(xy_l2_loss)
xy_l2_loss = 'asdf'
#store data
with open('somefile.pkl', 'wb') as f:
    pickle.dump(xy_l2_loss, f)
#load data
with open('somefile.pkl', 'rb') as f:
    xy_l2_loss = pickle.load(f)


text:
Q: Rookie PHP, receiving an undefined variable error I am reading a book and going through the examples, unfortunately i keep getting an error if i leave a field empty when i submit the form. I checked the errata and there was nothing, i tried posting on the books forums but I didn't get any responses.
I believe that maybe i have to declare the variables first but that would take away from the variables being automatically generated.
Any help would be greatly appreciated, i am a rookie trying to learn php.
per request, here is the $required and $expected. Thanks!
$expected = array('name', 'email', 'comments');
$required = array('name', 'email', 'comments');

<?php
foreach ($_POST as $key => $value){
    //assign to temporary variable and strip whitespace if not an array
    $temp = is_array($value) ? $value : trim($value);

    //if empty and required, add to $missing array
    if (empty($temp) && in_array($key, $required)){
        $missing[] = $key;
    } elseif(in_array($key, $expected)){
        //otherwise, assign to a variable of the same name as $key
        ${$key} = $temp;
    }
}

<?php
include('./includes/title.inc.php');
$errors = array();
$missing = array();

//Check to see if the form has been submitted
if (isset($_POST['send'])){
    //email processing script
    $to = 'drewdin1@hotmail.com'; //use your email address
    $subject = 'Feedback from Japan Journey';

    //list expecting fields
    $expected = array('name', 'email', 'comments');

    //set required fields
    $required = array('name', 'email', 'comments');
    include('./includes/processmail.inc.php');
}
?>
<!DOCTYPE HTML>

<meta charset=utf-8">
<title>Japan Journey<?php if (isset($title)){echo "—{$title}";} ?></title>
<link href="styles/journey.css" rel="stylesheet" type="text/css" media="screen">

Japan Journey

    <?php include('./includes/menu.inc.php'); ?>

Contact Us

        <?php if ($missing || $errors){ ?>

Please fix the item(s) indicated.

        <?php } ?>

Ut enim ad minim veniam, quis nostrud exercitation consectetur adipisicing elit. Velit esse cillum dolore ullamco laboris nisi in reprehenderit in voluptate. Mollit anim id est laborum. Sunt in culpa duis aute irure dolor excepteur sint occaecat.

        <form id="feedback" method="POST" action="">

                Name:
                    <?php if ($missing && in_array('name', $missing)){ ?>
                        Please enter your name
                    <?php } ?>

                <input name="name" id="name" type="text" class="formbox"<?php
                    if ($missing || $errors){
                        echo ' value="' . htmlentities($name, ENT_COMPAT, 'UTF-8') . '" ';
                    } ?> />

                Email:
                    <?php if ($missing && in_array('email', $missing)){ ?>
                        Please enter your email address
                    <?php } ?>

                <input name="email" id="email" type="text" class="formbox"<?php
                    if ($missing || $errors){
                        echo ' value="' . htmlentities($email, ENT_COMPAT, 'UTF-8') . '" ';
                    } ?> />

                Comments:
                    <?php if ($missing && in_array('comments', $missing)){ ?>
                        Please enter your comments
                    <?php } ?>

                <textarea name="comments" id="comments" cols="60" rows="8"><?php
                    if ($missing || $errors){
                        echo htmlentities($comments, ENT_COMPAT, 'UTF-8');
                    } ?></textarea>

                <input name="send" id="send" type="submit" value="Send message">

        </form>

            <?php if ($_POST && $missing) {print_r($_POST);} ?>

    <?php include('./includes/footer.inc.php'); ?>

A: In the below line:
echo ' value="' . htmlentities($email, ENT_COMPAT, 'UTF-8') . '" ';

You are using the variable $email but you haven't actually created that variable anywhere.
Try adding this line immediately above that one:
$email = isset($_POST['email'])?$_POST['email']:'';

This is a short hand form for an if..else statement.  It checks if an email exists in the $_POST array and uses that value, otherwise it simply sets it to an empty string.  Either way, the variable is now "defined".

A: Some browsers do not submit a html field which has no value attribute and the value attribute is empty, therefore you must first check if the post variable exists.
if ($missing || $errors){
    if (isset($email))
        echo ' value="' . htmlentities($email, ENT_COMPAT, 'UTF-8') . '" ';
}

I would recommend to make sure, all html input fields have at least value="" attribute in the html code, problem solved.

A: Quite simple, the email is entry is empty in your Request, so the variable $email never gets created as you only perform the assignment if $_REQUEST[$key] is not empty.
Besides, i would strongly suggest not to create variables based on an untrusted $_REQUEST, as this could open up serious security holes. A simple example: call your form url and append something like ?subject=damn


text:
Q: How to use JSON to return array from a query? I am trying to display all of the continents but all I am getting is '[object Object]' instead of the actual continent names. How can I actually get the continent names to show?
AJAX
<script>
$(document).ready(function(){

$.get('auto.php',{act:'fetchContinent'},loadContinents ,'json');

$("select#continents").change(function(){
             $('div#display').html($("select#continents option:selected").text())});

function loadContinents(data){
          var optionStr = "";
          for (var index in data) {
              optionStr += '<option value="' + data[index] + '">' + data[index] + '</option>\n';
          }
          $("select#continents").html(optionStr);}
});

A: You get [object Object] because the array returned from the server contains objects! Since those are in the form {Continent: "thecontinent"}, you can write the option like this:
optionStr += '<option value="' + data[index].Continent + '">' + data[index].Continent + '</option>\n';

data[index] is the object {Continent: "thecontinent"}
data[index].Continent is the value of the Continent property ot that object


text:
Q: Evaluate $\sum_{k=1}^\infty k \alpha^k$ I'm struggling with the derivation of this known result. As a prerequisite, consider the following results. Suppose we have time-series data {$x_i$ for $i = 1, \dots, N$} from a stationary process having mean $\mu$ and variance $\sigma^2$ and theoretical acf $\rho(k)$. The sample mean is $\bar{X} = \sum_{i=1}^N \frac{X_i}{N}$. For correlated observations, it can be shown that the sample mean variance is not $\sigma^2/N$ but is given by:
$$
Var(\bar{X}) = \frac{\sigma^2}{N}\left[ 1 + 2 \sum_{k=1}^{N-1}\left( 1 - \frac{k}{N} \right) \rho(k) \right]
$$
I'd like to find the variance of the sample mean for a stationary AR(1) process. The book states that $Var(\bar{X})$ for AR(1) reduces to $ Var(\bar{X}) = \frac{\sigma^2}{N}\left( \frac{1+\alpha}{1-\alpha} \right)$. To show this, I start with the autocorrelation function of an AR(1) process with parameter $\alpha$ which is $\rho(k) = \alpha^{|k|}$ where $\alpha \lt 1$. So the above equation becomes
$$
Var(\bar{X}) = \frac{\sigma^2}{N}\left[ 1 + 2 \sum_{k=1}^{N-1}\left( 1 - \frac{k}{N} \right) \alpha^k \right]
$$
Then let $N \rightarrow \infty $. The complication then is ultimately in solving $\sum_{k=1}^\infty (1 - \frac{k}{N}) \alpha^{|k|}$. If I split it then:
$$
\sum_{k=1}^\infty \alpha^k = \sum_{k=0}^\infty \alpha^k - 1 = \frac{\alpha}{1-\alpha}
$$
Now I need to solve the second part which is where I get stuck. I don't know how to evaluate:
$$
\sum_{k=1}^\infty k \alpha^k
$$
Ultimately, I'd like to show that $ Var(\bar{X}) = \frac{\sigma^2}{N}\left( \frac{1+\alpha}{1-\alpha} \right)$ but I believe by solving the above sum which I'm stuck on I'll be able to show this result from the general equation for $Var(\bar{X})$ above.

A: Either take the derivative approach as Kenta S mentioned, or do the following:
$$S=\sum_{1}^{\infty} k\alpha^k  \\ \alpha S= \sum_1^{\infty} k\alpha^{k+1} = \sum_2^{\infty} (k-1)\alpha^k =\sum_{2}^{\infty} k\alpha^k -\sum_2^{\infty} \alpha^k \\ =(S-\alpha) -\frac{\alpha^2}{1-\alpha} \\ \implies S= \frac{\alpha}{1-\alpha} +\left ( \frac{\alpha}{1-\alpha} \right)^2$$

A: $$\sum_{k=1}^{\infty} k\alpha^k$$
$$=\sum_{i=1}^{\infty}\sum_{k=i}^{\infty} \alpha^k$$
$$=\sum_{i=1}^{\infty} \alpha^i \sum_{k=0}^{\infty} \alpha^k$$
$$=\sum_{i=1}^{\infty} \alpha^i \frac{1}{1-\alpha}$$
$$=\frac{1}{1-\alpha} \sum_{i=1}^{\infty} \alpha^i $$
$$=\frac{\alpha}{(1-\alpha)^2}$$

A: Comments for the save.
$$\sum_{k=1}^\infty k \alpha^k=\frac{\partial}{\partial \alpha}\alpha^2\sum_{k=0}^\infty  \alpha^{k}-\alpha \sum_{k=0}^\infty\alpha^k$$
which is
$$=\frac{\partial}{\partial \alpha}\frac{\alpha^2}{1-\alpha}-\frac{\alpha}{1-\alpha}$$
$$=(\frac{\alpha}{1-\alpha})^2+\frac{\alpha}{1-\alpha}$$

A: So I answer it this way. This answer assumes $|a| < 1$.
$$
\sum_{k=1}^\infty k a^k = \sum_{k=0}^\infty k a^k = \sum_{k=0}^\infty a \frac{d}{d a} [a^k] = a \sum_{k=0}^\infty \frac{d}{da}[a^k] = a \frac{d}{da}[\sum_{k=0}^\infty a^k] = a \frac{d}{da} [\frac{1}{1-a}] = \cdots
$$


text:
Q: USB device recognised but not usable I'm trying to use a USB flash drive that was working perfectly until some time ago, after which I have made no changes to the system that can affect this.
When I plug in my USB device and run $ lsblk && lsusb
this is the output I received.
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda      8:0    0 931.5G  0 disk
├─sda1   8:1    0   512M  0 part /boot/efi
├─sda2   8:2    0    28G  0 part /
├─sda3   8:3    0   7.9G  0 part [SWAP]
└─sda4   8:4    0 895.2G  0 part /home
sr0     11:0    1  1024M  0 rom
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 004: ID 8087:07dc Intel Corp.
Bus 001 Device 003: ID 0bda:0129 Realtek Semiconductor Corp. RTS5129 Card Reader Controller
Bus 001 Device 002: ID 1bcf:2b90 Sunplus Innovation Technology Inc.
Bus 001 Device 005: ID 0781:5581 SanDisk Corp. Ultra
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

I can note the SanDisk Corp. Ultra at Bus 001 Device 005: ID 0781:5581 in the above output.
I do not understand why it was not mounted automatically and why I am unable to mount it. Please help me out with how to mount the device. Thanks in advance :)
Edit: This is happening with all USB devices, I did try connecting an external hard disk. The same thing happened.
Edit: I'm extremely sorry that I did not provide the basic information.
I'm Using Debian 10 (Buster) with a the latest kernel i.e. 5.8.0-rc1-00001-gc1966b82e604
When I run sudo journalctl -f
Jun 20 19:24:12 pesu.pes.edu kernel: usb 1-3: new high-speed USB device number 6 using xhci_hcd
Jun 20 19:24:12 pesu.pes.edu kernel: usb 1-3: New USB device found, idVendor=0781, idProduct=5581, bcdDevice= 1.00
Jun 20 19:24:12 pesu.pes.edu kernel: usb 1-3: New USB device strings: Mfr=1, Product=2, SerialNumber=3
Jun 20 19:24:12 pesu.pes.edu kernel: usb 1-3: Product: Ultra
Jun 20 19:24:12 pesu.pes.edu kernel: usb 1-3: Manufacturer: SanDisk
Jun 20 19:24:12 pesu.pes.edu kernel: usb 1-3: SerialNumber: 4C530001161117117402
Jun 20 19:24:12 pesu.pes.edu mtp-probe[2747]: checking bus 1, device 6: "/sys/devices/pci0000:00/0000:00:14.0/usb1/1-3"
Jun 20 19:24:12 pesu.pes.edu mtp-probe[2747]: bus: 1, device: 6 was not an MTP device
Jun 20 19:24:12 pesu.pes.edu mtp-probe[2750]: checking bus 1, device 6: "/sys/devices/pci0000:00/0000:00:14.0/usb1/1-3"
Jun 20 19:24:12 pesu.pes.edu mtp-probe[2750]: bus: 1, device: 6 was not an MTP device
Jun 20 19:24:18 pesu.pes.edu kernel: usb 1-3: USB disconnect, device number 6

When I run
sudo tail -f /var/log/syslog this is the output i get.
Jun 20 19:24:12 pesu kernel: [ 1110.256157] usb 1-3: New USB device strings: Mfr=1, Product=2, SerialNumber=3
Jun 20 19:24:12 pesu kernel: [ 1110.256162] usb 1-3: Product: Ultra
Jun 20 19:24:12 pesu kernel: [ 1110.256166] usb 1-3: Manufacturer: SanDisk
Jun 20 19:24:12 pesu kernel: [ 1110.256170] usb 1-3: SerialNumber: 4C530001161117117402
Jun 20 19:24:12 pesu mtp-probe: checking bus 1, device 6: "/sys/devices/pci0000:00/0000:00:14.0/usb1/1-3"
Jun 20 19:24:12 pesu mtp-probe: bus: 1, device: 6 was not an MTP device
Jun 20 19:24:12 pesu mtp-probe: checking bus 1, device 6: "/sys/devices/pci0000:00/0000:00:14.0/usb1/1-3"
Jun 20 19:24:12 pesu mtp-probe: bus: 1, device: 6 was not an MTP device
Jun 20 19:24:18 pesu kernel: [ 1116.267124] usb 1-3: USB disconnect, device number 6

A: Your kernel needs the modules usbcore and usb_storage to recognise USB devices as USB storage devices.  This includes USB thumb drives.
According to your output in the comments above, quoting here:
$ sudo modprobe usb_storage
modprobe: FATAL: Module usb_storage not found in directory /lib/modules/5.8.0-rc1-00001-gc1966b82e604

The kernel does not have the usb_storage module/code available.
Solution 1:
Compile your kernel with usb_storage included (Y not M).
Solution 2: Fix your issues compiling your kernel modules (need more info to solve that issue, feel free to add kernel module compilation/installation errors by editing your question, or (perhaps better) open a new question since it is a different problem).


text:
Q: How can I make CNTK solve the XOR problem? I'm trying to make an implementation of a XOR in CNTK in C#. I followed the example here: https://github.com/microsoft/CNTK/blob/release/latest/Examples/TrainingCSharp/Common/LogisticRegression.cs
, but it doesn't work. After training, the neural network gives the wrong result:
For comparison, I run the same architecture using AForge and after training it gives the correct result:
CNTK result
AForge result
int iterations = 10000;
// initialize input and output values
double[][] input = new double[4][] {
    new double[] {0, 0}, new double[] {0, 1},
    new double[] {1, 0}, new double[] {1, 1}
};
double[][] output = new double[4][] {
    new double[] {0}, new double[] {1},
    new double[] {1}, new double[] {0}
};

int inputDim = 2;
int hiddenDim = 2;
int numOutputClasses = 1;
DeviceDescriptor device = DeviceDescriptor.CPUDevice;
Variable inputVariable1 = Variable.InputVariable(new int[] { inputDim }, DataType.Float);
Variable outputVariable1 = Variable.InputVariable(new int[] { hiddenDim }, DataType.Float);
Variable inputVariable2 = Variable.InputVariable(new int[] { hiddenDim }, DataType.Float);
Variable outputVariable2 = Variable.InputVariable(new int[] { numOutputClasses }, DataType.Float);

var weightParam1 = new Parameter(new int[] { hiddenDim, inputDim }, DataType.Float, 1, device, "w");
var biasParam1 = new Parameter(new int[] { hiddenDim }, DataType.Float, 0, device, "b");
var classifierOutput0 = CNTKLib.Sigmoid(CNTKLib.Times(weightParam1, inputVariable1) + biasParam1);

var weightParam2 = new Parameter(new int[] { numOutputClasses, hiddenDim }, DataType.Float, 1, device, "ww");
var biasParam2 = new Parameter(new int[] { numOutputClasses }, DataType.Float, 0, device, "bb");
var classifierOutput1 = CNTKLib.Sigmoid(CNTKLib.Times(weightParam2, classifierOutput0) + biasParam2);

//var loss = CNTKLib.CrossEntropyWithSoftmax(classifierOutput1, outputVariable2);
var loss = CNTKLib.BinaryCrossEntropy(classifierOutput1, outputVariable2);
var evalError = CNTKLib.ClassificationError(classifierOutput1, outputVariable2);

// prepare for training
CNTK.TrainingParameterScheduleDouble learningRatePerSample = new CNTK.TrainingParameterScheduleDouble(0.01, 1);
IList<Learner> parameterLearners = new List<Learner>() { Learner.SGDLearner(classifierOutput1.Parameters(), learningRatePerSample) };
var trainer = Trainer.CreateTrainer(classifierOutput1, loss, evalError, parameterLearners);

float[] inputValuesArr = new float[input.Length * input[0].Length];
for (int i = 0; i < input.Length; i++)
{
    for(int k = 0; k < input[i].Length; k++)
    {
        inputValuesArr[i * input[i].Length + k] = (float)input[i][k];
    }
}
float[] outputValuesArr = new float[output.Length * output[0].Length];
for (int i = 0; i < output.Length; i++)
{
    for (int k = 0; k < output[i].Length; k++)
    {
        outputValuesArr[i * output[i].Length + k] = (float)output[i][k];
    }
}
Value inputValues= Value.CreateBatch<float>(new int[] { inputDim }, inputValuesArr, device);
Value outputValues = Value.CreateBatch<float>(new int[] { numOutputClasses }, outputValuesArr, device);

// train the model
for (int minibatchCount = 0; minibatchCount < iterations; minibatchCount++)
{
    //TODO: sweepEnd should be set properly instead of false.
#pragma warning disable 618
    trainer.TrainMinibatch(new Dictionary<Variable, Value>() { { inputVariable1, inputValues }, { outputVariable2, outputValues } }, device);
#pragma warning restore 618
    //TestHelper.PrintTrainingProgress(trainer, minibatchCount, updatePerMinibatches);
}

var inputDataMap = new Dictionary<Variable, Value>() { { inputVariable1, inputValues } };
var outputDataMap = new Dictionary<Variable, Value>() { { classifierOutput1.Output, null } };
classifierOutput1.Evaluate(inputDataMap, outputDataMap, device);
var outputValue = outputDataMap[classifierOutput1.Output];
IList<IList<float>> actualLabelSoftMax = outputValue.GetDenseData<float>(classifierOutput1.Output);

I wrote an XOR implementation, the trained network gave the result: {0.1, 0.6, 0.6, 0.7} instead of {0, 1, 1, 0}
I hope someone can help.
Update: I found an example with CNTK for c#, it works, and its structure has such layers: (2-8-1), if you change the structure to (2-2-1), and change the activation functions to sigmoidal, it starts to produce the same result as my code. This is strange, because a neural network with the same structure (2-2-1) of the AForge library does the right result.sample CNTK C# XOR


text:
Q: grep -P no longer works. How can I rewrite my searches? It looks like the new version of OS X no longer supports grep -P and as such has made some of my scripts stop working, for example:
var1=`grep -o -P '(?<=<st:italic>).*(?=</italic>)' file.txt`

I need to capture grep's result to a variable and I need to use zero-width assertions, as well as \K:
var2=`grep -P -o '(property:)\K.*\d+(?=end)' file.txt`

Any alternatives would be greatly appreciated.

A: If you want to do the minimal amount of work, change
grep -P 'PATTERN' file.txt

to
perl -nle'print if m{PATTERN}' file.txt

and change
grep -o -P 'PATTERN' file.txt

to
perl -nle'print $& while m{PATTERN}g' file.txt

So you get:
var1=`perl -nle'print $& while m{(?<=<st:italic>).*(?=</italic>)}g' file.txt`
var2=`perl -nle'print $& while m{(property:)\K.*\d+(?=end)}g' file.txt`

In your specific case, you can achieve simpler code with extra work.
var1=`perl -nle'print for m{<st:italic>(.*)</italic>}g' file.txt`
var2=`perl -nle'print for /property:(.*\d+)end/g' file.txt`

A: use perl;
perl -ne 'print if /regex/' files ...

If you need more grep options (I see you would like -o at least) there are various pgrep implementations floating around the net, many of them in Perl.
If "almost Perl" is good enough, PCRE ships with pcregrep.

A: There is another alternative: pcregrep.
Pcregrep is a grep with Perl-compatible regular expressions.  It has the exactly same usage as grep -P. So it will be compatible with your scripts.
It can be installed with homebrew:
brew install pcre

A: How about using the '-E' option? It works fine for me,
for example, if I want to check for a php_zip, php_xml, php_gd2 extension from php -m I use:
php -m | grep -E '(zip|xml|gd2)'

A: Equivalent of the accepted answer, but without the requirement of the -P switch, which was not present on both machines I had available.
find . -type f -exec perl -nle 'print $& if m{\r\n}' {} ';' -exec perl -pi -e 's/\r\n/\n/g' {} '+'

A: This one worked for me:
    awk  -F":" '/PATTERN/' file.txt

A: If your scripts are for your use only, you can install grep from homebrew-core using brew:
brew install grep

Then it's available as ggrep (GNU grep).
it doesn't replaces the system grep (you need to put the installed grep before the system one on the PATH).
The version installed by brew includes the -P option, so you don't need to change your scripts.
If you need to use these commands with their normal names, you
can add a "gnubin" directory to your PATH from your bashrc like:
PATH="/usr/local/opt/grep/libexec/gnubin:$PATH"

You can export this line on your ~/.bashrc or ~/.zshrc to keep it for new sessions.
Please see here for a discussion of the pro-s and cons of the old --with-default-names option and it's (recent) removal.

A: Install ack and use it instead. Ack is a grep replacement written in Perl. It has full support for Perl regular expressions.

A: OS X tends to provide BSD rather than GNU tools. It does come with egrep however, which is probably all you need to perform regex searches.
example: egrep 'fo+b?r' foobarbaz.txt
A snippet from the OSX grep man page:
grep is used for simple patterns and basic regular expressions (BREs); egrep can handle extended regular expressions (EREs).

A: Another Perl solution for -P
var1=$( perl -ne 'print $1 if m#<st:italic>([^<]+)</st:italic># ' file.txt)

A: use the perl one-liner regex by passing the find output with a pipe.
I used lookbehind (get src links in html) and lookahead for "  and passed the output of curl (html) to it.
bash-3.2# curl stackoverflow.com | perl -0777 -ne '$a=1;while(m/(?<=src\=\")(.*)(?=\")/g){print "Match #".$a." "."$&\n";$a+=1;}'
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  239k  100  239k    0     0  1911k      0 --:--:-- --:--:-- --:--:-- 1919k
Match #1 //ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js
Match #2 //cdn.sstatic.net/Js/stub.en.js?v=fb6157e02696
Match #3 https://ssum-sec.casalemedia.com/usermatch?s=183712&cb=https%3A%2F%2Fengine.adzerk.net%2Fudb%2F22%2Fsync%2Fi.gif%3FpartnerId%3D1%26userId%3D
Match #4 //i.stack.imgur.com/817gJ.png" height="16" width="18" alt="" class="sponsor-tag-img">elasticsearch elasticsearch-2.0 elasticsearch sharding android linux android firebase android ios in-app-purchase android unity3d <a href="/questions/tagged/vr" class="post-tag" title="show questions tagged 'vr'" rel="tag
Match #10 http://pixel.quantserve.com/pixel/p-c1rF4kxgLUzNc.gif" alt="" class="dno
bash-3.2# date
Mon Oct 24 20:57:11 EDT 2016

A: I had this same problem with grep suddenly on a docker rebuilt, I found the solution here : https://github.com/firehol/firehol/issues/325
just replaced -oP with -oE
echo $some_var | grep -oE '\b[0-9a-f]{5,40}\b' | head -1

A: Some more options, these also set correct exit status:

*

*equivalent to grep -P PATTERN FILE :
perl -e'while(<>){if( (m!PATTERN!) ){$ok++;print}};if(!($ok)){exit 1}' FILE

*equivalent to grep -P -i PATTERN FILE :
perl -e'while(<>){if( (m!PATTERN!i) ){$ok++;print}};if(!($ok)){exit 1}' FILE

*equivalent to grep -v -P PATTERN FILE :
perl -e'while(<>){if( !(m!PATTERN!) ){$ok++;print}};if(!($ok)){exit 1}' FILE
For a more cleaner solution use this gist - implemented switches are: -A , -B , -v , -P , -i : https://gist.github.com/torson/bd6931bda0035c4884b2a8c4c64a33b2


text:
Q: Postgres Query uses Bitmap index scan on GIN indexed item. Does not GIN use B-Tree internally? From postgres docs on GIN -

Internally, a GIN index contains a B-tree index constructed over keys.

But in my use case, I see Bitmap indexes instead -
My Schema and Indexes are created as below.
CREATE TABLE customer (
    jdata jsonb NOT NULL,
    comments text NULL
);

CREATE INDEX idx_jdata ON customer USING gin (jdata jsonb_path_ops);

Say, inserted a 10K records. sample prepared data/ alternate link
explain analyze select jdata from  customer where jdata @> '{"supplier":{"id":"7f5644ca-f0d3-4f50-947b-9e3e38f7b796"}}'

Outpt -
Bitmap Heap Scan on file_set  (cost=2139.27..36722.32 rows=10744 width=18) (actual time=1.438..267.122 rows=4048 loops=1)
  Recheck Cond: (jdata @> '{"supplier": {"id": "7f5644ca-f0d3-4f50-947b-9e3e38f7b796"}}'::jsonb)
  Heap Blocks: exact=1197
  ->  Bitmap Index Scan on idx_jdata  (cost=0.00..2136.58 rows=10744 width=0) (actual time=1.214..1.214 rows=4048 loops=1)
        Index Cond: (jdata @> '{"supplier": {"id": "7f5644ca-f0d3-4f50-947b-9e3e38f7b796"}}'::jsonb)
Planning Time: 0.065 ms
Execution Time: 267.456 ms

(the query plan above is based on real output form postgres - i had to change table/column names)
Why is Bitmap index created when a GIN index is created
My Postgres DB version is 13.5.

After looking at comment from @a-horse-with-no-name  -> I tried below
SET enable_seqscan = OFF;
explain analyze
select * from pg_opclass where "oid"=10003;
SET enable_seqscan = ON;

and the output -
QUERY PLAN                                                                                |
--------------------------------------------------------------------------------------------------------------------------------+
Index Scan using pg_opclass_oid_index on pg_opclass  (cost=0.14..8.16 rows=1 width=93) (actual time=0.015..0.016 rows=1 loops=1)|
  Index Cond: (oid = '10003'::oid)                                                                                |
Planning Time: 0.060 ms                                                                                |
Execution Time: 0.027 ms                                                                                |

I see difference -
"Bitmap Index Scan on idx_jdata" vs "Index Scan using pg_opclass_oid_index on pg_opclass"
Does this mean anything important. Can some one add more details about the using vs on and the on pg_opsclass.

A: A GIN index can contain the same tuple pointer multiple times, listed under different tokens which the field is broken down into.  Those need to be de-duplicated to make sure it doesn't return duplicate rows where it should not, and the way GIN chooses to do this is by forcing it go through a bitmap index scan; which inherently deduplicates the pointers. It is not the index which is the bitmap, it is the scan which uses bitmaps. Any index can be used in a bitmap index scan, but GIN indexes can only be used in bitmap scans, due to the need to deduplicate.


text:
Q: How to access hdfs by URI consisting of H/A namenodes in Spark which is outer hadoop cluster? Now I have some Spark applications which store output to HDFS.
Since our hadoop cluster is consisting of namenode H/A, and spark cluster is outside of hadoop cluster (I know it is something bad) I need to specify HDFS URI to application so that it can access HDFS.
But it doesn't recognize name service so I can only give one of namenode's URI, and if it fails, modify configuration file and try again.
Accessing Zookeeper for revealing active seems to very annoying, so I'd like to avoid.
Could you suggest any alternatives?

A: If you want to make a H/A HDFS cluster as your default config (mostly the case) that applies to every application started through spark-submit or spark-shell. you could write the cluster information into spark-defaults.conf.
sudo vim $SPARK_HOME/conf/spark-defaults.conf

And add the following lines. assuming your HDFS cluster name is hdfs-k8s
spark.hadoop.dfs.nameservices   hdfs-k8s
spark.hadoop.dfs.ha.namenodes.hdfs-k8s  nn0,nn1
spark.hadoop.dfs.namenode.rpc-address.hdfs-k8s.nn0 192.168.23.55:8020
spark.hadoop.dfs.namenode.rpc-address.hdfs-k8s.nn1 192.168.23.56:8020
spark.hadoop.dfs.client.failover.proxy.provider.hdfs-k8s    org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider

It should work when your next application launched.
sc.addPyFile('hdfs://hdfs-k8s/user/root/env.zip')

A: Suppose your nameservice is 'hadooptest', then set the hadoop configurations like below.
You can get these information from hdfs-site.xml file of remote HA enabled HDFS.
sc.hadoopConfiguration.set("dfs.nameservices", "hadooptest")
sc.hadoopConfiguration.set("dfs.client.failover.proxy.provider.hadooptest", "org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider")
sc.hadoopConfiguration.set("dfs.ha.namenodes.hadooptest", "nn1,nn2")
sc.hadoopConfiguration.set("dfs.namenode.rpc-address.hadooptest.nn1", "10.10.14.81:8020")
sc.hadoopConfiguration.set("dfs.namenode.rpc-address.hadooptest.nn2", "10.10.14.82:8020")

After this, you can use the URL with 'hadooptest' like below.
test.write.orc("hdfs://hadooptest/tmp/test/r1")

check here for more information.

A: For kerberos enabled clusters, you can access HDFS using following properties. More information here. These information you can get from remove HA hdfs-site.xml file.
spark.sparkContext.hadoopConfiguration.set("dfs.nameservices", "testnameservice")
spark.sparkContext.hadoopConfiguration.set("dfs.client.failover.proxy.provider.testnameservice", "org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider")
spark.sparkContext.hadoopConfiguration.set("dfs.ha.namenodes.testnameservice", "nn1,nn2")
spark.sparkContext.hadoopConfiguration.set("dfs.namenode.rpc-address.testnameservice.nn1", "namenode1_hostname:8020")
spark.sparkContext.hadoopConfiguration.set("dfs.namenode.rpc-address.testnameservice.nn2", "namenode2_hostname:8020")
spark.read.csv("hdfs://testnameservice/path/to/hdfs/sample.csv")

If you have also set spark to access kerberos token while launching with this property spark.kerberos.access.hadoopFileSystems for spark > 3.0 or spark.kerberos.access.namenodes for Spark < 3.0 as mentioned here. Unfortunately, for this, it requires only active namenode configuration and you have to poll namenode service or namenode at http://namenode_service:50070/jmx?qry=Hadoop:service=NameNode,name=NameNodeStatus and retrieve active namenode.

A: *

*Copy hadoop configuration dir to your spark cluster

*Point spark to this dir by setting HADOOP_CONF_DIR in spark-env.sh

e.g.
echo "HADOOP_CONF_DIR=\"/opt/hadoop/etc/hadoop\"" > spark-env.sh

A: I came across the similar type of issue. In my case, i was having the list of hosts of HA enabled environment, but no information above the "Active" node.
To solve the problem, i used the webhdfs call to get the status of each node, this is the webhdfs call that i used in my code -
curl 'http://[hdfsHost]:50070/jmx?qry=Hadoop:service=NameNode,name=NameNodeStatus'
I make above call with different HDFS hosts. It return "state" of each node in json output, like this
 {
  "..." : [ {
    "name" : "Hadoop:service=NameNode,name=NameNodeStatus",
     "modelerType" : "org.apache.hadoop.hdfs.server.namenode.NameNode",
     "State" : "active",
    .......
  } ]
}

if node is stand by you will get "State" : "standby"
Once you get the JSON, you can parse the json and get the state value.


text:
Q: How to read csv data I have a CSV file that needs to be read into R, transposed (swapping rows for columns) and then processed.
Here is the form of the file (not that columns actually extend to 2014):
Year,1970,1971,1972
Variable one,1,2,3
Variable two,11,22,33
Variable three,111,222,333

When I read it, the years are prefixed with 'X'
> rc <- read.csv("file.csv")
> rc
            Year X1970 X1971 X1972
1   Variable one     1     2     3
2   Variable two    11    22    33
3 Variable three   111   222   333

and when I transpose the data everything is treated as a string.
> t(rc)
      [,1]           [,2]           [,3]
Year  "Variable one" "Variable two" "Variable three"
X1970 "  1"          " 11"          "111"
X1971 "  2"          " 22"          "222"
X1972 "  3"          " 33"          "333"

If I delete the names for the rows in the csv file, the dates are still prefixed by X but the transpose does not change the data to strings.
So how do I do this properly so that the years are numeric and transposing does not create strings.

A: Just add check.names = FALSE with your read.csv statement (but it's not a great idea since you'll end up with syntactically invalid names in this case):
X <- read.csv(text = "Year,1970,1971,1972
 Variable one,1,2,3
 Variable two,11,22,33
 Variable three,111,222,333", check.names = FALSE)
X
#             Year 1970 1971 1972
# 1   Variable one    1    2    3
# 2   Variable two   11   22   33
# 3 Variable three  111  222  333

Regarding transposing your data, drop the string values first, and reintroduce them as the column names later:
tX <- t(X[-1])
colnames(tX) <- X[[1]]
tX
#       Variable one  Variable two  Variable three
# 1970             1            11             111
# 1971             2            22             222
# 1972             3            33             333


text:
Q: How to read back what I just wrote to a file? I've been trying to write a program to open a file in both read and write mode:
#include <fstream>
#include <iostream>
using namespace std;
int main(){
    fstream obj;
    obj.open("hello.txt",ios::in|ios::out);
    if (!obj){
        cout << "File not opened" <<endl;
        return 1;
    }
    obj << "Hi How are you" ;
    char c;
    while (!obj.eof()){
        obj.get(c);
        cout << c;
    }
    obj.close();
    return 0;
}

When I compile this program on Visual Studio Code on Windows, though the text "Hi how are you" is printed in the file, the contents of the file are not printed on my screen. Can someone tell me what might be the problem?

A: Resetting the position indicator with seekp to 0 helps, because both output and input indicators are set to the end of file after write operation (you can read them with tellp tellg).
obj << "Hi How are you" ;
obj.seekp(0);

char c;
while (!obj.eof()){
    obj.get(c);
    cout << c;
}

Considering avoiding using obj.eof(), you can e.g. read your file line by line:
std::string line;
std::getline(obj, line);
std::cout << line << std::endl;

or in the loop:
while (std::getline(obj, line))  // here std::basic_ios<CharT,Traits>::operator bool is used to check if operation succeeded
{
  std::cout << line << std::endl;
}

A: You got two problems there: buffering and seek position.
Buffering:
When you write the text with obj << "Hi How are you, you just write it into the buffer and the text gets written into the file after flushing the buffer. You can adjust which buffer type you want to use. The easiest way is to write std::endl after your text if you use line buffering.
A better explaination is already here
Seek Position:
You are reading from the last position in your file. You have to manually change the read position to the first character in the file, then you are done.


text:
Q: How i write a formular for get value for a column in sql server 2012? I have a table with 2 column named unit_Perchus_Price and unit_sale_price. then I want to add a column named profit_margin and it values can get from this formular.
Profit Margin = (1 - (UnitPurchasePrice / UnitSalePrice)) * 100
can I do that in sql server 2012 ??

A: Yes, this is called a computed column
alter table t
add ProfitMargin as (1 - (UnitPurchasePrice / UnitSalePrice)) * 100

Some basic remarks on computed columns :
It's rather simple when you use value from the same table. If you need values from other tables, you'll need a function (and impact on performances can be important).
And you can't use a computed column in the computation of another computed column.


text:
Q: Setting up custom stemming in solr I have been following the tutorial for solr, and am attempting to enable custom stemming, but I can't get it to work.
The first problem I ran into was that I couldn't find the schema.xml file.  Most of the documentation I saw implied that it would be in the following location:
/solr-4.9.0/example/solr/

but the only one I found was here:
/solr-4.9.0/example/solr/collection1/conf/schema.xml

I modified that file to contain the following:
<fieldtype name="plumbing_abbrev" class="solr.TextField">
  <analyzer>
    <tokenizer class="solr.WhitespaceTokenizerFactory"/>
    <filter class="solr.LowerCaseFilterFactory"/>
    <filter class="solr.StemmerOverrideFilterFactory"
            dictionary="stemdict.txt" ignoreCase="true"/>
    <filter class="solr.EnglishMinimalStemFilterFactory" />
  </analyzer>
</fieldtype>

In the same directory as the schema.xml file, I made a file called stemdict.txt which contains insinkerator\tise.
I expect this to make it so I can type in insinkerator and get documents that have the string ise in them, but it isn't working, typing in insinkerator gets none of the ise hits.  What am I doing wrong?
------edit-------
I tried changing stemdict.txt to bogus, and when I started up the solr server, it didn't work, throwing an exception saying that there was no such file as bogus.  This suggests that it is indeed finding, and using, the stemdict.txt file, but it just isn't using it to actually do anything useful.
To help, here is a screen shot of analysis for the field in question:


text:
Q: Not separable first order DE I have a two part question on first order DEs
i) Find $\frac{dy}{dx}$ for $y=ux$ where $u$ is a function of $x$
ii) Hence solve for $\frac{dy}{dx}=\frac{y^2}{2x^2}+\frac12$ given $y(1)=2$
For i) I got $\frac{dy}{dx}=u+u'x$
$=\frac{y}{x}+x\frac{x\frac{dy}{dx}-y}{x^2}$
But this then simplifies down to $\frac{dy}{dx}=\frac{dy}{dx}$ so I'm unsure whether I should just leave the answer as $\frac{dy}{dx}=u+u'x$
For ii) I got no ideas, I've tried guessing random substitutions for $u$ such as $x+\frac12$ but I have had no luck.
Can someone please show me how to use part i to solve ii?

A: Hint...When you substitute the expression you have for $\frac{dy}{dx}$ into the given differential equation, and substitute for $\frac yx=u$, you get
$$u+x\frac{du}{dx}=\frac12u^2+\frac12$$
$$\implies x\frac{du}{dx}=\frac12(u-1)^2$$
can you continue?


text:
Q: Mathematical way to solve Honeycomb Puzzle There is a puzzle: "Fill the board with letters from A to G, that in the field and in its surrounding each letter is placed only once (can't be repeated).
This rule concerns also fields with not full surrounding e.g. edge fields.

Could you tell me if there is a mathematical equation, which solve the puzzle?
Honeycomb puzzle

A: In the case you've posted, the simple algorithm can be applied:

*

*Find an empty field, that is surrounded by 6 filled fields or filled field that is surrounded by 5 filled and one empty field (there are 2 such fields).

*Fill the empty field with missing letter

*If the board is not filled, go back to 1.

I suppose, that on the higher levels of difficulty you should use some different methods like in sudoku.

A: This puzzle is related to the Hadwiger-Nelson problem. Note that in the shown honeycomb you can see four equal letters forming a parallelogram and three more equal letters that can be supplemented to a homothetic parallelogram. This idea might speed up the solution process.


text:
Q: Windsor: How do I tell the container to release DynamicParameters when releasing the component?         windsorContainer.Register(
            Component.For<ClassWithReferenceToDisposableService>()
            .LifeStyle.Transient
            .DynamicParameters((k, d) =>
                                                       {
                                                           d["disposableComponent"] =
                                                               windsorContainer.Resolve<DisposableComponent>();
                                                       }));

        windsorContainer.Register(Component.For<DisposableComponent>().LifeStyle.Transient);

        ClassWithReferenceToDisposableService service = windsorContainer.Resolve<ClassWithReferenceToDisposableService>();
        windsorContainer.Release(service);

When the container releases the service, is does not dispose of the "disposableComponent" due to the dynamic parameter. How can i opt in during creation and tell windsor to release the "disposableComponent" when releasing the service?

A: There's an overload to DynamicParameters that returns a delegate. This delegate is called when the component gets released and that's where you can release your dynamic parameters. See the documentation for an example.


text:
Q: facebook tab not resizing any more Does anyone know if the code that resized the iframe of a facebook tab has chanhged recently?
I used to add this in the head:

and this in the body:

and all that needed changing is the APP ID and the values in the setSize script then I could set the height to match the content on each tab.
However looking at my tabs now, all of them seem to have reset back to the default 800px high which makes me think facebook have changed the way they do things but can't find anything anywhere and have seen nothing on the developer blog.

A: You first have to check whether the Canvas is loaded-
FB.Canvas.setDoneLoading( function(response) {
    console.log(response.time_delta_ms);
    FB.Canvas.setAutoGrow();
});

FB.Canvas.setDoneLoading
OR, you can also try after onBodyLoad

A: This seems to work without even setting a height, possibly a responsive solution?


text:
Q: Is it possible to disable 'Install gatsby-starter' on Chrome browser We released a static website using gatsby. We just noticed that user will see 'Install gatsby-starter' on Chrome browser setting.
Why is it appearing on?  Can we disable it?
gatsby version:  "^2.13.39"

A: The answer I got from Gatsby team.
"
This is Chrome supporting PWAs in the browser itself. If you open your site with an Android Phone you'll also see a prompt to install it. You can remove this functionality by removing the manifest (+ optionally offline) plugin:
"


text:
Q: How do you instruct NUnit to load an assembly's dll.config file from a specific directory? If an assembly contains an app.config file, ConfigurationManager will load it as long as it is in the same directory as the NUnit project that is executing through NUnit-Gui.  To illustrate consider the following folder structure.
+ TestFolder
    testProject.nunit
  + AssemblyAFolder
      assemblyA.dll
      assemblyA.dll.config
  + AssemblyBFolder
      assemblyB.dll
      assemblyB.dll.config

Both AssemblyA and AssemblyB exercise code that calls into ConfigurationManager.  If I run these test assemblies independently in NUnit-Gui, ConfigurationManager will correctly resolve the local configuration files.
However, if I load testProject.nunit into NUnit-Gui (which contains references to both AssemblyA and AssemblyB), ConfigurationManager looks for the configuration file in TestFolder regardless of which assembly is currently executing.
Is there a way to direct NUnit to reload the application configuration to the one present in the current assembly's directory?
Here are the contents of testProject.nunit:
<NUnitProject>
  <Settings activeconfig="Debug" />
  <Config name="Debug" binpathtype="Auto">
    <assembly path="AssemblyAFolder\assemblyA.dll" />
    <assembly path="AssemblyBFolder\assemblyB.dll" />
  </Config>
</NUnitProject>

A: Nunit is unable to locate the path of App.config File in our project. So we need to manually tell the Nunit where the App.config File is placed in our project (obviously on the root folder).
In my case , the project structure is as following
     +ProjectWEBApp//web pages
       +Modules
         +aspx pages
       +web.Config

    +projectBusinesslogic //business logic .cs files
       +Modules
         +.cs

      +ProjectTestName// a seperate Nunit test cases project
        +Modules
      +App.Config

the ProjectWebApp uses the references of projectBusinesslogic which contains the business logic.
the +ProjectTestName uses the reference of projectBusinesslogic to perform test on the business logic.
The problems start here, Nunit test project needs its own app.config file. it won't use web.config file as in case of projectBusinesslogic,so when you run Nunit it will prompt an error

-Null Reference exception.......object instant not set to ...........

Solution-
When you run the Nunit GUI

*

*Project->Edit  a new pop up will open

*Properties -> General->Configuration File Name-> add your app.config File Name

*File->save and close the pop-up window

*ON Nunit Gui-File-> Reload Project

and that is the simple solution for your problem

A: The configSource element solution given by MarkLawrence is what I was looking for, and works nicely.  The challenge in implementing this solution however, is to make the assembly configuration load when running tests from both an explicit NUnit project (as in my case), AND when running the unit tests for an assembly in isolation (no explicit project).  To accomplish this, the following modifications to my file layout were required.
+ TestFolder
    testProject.nunit
    testProject.config
  + AssemblyAFolder
      assemblyA.dll
      assemblyA.dll.config
      assemblyA.dll.configfragment
  + AssemblyBFolder
      assemblyB.dll
      assemblyB.dll.config
      assemblyB.dll.configfragment

The configfragment files are created to contain the assembly configuration that was once in the corresponding config files.  Afterwards, the config files are modified to contain only a configSource element with a relative path to the corresponding configfragment file.  Note that the only time that this approach doesn't work is when assemblyA.dll and assemblyB.dll both require the same configuration section, as a conflict will arise when creating testproject.config.
After experimenting with this approach I decided to rely on generating the assembly configuration at runtime, and remove the static configuration files all together.  Here is some code that demonstrates how to generate the configuration, and make it accessible regardless of how the assembly-under-test is loaded.
void WithConfigurationFile(Action method)
{
    // Create the assembly configuration.
    string settingsSection = "myConfigSectionName";
    Configuration config =
        ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    config.Sections.Add(
        settingsSection,
        new ConfigSectionType(/*config element values*/);
    config.Save();

    try
    {
        // Invoke the method with the new configuration.
        ConfigurationManager.RefreshSection(settingsSection);
        method();
    }
    finally
    {
        // Revert the assembly configuration.
        File.Delete(config.FilePath);
        ConfigurationManager.RefreshSection(settingsSection);
    }
}

By using the ConfigurationManager.OpenExeConfiguration() overload that does not accept a path, we load the configuration from the host application's working directory, which changes depending on how you run your NUnit tests.  Also, the try/finally block guarantees that your assembly configuration will not interfere with other tests, which may or may not require such configuration.
Finally, to use within a unit test:
[Test]
void VerifyFunctionality
{
    WithConfigurationFile(delegate
    {
        // implement unit test and assertions here
    });
}

I hope this helps others who may have encountered similar issues!

A: The NUnit blog explained of why the config files load the way they do. Basically what they said was that NUnit lets the framework handle the config files and doesn't do any of the management.
You can also use the testProject.config file that would be loaded in your case, to reference the config files for each of the assemblies. Using the appSettings file attribute to add keys.
One final alternative is to use the configSource element attribute to use the section in one of the assemblies config files.
Hope this helps.

A: Use the configfile attribute in the Config level in your .nunit file:

<Config name="Debug" configfile="myconfigfilenamegoeshere.config />

A: Actually, if you are using NUnit and a runner within Visual Studio, you can stick your value in an App.config in your test project. Then add this line to your Post-build event:
copy /Y "$(ProjectDir)App.config" "$(TargetDir)$(TargetFileName).config"
When you access the ConfigurationManager in your tests, NUnit will pass the values in your app.config to .Net in the initialize method.


text:
Q: Https configuration in AWS Elastic Beanstalk I have a node.js app in elastic beanstalk and I want it to be consumed through HTTPS. But for some reason it doesn't connect securely.
Steps I followed:

*

*Created a hosted zone In Route53 with my own domain.

*Received email for domain verification, accepted and and created hosted zone.

*Enabled port 443 for https in EB environment configuration.

*Added new inbound rule for https with port 443 in security group.

Then when I hit the url (https://myurl.us-west-1.elasticbeanstalk.com/) in browser it shows the page but not securely. I have attached the screenshot.

A: Just consolidating the findings in hope that it will be useful for someone else as well.
I'm greatly simplifying here, but two key checks browser performs when validating a certificate are certificate chain and site name. (At least these two seem like the two most common sources of issues with certificates.)
With certificate chain browser checks that certificate was signed by a well known (and trusted) authority. So, first of all you need a proper certificate issued by a well known certificate issuing authority. The easiest is probably to get one from AWS Certificate Manager. But you can obtain one from a certificate authority instead. See here: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/configuring-https.html
To be fair, you actually can use a self signed certificate and can even suppress the warning by adding your signing certificate to the list of trusted certificates in your browser. But that isn't really an option for a public web site as it will require every visitor of your website to manually add your certificate as trusted.
With the name check a browser simply verifies that site name you typed in the url bar matches to one of those listed on the certificate. To satisfy this check you have to configure www.mydomain.com (or whatever your domain is) as an alias to you ELB in Route53. Then point your browser to www.mydomain.com (not to elasticbeanstalk url).


text:
Q: How to loop through properties of objects inside of an array within a React component? Here is my Parent component's render function:
  render() {
    const users = [
      'tom': {
        phone: '123',
        email: 'hotmail'
      },
      'rob': {
        phone: '321',
        email: 'yahoo'
      },
      'bob': {
        phone: '333',
        email: 'gmail'
      },
    ];

    const list = users.map((user) =>
      (<User
        name={user}
        phone={users.phone}
        email={users.email}
      />),
    );

    return
{list}
;
  }

The output shows up like this:

And here is the Child component's render function:
  render() {
    const {
      name,
      phone,
      email,
    } = this.props;

    const info = [name, phone, email];

    const item = info.map((index) => (

        { index }

    ));

    return item;
  }

How can I get it to show with the phone numbers and emails? Not sure what I'm doing incorrectly. Thanks.

A: At first this is not valid javascript:
const users = [
  'tom': {
    phone: '123',
    email: 'hotmail'
  },
  // ...
];

You should either define an array or an object. Let's say your users is an object literal:
const users = {
  'tom': {
    phone: '123',
    email: 'hotmail'
  },
  // ...
};

Then you can iterate over entries of the object:
const list = Object.entries(users).map(([name, info]) =>
  (<User
    name={name}
    phone={info.phone}
    email={info.email}
  />)
);

However Object.entries() is not supported in all browsers, check if it works in your environment.

A: First thing is that users is not a valid array If you want key value pair in main scope then use Object({})
 render() {
        const users = {
          'tom': {
            phone: '123',
            email: 'hotmail'
          },
          'rob': {
            phone: '321',
            email: 'yahoo'
          },
          'bob': {
            phone: '333',
            email: 'gmail'
          },
        };

        const list = Object.keys(users).map((user) =>
          (<User
            name={user}
            phone={users[user].phone}
            email={users[user].email}
          />),
        );

        return
{list}
;
      }

A: You need to be referring to "user" instead of "users" inside of the Parent component's map function.  The purpose of the "user" variable is to represent the current instance of each element in the array.  So the map function should look like:
const list = users.map((user) =>
  (<User
    name={user}
    phone={user.phone}
    email={user.email}
  />),
);

instead.

A: One solution is to change your "list" to an actual list:
const users = [
  {
    name: 'tom',
    phone: '123',
    email: 'hotmail'
  },
  {
    name: 'rob,
    phone: '321',
    email: 'yahoo'
  },
  {
    name: 'bob',
    phone: '333',
    email: 'gmail'
  },
];

Now user user.name instead of user.
Alternatively, create an object keyed by the names of each user:
const users = {
  'tom': {
    phone: '123',
    email: 'hotmail'
  },
  'rob': {
    phone: '321',
    email: 'yahoo'
  },
  'bob': {
    phone: '333',
    email: 'gmail'
  },
};

Then map over the keys:
const list = Object.keys(users).map((user) =>
  (<User
    name={user}
    phone={users[user].phone}
    email={users[user].email}
  />),
);

A: Your const users should be modified to map through them.
 const users = [
            {
            name: 'tom',
            phone: '123',
            email: 'hotmail',
          },
          {
            name:'rob',
            phone: '321',
            email: 'yahoo'
          },
          {
            name: 'bob',
            phone: '333',
            email: 'gmail'
          },
    ];
    const list = users.map((usr =>
      (<User
        name={usr.name}
        phone={usr.phone}
        email={usr.email}
      />),
    );

    return
{list}
;
  }


text:
Q: converting a string to date in Java import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TesterA
{
    public static void main(String[] args)
    {
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
        String dateInString = "7-Jun-2013";

        try
        {
            Date date = formatter.parse(dateInString);
            System.out.println(date);
            System.out.println(formatter.format(date));
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }
    }
}

I was trying to run this sample code copy from a web, but it doesn't work. How should I change it?
This is the error I got
java.text.ParseException: Unparseable date: "7-Jun-2013"
    at java.text.DateFormat.parse(DateFormat.java:366)
    at TesterA.main(TesterA.java:14)

A: I think it is a problem with your locale.
Try:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);

A: java.text.ParseException means you provided a string which cannot be parsed using the current settings.
Just set the Locale.
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);


text:
Q: restAPI login implementation when using password hashing with a salt (argon2) I'm currently building a rest api and stumbled across this problem:
The users password is stored hashed with a salt in the database as a typical argon2 string.
A user tries to login and sends therewith his email and password (unhashed).
But how do I compare hashes if I cant hash the password again ( as I'm missing the original salt).
Should I get the hash from the database and the compare the two or what's the best practice there?
I tried it with getting the hash form the database but I'm not sure if it's allowed to "get" something from a database if the user's request is a post-request.