text:
Q: Launching embedded Jetty wont work , SLF4J respond with error I'm running my program and I got this error :
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/Users/mtaboubi/.m2/repository/org/slf4j/slf4j-log4j12/1.6.1/slf4j-log4j12-1.6.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/mtaboubi/.m2/repository/ch/qos/logback/logback-classic/1.0.13/logback-classic-1.0.13.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
Exception in thread "main" java.lang.SecurityException: class "javax.servlet.FilterRegistration"'s signer information does not match signer information of other classes in the same package
    at java.lang.ClassLoader.checkCerts(ClassLoader.java:812)
    at java.lang.ClassLoader.preDefineClass(ClassLoader.java:493)
    at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
    at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    at org.eclipse.jetty.servlet.ServletContextHandler.<init>(ServletContextHandler.java:134)
    at org.eclipse.jetty.servlet.ServletContextHandler.<init>(ServletContextHandler.java:114)
    at org.eclipse.jetty.webapp.WebAppContext.<init>(WebAppContext.java:194)
    at ca.actimenu.utils.launcher.Launcher.parseArgs(Launcher.java:108)
    at ca.actimenu.utils.launcher.Launcher.<init>(Launcher.java:42)
    at ca.actimenu.utils.launcher.Launcher.<init>(Launcher.java:53)
    at LaunchWebapp.main(LaunchWebapp.java:12)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

Process finished with exit code 1

I'm using and embedded Jetty server and I'm using IntelliJ idea ...
It is the first time that I got this issue and I dont know what's going on .... Any help ?

A: You have multiple slf4j implementation dependencies on your pom.xml

A: Oh yes, It happens after I added these dependencies :
>         <!--AspectJ-->
>         <dependency>
>             <groupId>org.aspectj</groupId>
>             <artifactId>aspectjrt</artifactId>
>             <version>1.6.11</version>
>         </dependency>
>
>         <!--youtube-->
>         <dependency>
>             <groupId>com.google.apis</groupId>
>             <artifactId>google-api-services-youtube</artifactId>
>             <version>v3-rev144-1.20.0</version>
>         </dependency>
>
>         <dependency>
>             <groupId>com.google.oauth-client</groupId>
>             <artifactId>google-oauth-client-jetty</artifactId>
>             <version>1.11.0-beta</version>
>         </dependency>
>
>         <!--fin youtube-->
>
>         <!--JSCH - connection ssh via Java-->
>         <dependency>
>             <groupId>com.jcraft</groupId>
>             <artifactId>jsch</artifactId>
>             <version>0.1.53</version>
>         </dependency>

>    <dependency>
>        <groupId>com.sun.jersey.contribs</groupId>
>        <artifactId>jersey-multipart</artifactId>
>        <version>1.9.1</version>
>    </dependency>

And the problem is resolved when I delete these dependencies :)
I will search which of these dependencies uses SLF4J and I ll make an exclude ...
Thanks


text:
Q: side menu Help 2
I'm trying to use tableviewcotroller with this but when look at the screenshot at the button will seen a issue I need helping fixing so if anyone knows how to fix this plz help I don't want use SWRevealViewController I'm also doing with all code not scoreboards thanks for the help
class SidebarView: UIView, UITableViewDelegate, UITableViewDataSource {

    var titleArr = [String]()

    weak var delegate: SidebarViewDelegate?

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.clipsToBounds=true

        titleArr = ["Brittney Atwood", "Messages", "Contact", "Settings", "History", "Help", "Sign Out"]

        setupViews()

        myTableView.delegate=self
        myTableView.dataSource=self
        myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        myTableView.tableFooterView=UIView()
        myTableView.separatorStyle = UITableViewCellSeparatorStyle.none
        myTableView.allowsSelection = true
        myTableView.bounces=false
        myTableView.showsVerticalScrollIndicator=false
        myTableView.backgroundView = UIImageView(image: #imageLiteral(resourceName: "Rectangle 96"))
        myTableView.isOpaque = false

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titleArr.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell=tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.backgroundColor = .clear
        cell.selectionStyle = .none
        if indexPath.row == 0 {
            let cellImg: UIImageView!
            cellImg = UIImageView(frame: CGRect(x: 15, y: 10, width: 80, height: 80))
            cellImg.layer.cornerRadius = 40
            cellImg.layer.masksToBounds=true
            cellImg.contentMode = .scaleAspectFill
            cellImg.layer.masksToBounds=true
            cellImg.image=#imageLiteral(resourceName: "user11")
            cell.addSubview(cellImg)

            let cellLbl = UILabel(frame: CGRect(x: 110, y: cell.frame.height/2-15, width: 250, height: 30))
            cell.addSubview(cellLbl)
            cellLbl.text = titleArr[indexPath.row]
            cellLbl.font=UIFont.systemFont(ofSize: 17)
            cellLbl.textColor=UIColor.white
        } else {
            cell.textLabel?.text=titleArr[indexPath.row]
            cell.textLabel?.textColor=UIColor.white
        }
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.delegate?.sidebarDidSelectRow(row: Row(row: indexPath.row))
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return 100
        } else {
            return 60
        }
    }

    func setupViews() {
        self.addSubview(myTableView)
        myTableView.topAnchor.constraint(equalTo: topAnchor).isActive=true
        myTableView.leftAnchor.constraint(equalTo: leftAnchor).isActive=true
        myTableView.rightAnchor.constraint(equalTo: rightAnchor).isActive=true
        myTableView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive=true
    }

    let myTableView: UITableView = {
        let table=UITableView()
        table.translatesAutoresizingMaskIntoConstraints=false
        return table
    }()

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

A: Please write this code it may helps to you.
        var topSafeArea: CGFloat
        var bottomSafeArea: CGFloat

        if #available(iOS 11.0, *) {
            topSafeArea = view.safeAreaInsets.top
            bottomSafeArea = view.safeAreaInsets.bottom
        } else {
            topSafeArea = topLayoutGuide.length
            bottomSafeArea = bottomLayoutGuide.length
        }

        // safe area values are now available to use

Thank you.

A: that the view controller I don't know where the issue is it probably in one of the two files that I post it still not fix
 class ViewController: UITableViewController {
 var sidebarView: SidebarView!
 var blackScreen: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    self.title = "Messages"

    let btnMenu = UIBarButtonItem(image: #imageLiteral(resourceName: "menu"), style: .plain, target: self, action: #selector(btnMenuAction))
    btnMenu.tintColor=UIColor(red: 54/255, green: 55/255, blue: 56/255, alpha: 1.0)
    self.navigationItem.leftBarButtonItem = btnMenu

    sidebarView=SidebarView(frame: CGRect(x: 0, y: 0, width: 0, height: self.view.frame.height))
    sidebarView.delegate=self
    sidebarView.layer.zPosition=100
    self.view.isUserInteractionEnabled=true
    self.navigationController?.view.addSubview(sidebarView)

    blackScreen=UIView(frame: self.view.bounds)
    blackScreen.backgroundColor=UIColor(white: 0, alpha: 0.5)
    blackScreen.isHidden=true
    self.navigationController?.view.addSubview(blackScreen)
    blackScreen.layer.zPosition=99
    let tapGestRecognizer = UITapGestureRecognizer(target: self, action: #selector(blackScreenTapAction(sender:)))
    blackScreen.addGestureRecognizer(tapGestRecognizer)
}

@objc func btnMenuAction() {
    blackScreen.isHidden=false
    UIView.animate(withDuration: 0.3, animations: {
        self.sidebarView.frame=CGRect(x: 0, y: 0, width: 250, height: self.sidebarView.frame.height)
    }) { (complete) in
        self.blackScreen.frame=CGRect(x: self.sidebarView.frame.width, y: 0, width: self.view.frame.width-self.sidebarView.frame.width, height: self.view.bounds.height+100)
    }
}

@objc func blackScreenTapAction(sender: UITapGestureRecognizer) {
    blackScreen.isHidden=true
    blackScreen.frame=self.view.bounds
    UIView.animate(withDuration: 0.3) {
        self.sidebarView.frame=CGRect(x: 0, y: 0, width: 0, height: self.sidebarView.frame.height)
    }
  }
}

extension ViewController: SidebarViewDelegate {
func sidebarDidSelectRow(row: Row) {
    blackScreen.isHidden=true
    blackScreen.frame=self.view.bounds
    UIView.animate(withDuration: 0.3) {
        self.sidebarView.frame=CGRect(x: 0, y: 0, width: 0, height: self.sidebarView.frame.height)
    }
    switch row {
    case .editProfile:
        let vc=EditProfileVC()
        self.navigationController?.pushViewController(vc, animated: true)
    case .messages:
        print("Messages")
    case .contact:
        print("Contact")
    case .settings:
        print("Settings")
    case .history:
        print("History")
    case .help:
        print("Help")
    case .signOut:
        print("Sign out")
    case .none:
        break
        //        default:  //Default will never be executed
        //            break
    }
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Debugging module throw errors? I just started messing with node.js and I'm already having problems, I have no idea how to even start debugging this..
>   npm install express jade socket.io

module.js:333
    throw err;
          ^
Error: Cannot find module 'cookie-jar'
    at Function.Module._resolveFilename (module.js:331:15)
    at Function.Module._load (module.js:273:25)
    at Module.require (module.js:357:17)
    at require (module.js:373:17)
    at Object.<anonymous> (/usr/local/Cellar/node/0.10.24/lib/node_modules/npm/node_modules/request/index.js:15:14)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:349:32)
    at Function.Module._load (module.js:305:12)
    at Module.require (module.js:357:17)

A: If you want to just use npm just install each package with a separate command
npm install express
npm install jade
npm install socket.io

On my computer it works.
My suggestion is to use the "package.json" file. In that file you can specify the libraries you need and it's going to download the dependencies for you.
For example
{
    "name": "myapp",
    "version": "0.0.1",
    "author": "Alvise Susmel <alvise@50pixels.com>",
    "dependencies": {
            "jade": "*",
            "express": "*",
            "socket.io": "*"
    }
}

and just execute
npm install

And npm will make all for you. It will create a "node_modules" where there are the dependencies.
Just create your js files in the same directory of "node_modules" and the dependencies will be all available to be included.
As you can see in the package.json file, near every dependency, there is a " * ", that means "all versions". If you want, you can set a specific version.
If you want to know more about this, that's a useful link: https://npmjs.org/doc/json.html


text:
Q: Find a function $f\not \in BV[0,1]$ and $|f|\in BV[0,1]$ Find a function $f\not \in BV[0,1]$ and $|f|\in BV[0,1]$
I was thinking in a bounded function |f| such that f isn't bounded, but this isn't possible. Moreover, i'm trying to construct another pairwise function, but i'm a little stuck. Can someone help me?

A: How about $f(x) = 1$ if $x$ is rational and $f(x) = -1$ otherwise?


text:
Q: Prototype functions to classes and not ids elements i'm new to prototype framework and i'm trying to apply some functions to classes elements and not ids elements.
This because I need to replicate every functions to various elements.
If I apply them to ids elements, only one of those get involved.
So, this is my script running with ids elements:
function removing (){
$('element').remove();
var data = $('element').innerHTML;
var wanted_count = 50;
var output = cutHtmlString(data, wanted_count);
$('element').replace(output);
}

the script remove and element of two and, and cuts the remaining one (an html string) and replace it.
I tried this but doesn't work:
function removing (){
$$('element').remove();
var data = $$('element').innerHTML;
var wanted_count = 50;
var output = cutHtmlString(data, wanted_count);
$$('element').replace(output);
}

thanks for helping

A: '$$' returns an array, even if there happens to be only one result.
So you cannot apply functions such as remove() to the result of $$.
You probably want
$$('element').invoke('remove');
However, there is another problem: $$ takes a CSS rule, so $$('element'), though syntactically valid, would match only things matched by the CSS rule 'element' - i.e. DOM elements with tag 'element', and there aren't any in HTML.
If what you mean is all elements with class 'element', then the code is
$$('.element').invoke('remove');


text:
Q: Selecting an unnamed text field in a mechanize form (python) So i'm making a program to batch convert street addresses to gps co-ordinates using mechanize and python. this is my first time using mechanize. I can select the form ("form2') on the page. however the text box in the form has no name. how do i select the textbox so that mechanize can enter my text? I've tried selecting it by its id. but that does not work.
br.select_form("Form2") #works as far as i know
br.form["search"] = ["1 lakewood drive, christchurch"] #this is the field that i cannot select

and here is the source code from the website.
<form name="Form2" >
or  Type an <b>Address</b>
<input id="search" size="40" type="text" value=""  >
<input type="button" onClick="EnteredAddress();" value="Enter" />
</form>

any help would be much appreciated.

A: form.find_control(id="search") ?

A: FWIW I solved this by using the above answer by lazy1 except that I was trying to assign a value after using the find_control method. That didn't work of course because of assignment, I looked deeper into the method and found setattr() and that worked great for assigning a value to to the field.
will not work
br.form.find_control(id="field id here") = "new value here"

will work
br.form.find_control(id="field id here").__setattr__("value", "new value here")


text:
Q: Prolog recursion doing infinite loop Here's the code
flight(roc,syr,25).
flight(roc,jfk,55).
flight(jfk,bos,65).
flight(bos,syr,40).
flight(jfk,syr,50).
flight(bos,roc,50).

layover(roc,25).
layover(jfk,55).
layover(syr,30).
layover(bos,40).

route(X,Y,R,D) :-
   flight(X,Y,L),
   D is L,
   R = [X,Y].
route(X,Y,R,D) :-
   flight(X,Z,L),
   route(Z,Y,P,M),
   R = [X|P],
   layover(Z,T),
   D is M+L+T,
   \+ member(X,P).

Here's what's happening. The second clause
route(X,Y,R,D) :-
   flight(X,Z,L),
   route(Z,Y,P,M),
   R = [X|P],
   layover(Z,T),
   D is M+L+T,
   \+ member(X,P).

goes into an infinite loop. It displays the answers I want, then keeps finding more answers (as you can just keep looping around stops basically) and does an infinite loop until it stops. The program is supposed to find every possible flight route that doesn't loop around stops. I know why this happens, but have no idea how to change my code to fix it. Please help.
Here's one solution
?- route(roc, syr, Routing, Duration).
Routing = [roc, syr],
Duration = 25 ;
Routing = [roc, jfk, syr],
Duration = 160 ;
Routing = [roc, jfk, bos, syr],
Duration = 255 ;
false.

A: One caveat to my answer - I am making a few assumptions about your variables.  I assume X is the starting point, Y is the destination, R is the list of locations along path from X to Y (inclusive) and D is the distance traveled?  Or perhaps wait time.  Shouldn't matter.
It looks like a problem with your base case.  Your base case is checking for the existence of a flight(X,Y,L) that satisfies the route.  What you need to be checking is whether the list of locations from X to Y (R, if I am not mistaken) already covers from X to Y.  That is, if the last element of list R = Y and the first element of R = X, then you are done.
A last function you could use would be:
last([X],X).
last([H|T],R):- last(T,R).

Then you can have a base case:
route(X,Y,R,D):- last(R,L), L == Y, [H|T] = R, H == X.

Or something like that, anyway.  It has been awhile since I have used prolog...
Let me know if that helps.

A: I think your problem should be solved moving \+member(X,P) before the recursive call. That's because Prolog implements logic by means of a depth first search of clauses, i.e. top down and left to right selection and match.
Of course moving the test requires a change in P computation. Now is built after the visit. A simple way to do is using an accumulator, initialized to [] in first call, and unified to full path on destination. I.e.
route(X,Y,Acc, [X,Y|Acc], D) :- flight(X,Y,L), D is L.
...

?- route(roc, syr, [], Routing, Duration).


text:
Q: JavaFX how to get menubar to fit to parent in width only? I am using Scene Builder to create my GUI and my menu bar isn't resizing to the parent. How do i get it to do this?
When I try Modify -> Fit to Parent, the menu bar takes up the whole root pane, and obviously this isn't what i want. Here is an image of what i am talking about:

As you can see, the menu bar doesn't fully extend to the end of the window.

A: Here is another way to do it. Wrap MenuBar in a HBOX. Set MenuBar's HGrow to ALWAYS. Set HBOX Node Alignment to TOPLEFT.

A: You need to bind the preferred width property of your menu bar to the width of your stage or some other container node. It works when you dynamically resize too.
menuBar.prefWidthProperty().bind(primaryStage.widthProperty());

A: I had to set the anchor pane constraints in the menu bar. I had to make the left and right margins zero:


text:
Q: Transforming data frame to a selection list in selectInput (Shiny) I've a data frame corresponding to the sample below:
df = data.frame(subject=c("Subject A", "Subject B", "Subject C", "Subject D"),id=c(1:4))

I would like to transform this data frame to a list object that could be conveniently implemented in selectInput:
selectInput("subject", "Subject",
            choices = #my_new_list )

I would like for the end-user to see the list of subjects in the selection and for the selectInput to return the corresponding numerical value (id).
If I attempt to get my list via:
df <- data.frame(lapply(df, as.character),
                         stringsAsFactors = FALSE)
df <- as.list(df)

The selectInput drop down menu shows all available options:

I'm only interested in listing subjects and passing the corresponding numerical values.

A: Use function split:
my_new_list <- split(df$id, df$subject)
my_new_list
#$`Subject A`
#[1] 1

#$`Subject B`
#[1] 2

#$`Subject C`
#[1] 3

#$`Subject D`
#[1] 4

Together with function with:
my_new_list <- with(df, split(id, subject))

A: For the choices argument, you can use a named list, from the doc:

If elements of the list are named then that name rather than the value
  is displayed to the user

To make the named list you could try:
your_choices <- as.list(df$id)
names(your_choices) <- df$subject

And in the app:
selectInput("subject", "Subject",
                choices = your_choices )

A: Use setNames, for example:
selectizeInput('x3', 'X3', choices = setNames(state.abb, state.name))
like in this example http://shiny.rstudio.com/gallery/option-groups-for-selectize-input.html


text:
Q: RegEx to extract Contact Name and email from string I'm trying to come up with some RegEx to extract name and email address from a string.
I know there are tons of questions about this here, and just went through some and they don't work for me.
This is the RegEx I have so far
([\'(\w\d\s*)\'\s]*)<([a-z\d._%+-]+@[a-z\d.-]+\.[a-z]{2,4}\b)>

The strings can be like
Name Surname email@domain.com

'Name Surname' <email@domain.com>

'Name Surname' email@domain.com

Name Surname <email@domain.com>

So I guess you could see that both the ' and the < > can be entirely optional.
I need it to get the results in two groups, one for the contact name and one for the email.
I'm using classic asp due to legacy code in the company.
Thanks

A: You can use
'?(\w+(?:\s+\w+)*)'?\s+<?(\S+@[\w.-]+\.[a-zA-Z]{2,4}\b)

See the regex demo
Pattern explanation:

*

*'? - an optional '

*(\w+(?:\s+\w+)*) - Group 1 matching:

*

*\w+ - 1 or more alphanumeric/underscore symbols

*(?:\s+\w+)* - 0 or more sequences of 1+ whitespaces followed with 1+ alphanumeric/underscore symbols

*'? - an optional '

*\s+ - 1 or more whitespace symbols

*<?  - an optional <

*(\S+@[\w.-]+\.[a-zA-Z]{2,4}\b) - Group 2 matching

*

*\S+ - 1+ non-whitespace symbols

*@ - a literal @

*[\w.-]+ - 1 or more characters: alphanumeric/underscore, dot or hyphen

*\. - a literal dot

*[a-zA-Z]{2,4} - 2 to 4 ASCII letters

*\b - a trailing word boundary

A: Here are two Regex.  Use the first to get the email out of the string and the second to get a two part name.
Email
[\w\.\-]+@(([\w\-]+)\.)+(\w){2,3}

Name
\b[a-zA-Z]*[^\s@.]\b\s?\b[a-zA-Z]*[^\s@.]\b


text:
Q: Is my server being hacked in? I need help to decide if my server has been hacked in.
The server has sshd turned on. The other day, I tried lsof -i TCP to see someone is connecting to the server before I restart it. Then I noticed the following output:
sshd     19400    root    3u  IPv6 224125      0t0  TCP [2600:3c01::f03c:91ff:fe57:c70b]:ssh->123.456.789.123:59030 (ESTABLISHED)
sshd     19409    me    3u  IPv6 224125      0t0  TCP [2600:3c01::f03c:91ff:fe57:c70b]:ssh->123.456.789.123:59030 (ESTABLISHED)
sshd     10623    root    3u  IPv4 123099      0t0  TCP www.playandlearn.xyz:ssh->221.131.165.86:49085 (ESTABLISHED)
sshd     10624    sshd    3u  IPv4 123099      0t0  TCP www.playandlearn.xyz:ssh->221.131.165.86:49085 (ESTABLISHED)

The first two lines are for my ssh connection (I changed my ip address to a fake one).
The user name shown in last line is sshd, not something I expected. I then searched the ip address 221.131.165.86, and found out that some sites listed it as malicious address.
Trying to figure out how this address logged in the server, I grepped it from /var/log/auth.log, but only find (a lot of) lines like:
Mar 23 18:59:42 www sshd[16055]: Received disconnect from 221.131.165.86 port 19152:11:  [preauth]
Mar 23 18:59:42 www sshd[16055]: Disconnected from 221.131.165.86 port 19152 [preauth]

There was no entries for successful login from this address.
After a few hours, the connection was disconnected. Since then, I randomly checked a few times and hasn't seen any connections from the suspicious address.
But today I noticed the same symptoms for another ip address: showed up as user "sshd" in lsof, a lot of unsuccessful tries to connect, but no successful login entry in /var/log/auth.log.
So my questions are:

*

*Are those listings in lsof -i TCP evidences that they have connected successfully, or they are just trying to connect. Note that in the first case, the connection seems lasted for a few hours.

*If they have hacked in, why I can't find relative logs in auth.log?

*After wrote down all these, I realize that maybe those connections are connections to my web server? One of the pages uses web socket, that might explains the long connection time?

Thanks for your help. Please let know if I need to provide more info.

A: I don't think so, it seems you are just scanned. That sshd user appears there because sshd daemon - IIUC - has priviledge separation and during initial authentication of a user it spawns new process under sshd user.
You can try yourself:
watch -n 0.5 "lsof -ni TCP | grep :ssh"

See first output:
Every 0.5s: lsof -ni TCP | grep :ssh                                                                                localhost.localdomain: Wed Mar 24 22:07:58 2021

sshd    10010    root    3u  IPv4 1532608      0t0  TCP *:ssh (LISTEN)
sshd    10010    root    4u  IPv6 1532610      0t0  TCP *:ssh (LISTEN)

And try to login into non-existing user (I assume you allow password authentication here, thus it waits for user password).
ssh jwwj@localhost
Password:

And you should see something like...
Every 0.5s: lsof -ni TCP | grep :ssh                                                                                localhost.localdomain: Wed Mar 24 22:02:57 2021

sshd    10010       root    3u  IPv4 1532608      0t0  TCP *:ssh (LISTEN)
sshd    10010       root    4u  IPv6 1532610      0t0  TCP *:ssh (LISTEN)
ssh     11218       jiri    3u  IPv4 1543472      0t0  TCP 127.0.0.1:38662->127.0.0.1:ssh (ESTABLISHED)
sshd    11219       root    4u  IPv4 1544285      0t0  TCP 127.0.0.1:ssh->127.0.0.1:38662 (ESTABLISHED)
sshd    11220       sshd    4u  IPv4 1544285      0t0  TCP 127.0.0.1:ssh->127.0.0.1:38662 (ESTABLISHED)
sshd    11221       root    4u  IPv4 1544285      0t0  TCP 127.0.0.1:ssh->127.0.0.1:38662 (ESTABLISHED)

See that my (jiri) local ssh process to localhost caused presence of a process with PID 11220.
(BTW this was tested on OpenSUSE Tumbleweed.)
Info about sshd privsep https://security.stackexchange.com/a/115905/199910 and openssh project's presentation https://www.openbsd.org/papers/openssh-measures-asiabsdcon2007-slides.pdf


text:
Q: What are `(,)` and `,` in Javascript? Can someone explain the difference between (,) and , in JavaScript and how these operations are called?
var a = 42, b;
b = ( a++, a );

var a = 42, b;
b = a++, a;

A: () just executes code inside before assigning value to b.
So b = ( a++, a ); will do:

*

*a increment by one

*b equals to a
And , alone creates a second variable and assigns value to it (undefined at this case). Its just a shorthand:
var a = 42, b; is the same as:
var a = 42,
var b;

A: The answer is already in your source: Operator Precedence
The following code outputs as:
var a = 42, b;
b = ( a++, a );

a;  // 43
b;  // 43

But what would happen if we remove the ( )?
var a = 42, b;
b = a++, a;

a;  // 43
b;  // 42

Because the , operator has a lower precedence than the = operator.
  So, b = a++, a is interpreted as (b = a++), a. Because a++ has after side effects, the assigned value to
  b is the value 42 before the ++ changes a.

() is used to enforce Order of Operations. Operator precedence on MDN.

A: From mozilla.

The comma operator evaluates each of its operands (from left to right)
  and returns the value of the last operand.

var x = 1;

x = (x++, x);

console.log(x);
// expected output: 2

x = (2, 3);

console.log(x);
// expected output: 3


text:
Q: Scraping over multiple pages using BeautifulSoup and dataframe iterrows I'm using BeautifulSoup to scrape from multiple URLs. The URL iterates by appending a variable I have saved in a dataframe (postcode_URL).
The code breaks on line: table_rows = table.find_all('tr'), throwing the error: 'NoneType' object has no attribute 'find_all'
Interestingly, the code works perfectly if I remove the iteration and manually enter a single postcode in the URL, so I believe it must be something to do with the iteration loop.
Below is the code that I have used. Any ideas?
scraped_data = []

for x, row in postcodes_for_urls.iterrows():
    page = requests.get("http://myurl"+(row['postcode_URL']))
    soup = BeautifulSoup(page.content, 'html.parser')
    table = soup.find('table')
    table_rows = table.find_all('tr')
    for tr in table_rows:
        td = tr.find_all('td')
        row = [tr.text for tr in td]
        scraped_data.append(row)

pd.DataFrame(scraped_data, columns=["A", "B", "C"])

A: I investigated the problem and tried few snippets on my laptop.
The problem is not with the DataFrame , as you are reading each row at a time in the loop, the problem is with the URL, your program correctly scraps the page having table in it and throws an error for a postcode URL that doesn't have  element.
Consider the first test :
I created an HTML page without table in it :

     <title>Demo page</title>

Demo without table

And then I executed the python code as below :
from bs4 import BeautifulSoup
data = open('table.html').read()
parser = BeautifulSoup(data, 'html.parser')
table = parser.find('table')
rows = table.find_all('tr')
print(rows)

Above code stopped due to NoneType exception because parser.find() returns a NoneType object if table element is not found in the html data. So find_all() is not a method of NoneType object, thus it throws an error.
So I changed my HTML code as below :

    <title>Demo page</title>

Demo without table

Demo

Now the python code works well without any exception as table element is present.
So the conclusion :
The exception is because one of the postcode in the DataFrame is leading to an URL that does not contain a table. So, I recommend you to make a small change to your code :
scraped_data = []

for x, row in postcodes_for_urls.iterrows():
  page = requests.get("http://myurl"+(row['postcode_URL']))
  soup = BeautifulSoup(page.content, 'html.parser')
  table = soup.find('table')
  #add this :
  if table == None :
      continue

  table_rows = table.find_all('tr')
  for tr in table_rows:
    td = tr.find_all('td')
    row = [tr.text for tr in td]
    scraped_data.append(row)

pd.DataFrame(scraped_data, columns=["A", "B", "C"])

A: All you need is to put a check on table_rows if its None and its not empty, try below code. You can also put an exception handler like try and catch statement for best practices. It always breaks because of either an empty row or because of unusual patter on real page you are scraping.
scraped_data = []

for x, row in postcodes_for_urls.iterrows():
    page = requests.get("http://myurl"+(row['postcode_URL']))
    soup = BeautifulSoup(page.content, 'html.parser')
    table = soup.find('table')

    if table is not None and len(table.find_all('tr'))>0:
        table_rows = table.find_all('tr')
        for tr in table_rows:
            td = tr.find_all('td')
            row = [tr.text for tr in td]
            scraped_data.append(row)
    else:
        scraped_data.append('EMPTY')

pd.DataFrame(scraped_data, columns=["A", "B", "C"])


text:
Q: Camel JSON array body I have a JSON array in the route, tell me how can I call the rest service by passing the id array parameter there and call the rest as many times as there are "userID" elements in the array?
 {"data": [
    {
        "userID": 8053,
        "userDisplayName": "User 1",
        "eMail": "user1@mail.com",
        "year": 2019,
        "month": 5,
        "dayNum": 21,
        "startTimeAvg": 60328,
        "endTimeAvg": 60617,
        "durationSum": 289,
        "activeTimeSum": 289,
        "unproductivity": 289
    },
    {
        "userID": 9063,
        "userDisplayName": "User 2",
        "eMail": "user2@mail.com",
        "year": 2018,
        "month": 4,
        "dayNum": 15,
        "startTimeAvg": 60328,
        "endTimeAvg": 60617,
        "durationSum": 289,
        "activeTimeSum": 500,
        "unproductivity": 500
    },
    {
        "userID": 6548,
        "userDisplayName": "User 3",
        "eMail": "user3@mail.com",
        "year": 2020,
        "month": 5,
        "dayNum": 18,
        "startTimeAvg": 60328,
        "endTimeAvg": 60617,
        "durationSum": 289,
        "activeTimeSum": 300,
        "unproductivity": 300
    }
]}

Already done, there is a route that calls the rest service and writes the response parameters to the database. Now I need to call the second service using the userID from the body of the first call in the parameters. Tell me how can I do this?
 from("timer://foo?fixedRate=true&period=60000").
            log(LoggingLevel.INFO, "Cron job kicked off").
            setHeader(Exchange.HTTP_METHOD, constant("GET")).
            setHeader(Exchange.CONTENT_TYPE, constant("application/json")).
            setHeader(Exchange.HTTP_QUERY, constant("selectFields=userID,userDisplayName,year,month,dayNum,startTimeAvg,endTimeAvg,durationAvg,activeTimeSum,unproductivity")).
           to("http://172.27.79.78:8900/rest/SearchInform/1.0/api/v2/report_center/reports/user_activity").
            unmarshal(new JacksonDataFormat(JsonList.class)).
            log("MESSAGE BODY!!!!!  ${body.getData.size()}
            Split: ${body.getData.size()}").
            loop(simple("${body.getData.size()}")).

    to("sql:insert into XX_DSS_SI.USER_ACTIVITY values " +
    "(:#${body.getData.get(${exchangeProperty.CamelLoopIndex}).getUserID}," +
    ":#${body.getData.get(${exchangeProperty.CamelLoopIndex}).getUserDisplayName}," +
    ":#${body.getData.get(${exchangeProperty.CamelLoopIndex}).geteMail}).getUnproductivity})" +
    "?dataSource=#exampleDatasource").

      end().
      to( "direct:endFirstRout");

A: try to set json property
[JsonProperty("userID")]
public string Id {get;set;}


text:
Q: Is an array required to be initialized if I will read file contents into it? I am initializing buf unnecessarily with all zeros before immediately writing over its contents with read_exact:
fn parse<R: Read>(r: &mut R) -> Result<()> {
    let mut buf = [0u8; 1024];
    r.read_exact(&mut buf)?;
    // Do things to buf
    Ok(true)
}

While I don't think the 0-initialization is very time-consuming, it doesn't seem necessary. Is there a way around this?

A: Yes, such an initialization is required in safe Rust. The compiler isn't necessarily able to tell that the combination of read_exact and ? will prevent accesses to any uninitialized data from the array. The optimizing passes may make it better, but that cannot be counted on to work.
You could instead read into a Vec, which internally guarantees to never allow access to the uninitialized memory:
fn parse<R: Read>(r: &mut R) -> io::Result<()> {
    let mut buf = vec![]; // Can optionally use `Vec::with_capacity`
    r.take(1024).read_to_end(&mut buf)?;
    // Do things to buf
    Ok(())
}

In unsafe Rust, you can use mem::uninitialized. Make sure you understand all the terrible little nuances involved before choosing such a situation! Reading uninitialized memory is undefined behavior in Rust, so you must make absolutely sure that you prevent it from ever happening.
Here, we rely on:

*

*The fact that read_exact will return an error if it didn't populate all of the bytes.

*The fact that the destructor of [u8; 1024] will not read the bytes. This is important path to consider when an error occurs or if a panic is raised.

fn parse<R: Read>(r: &mut R) -> io::Result<()> {
    unsafe {
        let mut buf: [u8; 1024] = mem::uninitialized();
        r.read_exact(&mut buf)?;
        // Do things to buf
    }
    Ok(())
}

I wouldn't think this is would be worth it without heavy profiling.

A: There is currently no way to do this with read_exact in Rust outside of unsafe blocks. However, you can probably get what you want in this particular case by using std::io::BufReader::with_capacity instead of allocating your own mut [u8].
If you don't care about being able to set the buffer length yourself, you could have your function require the std::io::BufRead trait for its argument instead of Read.
Either of the approaches I mentioned will allow you to use fill_buf and consume instead of read_exact, which should give you the performance you want.


text:
Q: Add a textblock to grid dynamically My grid has 2 rows, 2 columns, and I want to add a textblock dynamically to first row, second column.
This is my code, which doesnt throw an exception but it doesnt show anything
<Grid HorizontalAlignment="Left" Height="768" VerticalAlignment="Top" Width="1366">
        <Grid.RowDefinitions>
            <RowDefinition Height="150"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="250"/>
        </Grid.ColumnDefinitions>
    </Grid>

protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            TextBlock txt = new TextBlock();
            txt.Width = 200;
            txt.Height = 100;
            txt.Foreground = new SolidColorBrush(Colors.Yellow);

            var location = await InitializeLocationServices();
            txt.Text = location;

            Grid.SetRow(txt, 0);
            Grid.SetColumn(txt, 1);

        }

A: You are never adding your TextBlock to the grid. You should name your Grid (eg. x:Name="myGrid") and call myGrid.Children.Add(txt) at some point.


text:
Q: Use jQuery in Wordpress WooCommerce page to filter content in div with siblings I have a long list of documents added to wooCommerce products which I am able to show as a complete list.
I want to create a searchfield to filter the results making it much more userfriendly. Preferable with a jQuery script.
This is the output:

2C metall

Datablad

teknisk informasjon

The rendered list looks somewhat like this:
2C metall
 - Safety Document
 - Technical Document
The div containing the productname is always in a div with class-name: "woocommerce-product-documents-title".
The sibling div that contains the document list is always in a class named: woocommerce-product-documents-491 (Where 491 is a random number)
So my task is to create a livesearch using regex that search through the divs for productnames, then toggle (hide) the non-corresponding divs with siblings.
I am able to add the searchfield on top of the list using prepend:
          $(".woocommerce").prepend('Filter List');

I am able to search the divs for a productname, but I am unable to select the next sibling div. I have tried .next(), .nextAll(), .first(). My main goal is to hide all divs, then unhide the one matching the search.
anyone got a great "starter-script" ?
This is what I have got so far:
 $(".wooDocList").prepend('
Filter List<input type="text" class="wooDocFilter">
');

 $('.wooDocFilter').keyup(function(){

   // Search text
   var text = $(this).val();

   // Hide all content class element
   $('.woocommerce-product-documents-title').toggle();
   $('.woocommerce-product-documents').toggle();

  // Search
   $('.woocommerce .woocommerce-product-documents-title:contains("'+text+'")').closest('.woocommerce-product-documents-title').toggle();

  var test = $('.woocommerce .woocommerce-product-documents-title:contains("'+text+'")').next().prop("classList")
  //$('.info').text(test[0] + '!!');

  $(test[0]).toggle();
 });

A: The way that you're selecting the sibling elements is probably unnecessary, as jQuery will allow you to chain methods to selectors. So, once you have an array of elements found via $('...').next() you can call .toggle() or .show() and it will apply to all classes that match, which will also include partial matches to your search as an added bonus.
Here's the adjusted code and a link to a js fiddle (doesn't contain a search bar but you can run the script and debug through it)
$(".wooDocList").prepend('
Filter List<input type="text" class="wooDocFilter">
');

$('.wooDocFilter').keyup(function(){

  // Search text
  var text = $(this).val();

  // Hide all content class element
  $('.woocommerce-product-documents-title').hide();
  $('.woocommerce-product-documents').hide();

  // Search
  $('.woocommerce .woocommerce-product-documents-title:contains("'+text+'")').closest('.woocommerce-product-documents-title').toggle();

  // Display sibling rows
  $('.woocommerce .woocommerce-product-documents-title:contains("'+text+'")').next().toggle();
 });

Fiddle is here

A: This is my solution:
 $(".wooDocList").prepend('
Filter List<input type="text" class="wooDocFilter">
');

$('.wooDocFilter').keyup(function(){

  // Search text
  var text = $(this).val();

  // Hide all content class element
  $('.woocommerce-product-documents-title').hide();
  $('.woocommerce-product-documents').hide();

  // Search
  $('.woocommerce .woocommerce-product-documents-title:contains("'+text+'")').closest('.woocommerce-product-documents-title').toggle();

 var test = $('.woocommerce .woocommerce-product-documents-title:contains("'+text+'")').next().prop("classList")
   $('.info').text(test[0] + '!!');

 $('.'+test[0]).show();
 });


text:
Q: Handling delays when retrieving files from remote server in PHP I am working with PHP to access files and photos from remote servers.  I am mostly using the file_get_contents() and copy() functions.
Sometimes accessing a small text file or photo is almost instant, but other times it seems to get "stuck" for a minute on the same exact file.  And sometimes it actually causes my script to hang, and even when I stop the script Apache remains locked up for several minutes.
I'm quite willing to accept the fact that internet connections can be flaky.  My concern is that I recover gracefully and that I do not crash Apache - the PHP set_time_limit() function only returns a fatal error.  In addition, there is a note in the PHP manual that time spent on stream operations does not contribute to the running time of the script.
How can I recover from such connection problems and allow my script to continue?  And why would this be causing Apache to hang?
Thanks, Brian

A: $options = array( 'http' => array(
      'user_agent'    => 'Firefox wannabe',
      'max_redirects' => 1,
      'timeout'       => 10,
  ) );
$context = stream_context_create( $options );
$content = file_get_contents( $url, false, $context );

Take a look at stream_context_create and HTTP Context Options. The above code will set a timeout on the connection, and will allow for one redirect.
This should prevent reaching the timeout.
The long delays may be caused by the network or by the remote server having a firewall denying you to grab too many files at once or by a flaky DNS server or router on the path to the remote host. As a suggestion, you should cache locally the downloaded files, so on the next refresh files will be handled locally instead of the big wide net.


text:
Q: My max-width:1140px is not working it cannot be in center my margin:0 auto i am using the max-width: 1140px on the div amd use margin:0 auto it is not working in the pc , on the other hand my instructor using it it works in his laptop
i tried with 900px then it working even not working on 1000px

.divs{
    max-width: 1140px;
    margin: 0 auto;
}

max-width

A: When you set  .divs to max-width greater than body, it takes the width of body, thus  margin: 0 auto does nothing.
When max-width is smaller than , width of .divs is effectively smaller than , thus margin: 0 auto works.
This should explain why it works on some resolution and not on others.

.divs-1140px{
    max-width: 1140px;
    margin: 0 auto;
}

.divs-300px{
    max-width: 300px;
    margin: 0 auto;
}

/* Added new example using percentage */
.divs-percentage {
    max-width: 70%;
    margin: 0 auto;
}

div {
  background: green;
}

body {
  background: yellow;
}

Larger than body

Smaller Than body

Using Percentage


text:
Q: How did Pushing Daisies get its name? I've been trying to figure this one out for a while. This show is about a person who can bring back people from the dead. How would it get the name Pushing Daisies? Thanks!

A: The phrase "pushing up daisies" is often linked to Keats, who is attributed as saying:

I shall soon be laid in the quiet grave -- thank God for the quiet grave -- O! I can feel the cold earth upon me -- the daisies growing over me -- O for this quiet -- it will be my first.

(letter from Joseph Severn to John Taylor, Mar. 6, 1821).

(Image originally from Flickr)

However, the link between daisies and death (particularly innocent death) is much older than that.  The Celtic poet Ossian wrote how unborn children would return to the ground as flowers:

a woman named Malvina, who was mourning the death of her baby, was consoled by the Maidens of King Morven. Malvina was told that her child had turned into a flower with a golden disk surrounded by silvery petals. It supposedly looked like an infant playing in a field.

(text from JSTOR Plant Science, but the legend connecting daises and the spirits of dead children is common).
Daisies are thus often a choice of flower to lay on a gravesite, and partly because of this, and partly because they grow easily with no maintenance, and like many flowers flourish in a nutrient rich soil (although bodies are typically well sealed in coffins now, this was not always the case), they are very commonly found in graveyards.
The exact origin of the phrase "push up daisies" is disputed (e.g. this site claims that it dates from c1860), but it's a fairly simple step from daisies growing above the bodies of the dead to the idiom.
It is certainly at least as old as World World I, when it was used in A Terre, a poem by Wilfred Owen about the physical loss suffered by a soldier entrapped within his deteriorating body (this is only part of the poem):

O Life, Life, let me breathe, - a dug-out rat!
Not worse than ours the existences rats lead -
Nosing along at night down some safe vat,
They find a shell-proof home before they rot.
Dead men may envy living mites in cheese,
Or good germs even. Microbes have their joys,
And subdivide, and never come to death,
Certainly flowers have the easiest time on earth.
"I shall be one with nature, herb, and stone."
Shelley would tell me. Shelley would be stunned;
The dullest Tommy hugs that fancy now.
"Pushing up daisies," is their creed, you know.
To grain, then, go my fat, to buds my sap,
For all the usefulness there is in soap.
D'you think the Boche will ever stew man-soup?
Some day, no doubt, if...

As a name for a show where people come back from the dead, it's perhaps particularly apt, since "pushing up daisies" brings to mind (even if this is not the general use of the phrase) images of people rising from the grave, dislodging the daisies around it.
Note that many other expressions for death have already been used, like taking a dirt nap, the last roundup (sounds a bit too Western anyway), and most famously, six feet under, so if that's what the creators were looking for, the list narrows quickly.

A: "Pushing daisies" is an euphemism for being dead. Urban dictionary puts it this way:

Dead. Your body is dead in the ground, and being used as fertilizer by
  plants. Hence you are "pushing" plants up from the ground.

A: "Pushing up the daisies" is a pretty well known phrase in the UK. I thought it would be better known elsewhere due to the Monty Python Dead Parrot sketch "If you hadn't nailed 'im to the perch 'e'd be pushing up the daisies!".
I believe that Monty Python, and this most famous sketch in particular, is often considered to be known worldwide.

A: It's approximately the same expression as the French "fumer les pissenlits par la racine", which literally means "to smoke the daisies from their roots". When you come to think of it, both expressions are very visual and mean the same thing: to be dead.


text:
Q: Why does attempting to autofit the width of a sheet, or a single column on that sheet, fail? I have one column whose contents are truncated, and I'd like to avoid having to 2-click the right column gutter to see the data. First I tried autofitting the entire shebang:
private void PopulatePivotTableDataSheet()
{
    if (null == _produceUsagePivotDataList) return;
    AddColumnHeadingRowPivotData();
    foreach (ProduceUsagePivotData pupd in _produceUsagePivotDataList)
    {
        AddPivotData(pupd.ItemCode, pupd.ItemDescription, pupd.Unit, pupd.MonthYear, pupd.Quantity,
            pupd.TotalPrice, pupd.IsContractItem);
    }
    _xlPivotDataSheet.Cells.AutoFit();
}

...but the last line fails with "AutoFit method of Range class failed"
Then I tried applying it to just the column in question like so:
private void AddPivotData(String ItemCode, String ItemDescription, String Unit, String MonthYear, int Quantity, Decimal TotalPrice, Boolean IsContractItem)
{
    var itemCodeCell = _xlPivotDataSheet.Cells[_lastRowAddedPivotTableData + 1, 1];
    itemCodeCell.Value2 = ItemCode;

    var itemDescriptionCell = _xlPivotDataSheet.Cells[_lastRowAddedPivotTableData + 1, 2];
    itemDescriptionCell.Value2 = ItemDescription;
    itemDescriptionCell.AutoFitWidth();
    . . .

...and that last line fails with, "'System.__ComObject' does not contain a definition for 'AutoFitWidth'"
What in Sam Hill o' beans is going on here? Autofitting should be easily doable, shouldn't it?

A: This will apply AutoFit to the columns comprising the range:
_xlPivotDataSheet.Cells.EntireColumn.AutoFit();


text:
Q: kafka.producer.async.DefaultEventHandler - Failed to send requests for topics I've been struggling for days trying to make a really simple application with a kafka broker and a kafka producer running on localhost, I've read all the possible answers to similar problems on google but still I couldn't make it work.
This is the error I get:
INFO  kafka.client.ClientUtils$ - Fetching metadata from broker id:0,host:localhost,port:9092 with correlation id 0 for 1 topic(s) Set(clicks)
[ProducerSendThread-] INFO  kafka.producer.SyncProducer - Connected to localhost:9092 for producing
[ProducerSendThread-] INFO  kafka.producer.SyncProducer - Disconnecting from localhost:9092
[ProducerSendThread-] WARN  kafka.producer.BrokerPartitionInfo - Error while fetching metadata [{TopicMetadata for topic clicks ->
No partition metadata for topic clicks due to kafka.common.LeaderNotAvailableException}] for topic [clicks]: class kafka.common.LeaderNotAvailableException
[ProducerSendThread-] INFO  kafka.client.ClientUtils$ - Fetching metadata from broker id:0,host:localhost,port:9092 with correlation id 1 for 1 topic(s) Set(clicks)
[ProducerSendThread-] INFO  kafka.producer.SyncProducer - Connected to localhost:9092 for producing
[ProducerSendThread-] INFO  kafka.producer.SyncProducer - Disconnecting from localhost:9092
[ProducerSendThread-] WARN  kafka.producer.BrokerPartitionInfo - Error while fetching metadata [{TopicMetadata for topic clicks ->
No partition metadata for topic clicks due to kafka.common.LeaderNotAvailableException}] for topic [clicks]: class kafka.common.LeaderNotAvailableException
[ProducerSendThread-] ERROR kafka.producer.async.DefaultEventHandler - Failed to collate messages by topic, partition due to: Failed to fetch topic metadata for topic: clicks
[ProducerSendThread-] INFO  kafka.producer.async.DefaultEventHandler - Back off for 100 ms before retrying send. Remaining retries = 3

And this is my code:
Properties properties= new Properties();
properties.put( "broker.id", "1");
properties.put( "advertised.host.name", "localhost");
properties.put( "advertised.port", "9092");
properties.put( "host.name", "localhost");
properties.put( "auto.create.topics.enable","true");
properties.put("zookeeper.connect", zookeeperConnectString);
properties.put("port","9092");
properties.setProperty("num.partitions", "1");
properties.setProperty("log.dirs", newPath(KAFKA_LOG_DIR).toString());

KafkaConfig kafkaConfig = new KafkaConfig(properties);
KafkaServerStartable kafkaServer = new KafkaServerStartable(kafkaConfig);
kafkaServer.startup();

String topic = clicks;

ZkClient zookeeper = new ZkClient(zookeeperConnectString, 30000, 30000, ZKStringSerializer$.MODULE$);
if (!AdminUtils.topicExists(zookeeper, topic)) {
   AdminUtils.createTopic(new ZkClient(zookeeperConnectString), topic, 1, 1, new Properties());
    }
zookeeper.close();

Properties producerProps = new Properties();
producerProps.put("serializer.class", "kafka.serializer.StringEncoder");
producerProps.put("key.serializer.class", "kafka.serializer.StringEncoder");
producerProps.setProperty("producer.type", "async");
producerProps.put("metadata.broker.list", "localhost:9092");
producerProps.put("request.required.acks","0");

Producer producer = new Producer(new ProducerConfig(producerProps));

String click = "exampleMessage";
producer.send(ImmutableList.of(new KeyedMessage(topic, click)));
producer.close();

I already have a zookeeper instance correctly running on localhost:2181.
I'm using the following versions of kafka and zookeeper:
<dependency>
      <groupId>org.apache.kafka</groupId>
      <artifactId>kafka_2.10</artifactId>
      <version>0.8.2.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.kafka</groupId>
      <artifactId>kafka-clients</artifactId>
      <version>0.8.2.2</version>
    </dependency>
  <dependency>
      <groupId>org.apache.zookeeper</groupId>
      <artifactId>zookeeper</artifactId>
      <version>3.4.6</version>
    </dependency>

Thanks for any help or comment :)

A: In case somebody has encountered the same issue, I made it work adding  Thread.sleep(500); after the creation of the topic. I don't know exactly why, it may be due to the instance of Zookeeper running on localhost that takes some time to initialize.


text:
Q: Do Spring transactions propagate through new instantiations I'm working on a bunch of legacy code written by people before me and I'm confused about a particular kind of setup and wonder if this has ever worked to begin with.
There is a managed bean in spring that has a transactional method.
  @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Throwable.class)
  public boolean updateDraftAndLivePublicationUsingFastDocumentsOfMySite(List<FastDocumentLite> fastDocumentLites, Long mySiteId) throws Exception { ... }

Now inside that method I find new instantiations calling update methods fe:
 boolean firstFeed = new MySiteIdUpdate(publishing, siteDao, siteDomainService).update(siteId, fastDocumentLites.get(0).getMySiteId());

From my understanding on IOC this new class isn't managed by spring , it's just a variable in the bean.  Now going further inside the update method you see another service gets called.
  @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Throwable.class)
  public void activateSubdomainForSite(Long siteId, boolean activationOfSite)

So if there is a transaction open it should be propagated into this service.  But here is what I don't get if that MySiteIdUpdate object isn't managed by spring does the first transaction move forward to the activateSubdomainForSite method ??  Or is another transaction being opened here.  I looked in the logs and I believe it to be the latter but I rather ask the experts for a second oppinion before I proclame this legacy code to be complete rubbish to the project lead.  I'm suffering with a StaleStateException somewhere further down the road and I'm hoping this has anything to do with it.

A: I think the code is correct, and the second @Transactional should reuse the existing transaction.
Because:
1) Spring Transaction handling is done either by Proxies or by AspectJ advices. If it is done by Proxies then it is required that MySiteIdUpdate invoke an instance that is injected (this is what you did). If you use AspectJ, then it should work anyway.
2) The association Transactions to the code that use is done by the Thread, this mean, as long as you "are" in the thread which started the transaction you can use it. (you do not start an new thread, so it should work)

An other way to explain: It is perfect legal when you have some method in your call hierarchy that does not belong to an spring bean. This should not make the transaction handling fail.


text:
Q: Auto Scan at set intervals and populate SharePoint 2010 List Hi can anyone Help me!
I want something that I am able to select a different SharePoint List every week.
within that list select the columns that apply (Monday to Friday or just monday),
I then need it to scan at set intervals(Seconds) the columns selected.
when it detects an blank entry, in one or all of the columns selected.
It will inputs some data in to that field automatically
is this even possible?
Thanks
maddie

A: Yon can use the Timer job for this requirement.

*

*Place all your configuration in one list

*Configure the timer job at time you need to run

*write the custom code  as per your requirement

Please find the below link  for step by step walkthrough
Custom Timer Job in SharePoint 2010


text:
Q: Cucumber with Capybara, how to embed screenshot into report for each step? I know how to take screenshot after a failed scenario, but how do I take screenshot after each step and embed it in report?
AfterStep do |scenario|
  screenshot =  "#{SecureRandom.urlsafe_base64}.png"
  page.save_screenshot(screenshot)
  embed(screenshot, "image/png", "SCREENSHOT")
  FileUtils.rm_rf(screenshot)
end

The screenshot is saved successfully, but embed method does not exist in that context. I know embed method is defined in the reporter class, how do I get hold of the reporter class in the hooks?

A: actually my question was invalid.
the embed method does exist in AfterStep hook. the problem I had was probably related to some browser startup issue.


text:
Q: FastCGI - Rewrite - Location with Nginx I just switched to nginx but I'm having trouble with my URL-Rewriting
I used
location /id/ {
       rewrite ^/id/(.*) /index.php?id=$1 break;
}

But the php code is not interpreted, worst it's downloaded raw.
Yet .php files are configured as follow:
    location ~ \.php$ {
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /var/www/my_app$fastcgi_script_name;
            include /etc/nginx/fastcgi_params;
    }

What is wrong with my vhost ?
EDIT: Here is the entire vhost
server {
    listen   80; ## listen for ipv4
    server_name  viditx.com www.viditx.com; ## change this to your own domain name

   # I find it really useful for each domain & subdomain to have
   # its own error and access log
    error_log /var/log/nginx/viditx.com.error.log;
    access_log  /var/log/nginx/viditx.com.access.log;
root /var/www/viditx;

location / {
        # Change this to the folder where you want to store your website
        index  index.html index.htm index.php;
}
location /phpmyadmin {
           root /usr/share/;
           index index.php index.html index.htm;
           location ~ ^/phpmyadmin/(.+\.php)$ {
                   try_files $uri =404;
                   root /usr/share/;
                   fastcgi_pass 127.0.0.1:9000;
                   fastcgi_index index.php;
                   fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                   include /etc/nginx/fastcgi_params;
           }
           location ~* ^/phpmyadmin/(.+\.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt))$ {
                   root /usr/share/;
           }
    }
    location /phpMyAdmin {
           rewrite ^/* /phpmyadmin last;
    }

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;

    location = /50x.html {
            root   /var/www/nginx-default;
    }

    location ~ \.php$ {
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            # again, change the directory here to your website's root directory
            # make sure to leave $fastcgi_script_name; on the end!
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include /etc/nginx/fastcgi_params;
    }

}

A: You should try :
location /id/ {
       rewrite '^/id/(.*)$' /index.php?id=$1 break;
}

and :
location ~ \.php$ {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index   index.php;
    fastcgi_param   SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include     /etc/nginx/fastcgi_params;
}

Have fun !

A: Did you read the documentation?
break -> last:
location /id/ {
    rewrite ^/id/(.*)$ /index.php?id=$1 last;
}


text:
Q: Lua not recognized as an internal or external command, What did I do wrong? I installed Lua using "winget install "lua for windows"" It says it installed but when I type lua and also lua53, or lua54 at command prompt it tells me "lua is not recognized as an internal or external command, operable program or batch file"

I installed the file using the installer, and expected the lua version to be displayed when I entered lua at the command prompt.

A: run from cmd:
echo %path%

and see, the output should contain a path like this:
C:\Program Files\Lua\5.1;C:\Program Files\Lua\5.1\clibs;C:\Program Files\Lua\5.1\include;

add if needed:
set PATH=%PATH%;C:\Program Files\Lua\5.1;C:\Program Files\Lua\5.1\clibs;C:\Program Files\Lua\5.1\include

A: Lua has to be capitalized to run!


text:
Q: How can solve the ERROR [BABEL] maximum size 500KB issue in server? I am using NUXTJS application for an SSR page, but i am getting an error of bootstrap-vue icon size issue.
The file is hosted in AWS server and this will be the error
The code generator has deoptimised the styling of
/var/www/html/my_folder/node_modules/bootstrap-vue/src/icons/icons.js
as it exceeds the max of 500KB.

What will be the issue on this ? i have added babbel in build location too..

A: you can add it like this and it works,just added in your nuxt.config.js file
  build: {
     babel: {
      compact: true,
     },
  },

A: Try to add
babel: { compact: true }
below extend(config, ctx) {}, like this
....
 /*
 ** You can extend webpack config here
 */
 extend(config, ctx) {},
 babel: { compact: true }

ref: https://github.com/bootstrap-vue/bootstrap-vue/issues/5627#issuecomment-668487772
Edit: edit this on nuxt.config.js file


text:
Q: Use of uninitialized value within @spl in substitution (s///) I am getting following error while running the script.
Use of uninitialized value in print at PreProcess.pl line 137.
Use of uninitialized value within @spl in substitution (s///) at PreProcess.pl line 137.

Is there any syntax error in the script?
(Running it in Windows - Strawberry 64 last version)
my $Dat=2;
my $a = 7;
foreach  (@spl) {
    if ( $_ =~ $NameInstru ) {
        print $spl[$Dat] =~ s/-/\./gr, " 00:00; ",$spl[$a],"\n";    # data
        $Dat += 87;
        $a += 87;
    }
}

inside of array i hve  this type of data
"U.S. DOLLAR INDEX - ICE FUTURES U.S."
150113
2015-01-13
098662
ICUS
01
098
  128104
   14111
   88637
     505
   13200
      50
     269
   43140
   34142
    1862
   37355
     482
     180
  110623
  126128
   17480
    1976
    1081
   -3699
    8571
    -120
     646
      50
     248
    1581
   -8006
     319
    2093
      31
     -30
    1039
    1063
      42
      18
  100.0
   11.0
   69.2
    0.4
   10.3
    0.0
    0.2
   33.7
   26.7
    1.5
   29.2
    0.4
    0.1
   86.4
   98.5
   13.6
    1.5
    215
      7
.
.
     16
.
.
     50
     16
      8
    116
      6
      4
    197
     34
    28.6
    85.1
    41.3
    91.3
    28.2
    85.1
    40.8
    91.2
"(U.S. DOLLAR INDEX X $1000)"
"098662"
"ICUS"
"098"
"F90"
"Combined"

"U.S. DOLLAR INDEX - ICE FUTURES U.S."
150106
2015-01-06
098662
ICUS
01
098
  127023
   17810
   80066
     625
   12554
       0
      21
   41559
   42148
    1544
   35262
     452
     210
  109585
  125065
   17438
    1958
   19675
     486
   23911
      49
    2717
       0
     -73
    9262
   -5037
      30
    5873
     270
      95
   18439
   19245
    1237
     431
  100.0
   14.0
   63.0
    0.5
    9.9
    0.0
    0.0
   32.7
   33.2
    1.2
   27.8
    0.4
    0.2
   86.3
   98.5
   13.7
    1.5
    202
      7
.
.
     16
      0
.
     48
     16
      9
    105
      6
      4
    185
     34
    29.3
    83.2
    43.2
    90.6
    28.9
    83.2
    42.8
    90.5
"(U.S. DOLLAR INDEX X $1000)"
"098662"
"ICUS"
"098"
"F90"
"Combined"

A: You are probably trying to load a file of data sets of a size of 87 lines each into an array, and then you get an error at the end of your data, when you try to read outside of the last array index.
You can probably solve it by iterating over the array indexes instead of the array values, e.g.
my $Dat = 2;
my $a = 7;
my $set_size = 87;

for (my $n = 0; $n + $a < @spl; $n += $set_size) {
    if ( $spl[$n] =~ $NameInstru ) {
        print $spl[$n + $Dat] =~ s/-/\./gr, " 00:00; ",$spl[$n + $a],"\n";    # data
    }
}

While this might solve your problem, it might be better to try and find a proper way to parse your file.
If the records inside the input file are separated by a blank line, you can try to read whole records at once by changing the input record separator to "" or "\n\n". Then you can split each element in the resulting array on newline \n and get an entire record as a result. For example:
$/ = "";
my @spl;
open my $fh ...
while (<$fh>) {
    push @spl, [ split "\n", $_ ];
}

...

for my $record (@spl) {
    # @$record is now an 87 element array with each record in the file
}

A: TLP's solution of iterating over the indexes of an array, incrementing by 87 at time is great.
Here's a more complex solution, but one that doesn't require loading the entire file into memory.
my $lines_per_row = 87;

my @row;
while (<>) {
   chomp;
   push @row, $_;
   if (@row == $lines_per_row) {
      my ($instru, $dat, $a) = @row[0, 2, 7];
      if ($instru =~ $NameInstru) {
         print $dat =~ s/-/\./gr, " 00:00; $a\n";
      }

      @row = ();
   }
}


text:
Q: Can we initialize a list from a specific index in lazy column? I want to initialize a list from a specific index in lazy column.
For example: I have a list of 10 items. I want the list to load from 5. index when first loaded.
The method I'm using now is to scroll to the 5th index after loading the list. But instead I want to initialize the list directly from an index I want. Is it possible?

A: you can use itemsIndexed() extension and filter the list
LazyColumn() {
    itemsIndexed(viewModel.list) { index, item ->
        if(index >5){
           // your composable here
        }
    }
}


text:
Q: Cluster marker on Google Map I'm not much experienced in Google Map API work but now I'm going to try it.
Currently I'm trying to create an application where user can select location type like
Restaurant, theater etc..when user will click on theater link he'll get all the theater's markers over the map around his current location and when he'll click on restaurant he'll get all the Restaurant's markers over the map along with theater's markers. I do have some lat/long details to test it.
For that I'm using Google Map API's cluster marker but now problem is that when I click on restaurant then theater marker is getting converted to restaurant marker icons.
My question is that is there any other good method to do this kind of application or I should use the same method. If yes then how to do that?

A: I think,It's useful to You.I have tried following Api working fine.and I prepared following links.and i have used to IOS application and android.
API:
https://maps.googleapis.com/maps/api/place/search/xml?location=11.033538,76.958542&radius=50000&types=restaurant&sensor=false&key=AIzaSyBbFJq2_okjiRn4duMJwDCZvYoVrM_Tbtg

Api used to authentication key and developing API formate
Supported Type


text:
Q: Overlapping while replacing one fragment with another I have been trying to replace the fragment with another fragment if user clicks on one of the list item. Now the problem is the other fragment is getting displayed but it is not replacing previous frame but it is just getting displayed on top of the previous fragment. This is how I am calling my new fragment on list item click:
            public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

            String sender = ((TextView) view.findViewById(R.id.sender)).getText() .toString();
            String subject = ((TextView) view.findViewById(R.id.subject)).getText() .toString();
            String fname = ((TextView) view.findViewById(R.id.file_name)).getText() .toString();

            Fragment frag =new  DisplayFragment();
            Bundle bundle = new Bundle();
            bundle.putString("file_name", fname);
             frag.setArguments(bundle);

            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.fragment_frame, frag);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();

and activity associated with this fragment is:
 <FrameLayout
    android:id="@+id/fragment_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
/>

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</ListView>

now the code for new fragment is:
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState)
{
    View rootView = inflater.inflate(R.layout.activity_displayfile, container, false);
    return rootView;

}
public void onActivityCreated(Bundle savedInstanceState)
{
    super.onActivityCreated(savedInstanceState);
    TextView tv=(TextView)getView().findViewById(R.id.textView1);
    Bundle bundle = this.getArguments();
    String myfile = (String)bundle.get("file_name");
    tv.setText(myfile);
}

and its associated activity is :
<FrameLayout
    android:id="@+id/display_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
>
<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</FrameLayout>

the desired output should be the textview in new fragment should replace whole content of previous fragment. but the output after clicking item that I am getting is:

this "hi" should get displayed alone not with the list. It seems my code is correct. Thanks in advance.

A: Issue here is that you have a frame layout n a list view in a single view. You are replacing your frame with the fragment but your list view is still there.

*

*Use fragment in your xml instead of frame layout and list view

*Create a list fragment

*On create of activity add list fragment to the view

*On list item click replace list fragment with your fragment.

Hope this helps.


text:
Q: if statement with geting the last character of a String in Android Studio java My code need the if statement to see the last character of some string but how many time i try nothing happens, that mean the conduction is false !.
my code:
            String zzz = T2.getText().toString();
            String zz = zzz.substring(zzz.length() - 1);

            String oo = "+";
            if ( zz ==  oo){
                T1.setText(" the result ");
            }
            ..
            String Add1 = T1.getText().toString();
            AAAA11111 = AAAA11111 + Double.parseDouble(Add1);
            T2.setText(Double.toString(AAAA11111) + " +"); // the last character is "+" and it's what i needed
            ..

A: For string comparison use equals method:
zz.equals(oo)

In this answer you will find a very good explanation about the difference between using the "==" operator and the equals method for string comparison.

A: If you only want to check the last character of the string, It also works!
char lastChar = zzz.charAt(zzz.length() - 1);

if (lastChar == '+') {
    // Do something
}


text:
Q: Read DOCX files using javascript in sharepoint 2013 Can we fetch contents of DOCX files uploaded in a doc library from javascript code ?  I could easily read a TXT file ref : http://msdn.microsoft.com/en-us/library/office/jj163201(v=office.15).aspx .
Any pointers on how to read contents of a DOCX through javascript object model/REST API

A: There is no OOTB tool/service available to read word files in Sharepoint online.
For workaround you must have download the file using client object model and then read the content of the files using INTEROP or .NET object model.


text:
Q: HikariCP with Oracle com.zaxxer.hikari.pool.HikariProxyCallableStatement cannot be cast to oracle.jdbc.OracleCallableStatement I using Hikari Pool and OracleCallableStatement:
My datasource:
<bean id="myDataSource" class="com.zaxxer.hikari.HikariDataSource">
      <property name="jdbcUrl" value="${my.oracle.url}"/>
      <property name="driverClassName" value="oracle.jdbc.pool.OracleDataSource"/>
      <property name="username" value="${my.oracle.user}"/>
      <property name="password" value="${my.oracle.password}"/>
</bean>

And I try make a request to Oracle:
 public List getProducts(int numbersMonths, Long initServiceId,
List<Long> serviceIds) throws SQLException {
        Connection cnn = null;
        OracleCallableStatement stm = null;
        ResultSet rs = null;
        List<ProductLink> res = new ArrayList<>();
        final String sql = sqlCust(sqlProducts);
        try {
            cnn = custDataSource.getConnection();
            stm = (OracleCallableStatement) cnn.prepareCall(sql);
            stm.setPlsqlIndexTable(1, serviceIds.toArray(), serviceIds.size(), serviceIds.size(), OracleTypes.BIGINT, 0);
            stm.registerOutParameter(2, OracleTypes.CURSOR);
            stm.setLong(3, initServiceId);
            stm.setInt(4, numbersMonths);
            stm.execute();
            rs = stm.getCursor(2);
            // do stuff
} catch (SQLException ex) {
            DbUtils.closeQuietly(cnn, stm, rs);
            throw ex;
        } finally {
            DbUtils.closeQuietly(cnn, stm, rs);
        }

But I have error om this line: stm = (OracleCallableStatement) cnn.prepareCall(sql);
java.lang.ClassCastException: com.zaxxer.hikari.pool.HikariProxyCallableStatement cannot be cast to oracle.jdbc.OracleCallableStatement

Also I have a error:
Failed to create instance of driver class oracle.jdbc.pool.OracleDataSource, trying jdbcUrl resolution
java.lang.ClassCastException: oracle.jdbc.pool.OracleDataSource cannot be cast to java.sql.Driver

on this line: cnn = custDataSource.getConnection();
What is wrong? Why I getting this errors?

A: In fact, since you are using a connection pool, the CallableStatement implementation is not from the driver, but from that connection pool instead.
Either you should find a way to access the core implementation (which I think is risky), or you should try to use the CallableStatement only, and not depend on Oracle implementation.

A: Use CallableStatement instead

The interface used to execute SQL stored procedures. The JDBC API provides a stored procedure SQL escape syntax that allows stored procedures to be called in a standard way for all RDBMSs.

This is used by prepareCall method

Creates a CallableStatement object

A: Try replacing the line
            stm = (OracleCallableStatement) cnn.prepareCall(sql);

with
            stm = cnn.prepareCall(sql).unwrap(OracleCallableStatement.class);


text:
Q: amchart generating a pie chart, need different colors and labels to be set inside the slices I am using amcharts, for generating a pie chart with the label inside.
I tried many attempts but it didn't come properly. Here is my fiddle
 AmCharts.makeChart("chart4", {
           "type": "pie",
           "theme": "light",
           "labelRadius": -35,
           "labelText": "[[percents]]%",
           "dataProvider": [ {
             "country": "Used Space",
             "fillColor":"#0000ff",
             "litres": 84
           },
           {
           "country": "Free Space",
            "color":"#33cc33",
             "litres": 16
             }],
           "valueField": "litres",
           "titleField": "country",
           "outlineAlpha": 0.4,
           "depth3D": 12,
           "outerRadius":35,
           "angle": 40,
           "labelsEnabled": false,
           "autoMargins": false,
  "marginTop": 0,
  "marginBottom": 0,
  "marginLeft": 8,
  "marginRight": 8,
  "pullOutRadius": 0,

            "balloon":{
            "fixedPosition":true
           },
           "export": {
             "enabled": true,
            menu:[]
           }
         } );

         // generate some random data, quite different range
         function generateChartData() {
             var chartData = [];

            chartData = [{"date" : "09/11/2018 0:00", "diskSpaceUsage" : "84"},{"date" : "09/11/2018 1:00", "diskSpaceUsage" : "84"},{"date" : "09/11/2018 2:00", "diskSpaceUsage" : "84"},{"date" : "09/11/2018 3:00", "diskSpaceUsage" : "84"},{"date" : "09/11/2018 4:00", "diskSpaceUsage" : "84"},{"date" : "09/11/2018 5:00", "diskSpaceUsage" : "84"},{"date" : "09/11/2018 6:00", "diskSpaceUsage" : "84"},{"date" : "09/11/2018 7:00", "diskSpaceUsage" : "84"},{"date" : "09/11/2018 8:00", "diskSpaceUsage" : "83.75"},
            {"date" : "09/11/2018 9:00", "diskSpaceUsage" : "83"},{"date" : "09/11/2018 10:00", "diskSpaceUsage" : "83"},{"date" : "09/11/2018 11:00", "diskSpaceUsage" : "83"},{"date" : "09/11/2018 12:00", "diskSpaceUsage" : "83"},{"date" : "09/11/2018 13:00", "diskSpaceUsage" : "83"},{"date" : "09/11/2018 14:00", "diskSpaceUsage" : "83"},{"date" : "09/11/2018 15:00", "diskSpaceUsage" : "83"},{"date" : "09/11/2018 16:00", "diskSpaceUsage" : "83"},{"date" : "09/11/2018 17:00", "diskSpaceUsage" : "83"},{"date" : "09/11/2018 18:00", "diskSpaceUsage" : "83"},
            {"date" : "09/11/2018 19:00", "diskSpaceUsage" : "83"},{"date" : "09/11/2018 20:00", "diskSpaceUsage" : "83"},{"date" : "09/11/2018 21:00", "diskSpaceUsage" : "83"},{"date" : "09/11/2018 22:00", "diskSpaceUsage" : "83.5"},{"date" : "09/11/2018 23:00", "diskSpaceUsage" : "84"},
            {"date" : "09/12/2018 0:00", "diskSpaceUsage" : "84"},{"date" : "09/12/2018 1:00", "diskSpaceUsage" : "84"},{"date" : "09/12/2018 2:00", "diskSpaceUsage" : "84"},{"date" : "09/12/2018 3:00", "diskSpaceUsage" : "84"},{"date" : "09/12/2018 4:00", "diskSpaceUsage" : "84"},{"date" : "09/12/2018 5:00", "diskSpaceUsage" : "84"},{"date" : "09/12/2018 6:00", "diskSpaceUsage" : "84"},{"date" : "09/12/2018 7:00", "diskSpaceUsage" : "84"},{"date" : "09/12/2018 8:00", "diskSpaceUsage" : "84"},{"date" : "09/12/2018 9:00", "diskSpaceUsage" : "84"},{"date" : "09/12/2018 10:00", "diskSpaceUsage" : "84"}];

             return chartData;
         }

I need to set the colors for both the parts, and the labels should be displayed inside the slices. Any suggestions would be highly appreciated !

A: to change the slice colors, use option colors
"colors": ['red', 'green'],

to display slice labels, set option labelsEnabled to true
"labelsEnabled": true,

see following working snippet...

AmCharts.makeChart("chartdiv", {
  "type": "pie",
  "theme": "light",
  "colors": ['red', 'green'],
  "labelRadius": -35,
  "labelText": "[[percents]]%",
  "dataProvider": [ {
    "country": "Used Space",
    "litres": 84
  },
 {
   "country": "Free Space",
    "litres": 16
  }],
  "valueField": "litres",
  "titleField": "country",
  "outlineAlpha": 0.4,
  "depth3D": 12,
  "outerRadius":35,
  "angle": 40,
  "labelsEnabled": true,
  "autoMargins": false,
  "marginTop": 0,
  "marginBottom": 0,
  "marginLeft": 8,
  "marginRight": 8,
  "pullOutRadius": 0,

  "balloon":{
    "fixedPosition":true
  },
  "export": {
    "enabled": true,
    menu:[]
  }
} );
#chartdiv {
  width: 100%;
  height: 500px;
}

<link rel="stylesheet" href="https://www.amcharts.com/lib/3/plugins/export/export.css" type="text/css" media="all" />

A: You can either set the colors array like @WhiteHat mentioned, or if you want to specify a color for specific slices like what your code seems to be attempting to do, use colorField and have the field name match the property in your data. You can also set a labelColorField if you want to change the label color:
AmCharts.makeChart("chartdiv", {
  // ...
  colorField: "color", //property containing your color in your data
  labelColorField: "labelColor",
  dataProvider: [{
    "country": "Used Space",
    "color": "#0000ff", //color pulled from here
    "labelColor": "#efefef",
    "litres": 84
  },
    {
    "country": "Free Space",
    "color": "#33cc33",
    "labelColor": "#efefef",
    "litres": 16
  }],
  // ...
});

Like @WhiteHat said, you need to enable labels by setting labelsEnabled to true. You also need to tweak labelRadius even further and use a larger negative value to move it further inside if needed.
AmCharts.makeChart("chartdiv", {
  // ...
  labelsEnabled: true,
  labelRadius: -150,
  // ...
});

Demo:

AmCharts.makeChart("chartdiv", {
  "type": "pie",
  "theme": "light",
  "colorField": "color",
  "labelColorField": "labelColor",
  "labelRadius": -150,
  "labelsEnabled": true,
  "labelText": "[[percents]]%",
  "dataProvider": [{
      "country": "Used Space",
      "color": "#0000ff", //color pulled from here
      "labelColor": "#efefef",
      "litres": 84
    },
    {
      "country": "Free Space",
      "color": "#33cc33",
      "labelColor": "#efefef",
      "litres": 16
    }
  ],
  "valueField": "litres",
  "titleField": "country",
  "outlineAlpha": 0.4,
  "depth3D": 12,
  "outerRadius": 35,
  "angle": 40,
  "autoMargins": false,
  "marginTop": 0,
  "marginBottom": 0,
  "marginLeft": 8,
  "marginRight": 8,
  "pullOutRadius": 0,

  "balloon": {
    "fixedPosition": true
  },
  "export": {
    "enabled": true,
    menu: []
  }
});
#chartdiv {
  width: 100%;
  height: 500px;
}

<link rel="stylesheet" href="https://www.amcharts.com/lib/3/plugins/export/export.css" type="text/css" media="all" />


text:
Q: Cumulative sum while value I'm summing is unchanged I have the following data structure

Y
cum_sum

1
1

1
1

1
1

0
1

0
1

1
1

0
1

1
1

1
1

I would like to have cum_sum change so that it calculates the cumulative sum while Y is unchanged, so that the data is:

Y
cum_sum

1
1

1
2

1
3

0
1

0
2

1
1

0
1

1
1

1
2

Not sure how to do it and I've tried searching but the phrasing I'm using leads me to different questions

A: * Example generated by -dataex-. For more info, type help dataex
clear
input byte(y cum_sum)
1 1
1 1
1 1
0 1
0 1
1 1
0 1
1 1
1 1
end

replace cum_sum = cum_sum + cum_sum[_n-1] if y == y[_n-1]


text:
Q: App crashes due to no call to super.OnCreate() even when call is present in ListFragment My app crashes with the SuperNotCalledException.
I have already called super.OnCreate(savedInstanceState); in OnCreate(). Here's my code.
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get max available VM memory, exceeding this amount will throw an
    // OutOfMemory exception. Stored in kilobytes as LruCache takes an
    // int in its constructor.
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

    // Use 1/8th of the available memory for this memory cache.
    final int cacheSize = maxMemory / 8;

    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            // The cache size will be measured in kilobytes rather than
            // number of items.
            return bitmap.getByteCount() / 1024;
        }
    };

}

The app crashes with the following stacktrace.
11-07 12:56:37.807  15516-15516/com.laer.easycast D/AndroidRuntime﹕ Shutting down VM<
11-07 12:56:37.817  15516-15516/com.laer.easycast E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.laer.easycast, PID: 15516
    android.support.v4.app.SuperNotCalledException: Fragment ImagePane{64e8db70 id=0x7f090001} did not call through to super.onCreate()

Any idea what's wrong with it? I've tried hard...


text:
Q: Convert List of 1 element to Option Let's say I have a List[T] from which I need a single element, and I'd like to convert it to an Option.
val list = List(1,2,3)
list.take(1).find(_=>true) // Some(1)

val empty = List.empty
empty.take(1).find(_=>true) // None

This would appear to be somewhat of a hack ;-)
What's a better approach to converting a single element List to an Option?

A: Scala provides a headOption method that does exactly what you want:
scala> List(1).headOption
res0: Option[Int] = Some(1)

scala> List().headOption
res1: Option[Nothing] = None

A: headOption is what you need:
scala> List.empty.headOption
res0: Option[Nothing] = None

scala> List(1,2,3).take(1).headOption
res1: Option[Int] = Some(1)


text:
Q: Copy all files from one folder to another and making them read only I have a bunch of boilerplate code that I copy to a number of projects using a windows batch script.
xcopy /E/I/R/Y path\to\origin path\to\destination
I want to set the read-only attribute on files copied to the destination folder as a reminder not to edit the file as it was generated automatically.  The destination folder will contain other code also, not just the code I copy from boilerplate.
I found the command to make a file read only, attrib +r file.extension,  how can I apply the read only attribute on each file copied to the destination folder?

A: Found a way to do it in Windows 7 using robocopy.
robocopy origin destination * /e /a+:R

A: @echo off
set "origin=originfolder"
set "destination=destinationfolder"
pushd %origin%
for %%a in ("*.*") do (
copy "%%a" "%destination%"
attrib +r "%destination%\%%a")
echo/Done.&pause>nul&exit/b

This should work


text:
Q: If Column Contains String then put value for that row I have data that looks like this:
A                              B
Manager, Sales
Manager
Manager, Marketing
Manager, Marketing, Sales

How do I make column B fill-in with "Yes" or "No" if Column A contains Sales, Marketing, or Sales, or Marketing?
Final data should look like this:
A                             B
Manager, Sales                Yes
Manager                       No
Manager, Marketing            Yes
Manager, Sales, Marketing     Yes

A: Does this work:
library(dplyr)
library(stringr)
df %>% mutate(B = case_when(str_detect(A, 'Sales|Marketing') ~ 'Yes', TRUE ~ 'No'))
                          A   B
1            Manager, Sales Yes
2                   Manager  No
3        Manager, Marketing Yes
4 Manager, Marketing, Sales Yes

A: Using ifelse
df$B <- ifelse(grepl('Sales|Marketing', df$A), "Yes", "No")


text:
Q: Disable 3D warning overlay I can't find any way to disable the overlay in the screenshot below from the NVidia control panel.  The biggest pain is that my bluetooth keyboard doesn't have an insert button.
Screenshot:
"This application is not rated by NVIDIA Corp."
Requested Details:

*

*This happens for numerous games

*Windows 8

*Geforce GTX 670mx

*Games operate fine

As for the solution of adding a profile for each unrecognized game, I really don't want to go through all 800+ games in my library :(


text:
Q: Vim: regular expression to match up to a string What regular expression in Vim will match all
characters up to no. in the below sting?
foo, bar, and baz, no. 13, qux

In other words the match must be foo, bar, and baz,
I'm new with regular expressions, did my research here on Stack
Overflow, and one suggestion is .+?(?= no.).  But it seems to work
only with the regular (perl?) flavour of regular expressions, not in
Vim.
Please, help.
Maybe there's a simpler solution to what I'm trying to achieve.  My ultimate goal is to put foo, bar, and baz in curly brackets, and I planned to to a global substitution command involving regular expressions.

A: this regex in vim should do
.*\zeno

e.g. you do this on your line:
s/.*\zeno//

that line would be changed into:
no. 13, qux

EDIT
just saw your "ultimate goal", you can just use the regex:
:s/.*\zeno/{&}

if you don't want to wrap the comma:
:s/.*\ze, no/{&}

A:
My ultimate goal is to put 'foo, bar, and baz' in curly brackets

You could try
:s/\v(.*)(, no\.)/{\1}\2/

A: This should do:
.*\( no[.]\)\@=

In words, all characters up to the set of characters matching " no.".  The match look ahead, \@=, performs the check for " no.".

A: All answers given so far are wrong to me, because they perform a greedy match. In a line where there are several occurrences of "no", they will match up to the last one:
YES YES YES YES no YES YES no YES
^^^^^^^^^^^^^^^^^^^^^^^^^^^

However, the purpose when matching everything up to some string is often to stop at the first occurrence:
YES YES YES YES no YES YES no YES
^^^^^^^^^^^^^^^^

For this purpose, use a non‐greedy regular expression, such as:
.\{-}\(no\)\@=

\{-} is the non‐greedy alternative to the multiplier * (see :help non-greedy). \@= is a positive look‐ahead, it will check that "no" follows but will not include it in the match (see :help /\@= ).

As a side note, a common scenario for "matching everything up to some string" is to match an expression with opening and closing delimiters. Examples:

*

*C‐style string literals "string literal";

*C++‐style comments // comment\n (whose closing delimiter is the newline character);

*regular expressions /regex/.

In many such cases, the closing delimiter may in fact appear escaped inside the expression to be matched. For instance:

*

*A C‐style string literal may contain the double‐quote character, in which case it must appear escaped as in \".

*In a C++ comment, a newline character preceeded by a backslash is ignored, with the side effect that the comment continues on the following line.

*A regular expression may contain a slash; in an overly simplistic approach to the syntax of regular expressions, we may assume that all such occurrences are escaped as in \/ (this is not true, for example /[abc/]/ is also a valid Vim regex which matches any character among "a", "b", "c", "/").

Hence, we must refine our regular expression so that it does not stop on escaped occurrences of the closing delimiter.
Let's start with the wrong regular expression that matches anything between a starting delimiter "start" and a closing delimiter "stop" (which are not included in the match, thanks to the positive look‐behind \@<= and the positive look‐ahead \@= ):
\(start\)\@<=\_.\{-}\(stop\)\@=

The match will stop at any occurrence of "stop", even if it is escaped:
test start test \stop test stop test
          ^^^^^^^

To fix this behaviour, we may replace \_. (which matches any character, including newlines) by the disjunction of \_[^\\] (which matches any character but a backslash) and \\\_. (which matches a backslash followed by any character). This means that any non‐escaped backslash will be interpreted as the beginning of an escaping sequence. Backslashes themselves can be escaped, so that \\stop is an escaped backslash followed by a true closing delimiter.
Here is the Braille expression:
\(start\)\@<=\(\_[^\\]\|\\\_.\)\{-}\(stop\)\@=

and some tests:
test start test \stop test stop test
          ^^^^^^^^^^^^^^^^^
test start test \\stop test stop test
          ^^^^^^^^
test start test \\\stop test stop test
          ^^^^^^^^^^^^^^^^^^^


text:
Q: Is extending a factory class an anti-pattern? Let's say that there is a CarFactory class and it is extended by classes like FerrariFactory and VolvoFactory. Each class has a List<Car> build(List<CarPart>) method
Now a requirement comes up that for any given List<CarPart> the optimal list of Cars must be returned.
Would it be an anti-pattern to put the logic in CarFactory.build?
CarFactory
    List<Car> build(List<CarPart>)
        split car part list into optimal car part sub-lists for each factory
        instantiate car factories and pass in the sub-list of car parts
        return collection of cars

Or would it be better to have another class like a CarBuilder class does this?. Is there a typical design pattern I can use to solve this problem?

A: I think, any logic in builder is anti pattern, because, instantiate new object should be very fast and quite.
I mean, that maximum code in builder - only one operator new ClassName(params...).
if you need any logic - move it to new small class, which solve this:
List <Car> CarFactory.build (params...) {
  return new CarLogicSolver(params).list();
}

you can see great examples in java.util.stream.Collectors.toSet, .toList, toMap etc.


text:
Q: Perturbation theory in quantum mechanics In perturbation theory perturbed eigenstates expanded by unperturbed eigenstates, but we know when the system perturbed its Hilbert space altered and hence its basis changed, then we can't state this basis spans the new Hilbert space and we can't expand perturbed eigenstates by them. How this problem resolved?
Please don't answer this question to say that it is approximately true since in textbooks this is done in exact manner.

A:
then we can't state this basis spans the new Hilbert space

There is no "new" Hilbert space. If the original basis of space $L_2(x\in \mathbb{R})$ consisting of eigenfunctions of $\hat{H}$ is complete, any admissible function $\psi$ can be expanded, eigenfunctions of $\hat{H}+\hat{H}{}'$ including.

A:
In perturbation theory perturbed eigenstates expanded by unperturbed eigenstates,

Yes, they are!

but we know when the system perturbed its Hilbert space altered and hence its basis changed,

Having a basis means that any vector is expanded by those. Thus, in general, the new eigenvectors are a linear combination of the former.

then we can't state this basis spans the new Hilbert space and we can't expand perturbed eigenstates by them.

The system is the same, your Hilbert space is unchanged. However, the eigenvectors have changed. What you must do is find the new set of eigenvectors, which can be expressed as combination of the former eigenvectors.

Please don't answer this question to say that it is approximately true since in textbooks this is done in exact manner.

You're wrong. It IS an approximate solution, it needs to be computed order by order. However, there are a few examples were the perturbative solution (up to certain order) is the exact solution, but it is not the rule! [a typical example is a charges harmonic oscillator in the presence of a constant electric field].