text:
Q: Build a tags list using UICompositional layout iOS | Remove empty space within groups I am building a list that contains hashtags using the UICompositionalLayout, I have managed to achieve dynamic-sized cells in my sections using the estimated metrics. Which looks like this

However, I want to remove the empty spaces between the tags and have a continuous stream spanning over two rows. Here is how I am building my layout section
let itemSize = NSCollectionLayoutSize(widthDimension: .estimated(120), heightDimension: .absolute(44))
        let layoutItem = NSCollectionLayoutItem(layoutSize: itemSize)
        layoutItem.contentInsets = NSDirectionalEdgeInsets(top: 5, leading: 5, bottom: 5, trailing: 5)
        let layoutGroupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.43), heightDimension: .fractionalWidth(0.35))
        let layoutGroup = NSCollectionLayoutGroup.vertical(layoutSize: layoutGroupSize, subitems: [layoutItem])
        let layoutSection = NSCollectionLayoutSection(group: layoutGroup)
        layoutSection.orthogonalScrollingBehavior = .continuous
        return layoutSection

Thanks a lot for your help!

A: UI components are great -- until they're not.
Something such as a UICollectionView is designed to layout and manage a large number of items (cells).
When the layout doesn't match the desired layout, though, it can become a fight against the built-in design of the component. That's the case here.
As you know, by default, a horizontal scrolling collection view aligns the cells like this:

Trying to get the cells left-aligned with equal spacing from row-to-row is not easy, whether using Flow or Compositional layout.
You might want to take a different approach -- here's one idea...
We'll start with a simple "self-selectable Tag View":
class MyTagView: UIView {

    public var selectChanged: ((MyTagView) ->())?

    public var text: String = "" {
        didSet {
            theLabel.text = text
        }
    }

    public var normalForegroundColor: UIColor = UIColor(red: 78.0 / 255.0, green: 164.0 / 255.0, blue: 145.0 / 255.0, alpha: 1.0)
    public var normalBackgroundColor: UIColor = .white
    public var highlightForegroundColor: UIColor = .lightGray
    public var highlightBackgroundColor: UIColor = UIColor(red: 78.0 / 255.0, green: 164.0 / 255.0, blue: 145.0 / 255.0, alpha: 1.0)

    private let theLabel: UILabel = {
        let v = UILabel()
        v.textAlignment = .center
        return v
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    func commonInit() -> Void {
        backgroundColor = normalBackgroundColor
        theLabel.textColor = normalForegroundColor
        theLabel.translatesAutoresizingMaskIntoConstraints = false
        addSubview(theLabel)
        let g = self
        NSLayoutConstraint.activate([
            theLabel.topAnchor.constraint(equalTo: g.topAnchor, constant: 4.0),
            theLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 8.0),
            theLabel.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -8.0),
            theLabel.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -4.0),
            theLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: 40.0),
        ])
        layer.cornerRadius = 8
        layer.borderWidth = 1
        layer.borderColor = normalForegroundColor.cgColor

        let t = UITapGestureRecognizer(target: self, action: #selector(gotTap(_:)))
        addGestureRecognizer(t)
    }
    @objc func gotTap(_ sender: Any?) {
        selected.toggle()
        selectChanged?(self)
    }
    var selected: Bool = false {
        didSet {
            if selected {
                backgroundColor = normalForegroundColor
                theLabel.textColor = normalBackgroundColor
                layer.borderColor = normalBackgroundColor.cgColor
            } else {
                backgroundColor = normalBackgroundColor
                theLabel.textColor = normalForegroundColor
                layer.borderColor = normalForegroundColor.cgColor
            }
        }
    }
}

which gives us this:

It also has a closure so we can inform its parent / controller when the selected state has changed.
Next we'll create a "Tags View" that will use a vertical stack view with horizontal "row" stack views to layout the tags:
class MyTagsView: UIView {

    public var delegate: MyTagsViewDelegate?

    public var tagViews: [MyTagView] = []

    var theTags: [String] = [] {
        didSet {
            // clear existing (in case we're setting the tags multiple times)
            vStack.arrangedSubviews.forEach { v in
                v.removeFromSuperview()
            }
            tagViews = []
            var totalWidth: CGFloat = 0
            // create individual tag views and get the total width
            theTags.forEach { str in
                let t = MyTagView()
                t.text = "#" + str
                let sz = t.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
                totalWidth += sz.width
                tagViews.append(t)
            }

            let rowWidth: CGFloat = totalWidth / CGFloat(numRows)
            var iTag: Int = 0
            while iTag < tagViews.count {
                // create a new "row" horizontal stack view
                let v = UIStackView()
                v.spacing = 8
                vStack.addArrangedSubview(v)
                var cw: CGFloat = 0
                // add tag views
                while cw < rowWidth, iTag < tagViews.count {
                    let t = tagViews[iTag]
                    let sz = t.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
                    v.addArrangedSubview(t)
                    cw += sz.width
                    iTag += 1
                }
            }

            // set closure so we can track selections
            tagViews.forEach { tv in
                tv.selectChanged = { [weak self] theTagView in
                    guard let self = self,
                          let idx = self.tagViews.firstIndex(of: theTagView)
                    else { return }
                    if theTagView.selected {
                        self.delegate?.myTagsView(self, didSelectItemAt: idx)
                    } else {
                        self.delegate?.myTagsView(self, didDeSelectItemAt: idx)
                    }
                }
            }
        }
    }

    // number of rows of tagViews
    public var numRows: Int = 2

    // vertical stack view to hold the rows
    private let vStack: UIStackView = {
        let v = UIStackView()
        v.axis = .vertical
        v.spacing = 8
        v.alignment = .leading
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    func commonInit() -> Void {
        let scrollView = UIScrollView()
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        scrollView.addSubview(vStack)
        addSubview(scrollView)
        let g = self
        let cg = scrollView.contentLayoutGuide
        NSLayoutConstraint.activate([
            scrollView.topAnchor.constraint(equalTo: g.topAnchor, constant: 0.0),
            scrollView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 0.0),
            scrollView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: 0.0),
            scrollView.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: 0.0),

            vStack.topAnchor.constraint(equalTo: cg.topAnchor, constant: 8.0),
            vStack.leadingAnchor.constraint(equalTo: cg.leadingAnchor, constant: 8.0),
            vStack.trailingAnchor.constraint(equalTo: cg.trailingAnchor, constant: -8.0),
            vStack.bottomAnchor.constraint(equalTo: cg.bottomAnchor, constant: -8.0),

            scrollView.heightAnchor.constraint(equalTo: vStack.heightAnchor, constant: 16.0),
        ])
    }

}

It will use a protocol to allow our controller to respond to selection / deselection:
// protocol so we can tell the controller about selections
protocol MyTagsViewDelegate {
    func myTagsView(_ myTagsView: MyTagsView, didSelectItemAt index: Int)
    func myTagsView(_ myTagsView: MyTagsView, didDeSelectItemAt index: Int)
}

Our example controller will create 3 instances of MyTagsView, with 2, 3 and 4 "rows":
class MyTagsVC: UIViewController, MyTagsViewDelegate {

    let theTags: [String] = [
        "streetphotograhy", "portraits", "wild", "india", "landscape", "portrait",
        "These", "Are", "Tags", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday",
        "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December",
        "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L",
    ]

    let stack = UIStackView()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .systemBlue

        stack.axis = .vertical
        stack.spacing = 16
        stack.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(stack)

        let g = view.safeAreaLayoutGuide
        NSLayoutConstraint.activate([
            stack.topAnchor.constraint(equalTo: g.topAnchor, constant: 16.0),
            stack.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
            stack.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
            // let the view determine its own height
        ])

        // let's create 3 tag views
        //  with 2, 3, 4 rows
        for i in 2...4 {
            let tv = MyTagsView()
            tv.backgroundColor = .white
            tv.numRows = i
            tv.theTags = self.theTags
            tv.delegate = self
            stack.addArrangedSubview(tv)
        }

    }
    func myTagsView(_ myTagsView: MyTagsView, didSelectItemAt index: Int) {
        guard let tvIDX = stack.arrangedSubviews.firstIndex(of: myTagsView) else { return }
        print("Selected: \(index) / \"\(theTags[index])\" in tags view \(tvIDX)")
    }
    func myTagsView(_ myTagsView: MyTagsView, didDeSelectItemAt index: Int) {
        guard let tvIDX = stack.arrangedSubviews.firstIndex(of: myTagsView) else { return }
        print("Deselected: \(index) / \"\(theTags[index])\" in tags view \(tvIDX)")
    }
}

and it looks like this:

This is just an idea of one other approach ... and is just starter code to play with to see if it would be a workable alternative.


text:
Q: why JSTL forEach do not complete loop? I have a xhtml file that loops trhough some items and for each item includes a xhtml which loops to display some items:
    file-a.xhtml
    <c:forEach var="record" items="#{firstItemsList}">
      do some stuff...
      <ui:include src="file-b.xhtml" />
    </c:forEach>

In file be I have the following:
    #{viewController.resetComments()}
    <c:forEach var="item" items="#{comments}" varStatus="status">
      show some tags here...
    </c:forEach>

problem is that in the second or third or ... imports of the file-b within file-a, for each loop in file-b will loop through max number of comments which was in the first call. for example, if the first import ofcall for file-b has 3 elements in it and the second call for file-b has 5 elements in it, then forEach loop stops showing content on the 3rd index for the second call.  now if the first call has zero elements in it.. all other proceeding calls for file-b will show nothing even if they have comment items.
question is how can i make the forEach loop complete task correctly on each call for file-b?

A: I still do not know why the loop is not working properly but i bypassed the problem by hard coding html fragment that forEach was generating in xhtml file inside java code in my controller. So in file B i have the following instead of the forEach loop.
    <h:outputFormat escape="false" value="#{controller.showComments(list)}" />

redpajama_set_name: RedPajamaStackExchange


text:
Q: Inconsistent SSL error when accessing different sites This is not one of the "why does my code not download over HTTPS" questions. I have seen and read all of them years ago, and since then I have implemented this same approach a number of times, successfully.
My very simple C# code that targets 4.7.1 framework and runs on 4.7.2 framework attempts to download resources over HTTPS. It follows all commonly known recommendations as regards to configuring ServicePointManager, WebClient, and WebRequest. Initially, I tested it with an Apache 2.4.20 instance on our LAN, and it worked fine. Next, I tested it with a couple of other servers on the public Internet, and there I ran into the error that occurs about 5 seconds after making the request, even though the page opens in a browser instantaneously:
{"The request was aborted: Could not create SSL/TLS secure channel."}

I checked the server certificates. They are trusted by Mozilla and Windows and open in any browser known to me, in a fully trusted mode. The sites respond over TLS 1.2. There is nothing visibly wrong with the servers or their certificates. For a sanity check, I took Google's homepage address https://www.google.ca/?gws_rd=ssl, and it opened just fine. Some sites open, other sites do not. I tried enabling one TLS version at a time, and each worked equally well with each of the working sites, whereas none of them worked with the non-working sites.
Here is my code. It is written to be used with basic auth but tested without it as well. This is not an authentication issue.
ServicePointManager.Expect100Continue = true;
ServicePointManager.DefaultConnectionLimit = 9999;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11; // | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; // tested by enabling only 1 protocol at a time locally. Each worked.

if (ServicePointManager.ServerCertificateValidationCallback == null) // for testing only
{
    ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) => { return true; };
}

using (var client = new WebClientEx()) // Ex adds Timeout and CookieContainer
{
    client.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache);
    client.Headers.Add("Cache-Control", "no-cache");
    client.Encoding = Encoding.UTF8;

    var cc = new CredentialCache();
    // Using one or the other, depending on the situation, or none
    //cc.Add(url, "Basic", new NetworkCredential(user, pass));
    //cc.Add(new Uri(url.GetLeftPart(UriPartial.Authority)), "Digest", new NetworkCredential(user, pass));
    client.Credentials = cc;

    return client.DownloadData(url);
}

Before falling back onto WebClient, I have tried with the plain HttpRequest for the sake of its reliable timing out, which is important for my implementation:
var req = (HttpWebRequest)WebRequest.Create(url);
req.Timeout = (int)timeout.TotalMilliseconds;
req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; // tried with or w/o

var encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes($"{user}:{pass}"));
req.Headers.Add("Authorization", "Basic " + encoded); // tried with or w/o

var credentialCache = new CredentialCache();
credentialCache.Add(url, "Basic", new NetworkCredential(user, pass)); // tried with or w/o
req.Credentials = credentialCache;
req.PreAuthenticate = true; // tried with or w/o
using (var response = (HttpWebResponse)req.GetResponse())
{
    using (var ms = new MemoryStream())
    {
        response.GetResponseStream().CopyTo(ms);
        return ms.ToArray();
    }
}

Both variants of my code equally worked with my local Apache and Google but did not work with some other sites. I cannot find any faults with my code. One of the sites that did not work is https://jigsaw.w3.org/HTTP/Basic/ that opens fine in any browser. This is the site that most of our software uses for unit testing, so I am expected to produce something that works with it during the test phase and with any arbitrary web server out there in production.
I turned on System.Net tracing and compared the successful and failed download attempts, and the difference is that one proceeds with the handshake while the other fails right away. There is no useful info in the trace.
Any ideas what is amiss?
All services and technologies mentioned in this question are beyond my control and have to remain whatever they currently are. I am powerless to change any versions or to install any updates. It has to work the way it currently is. If you are not happy with it, please skip over to other questions.

A: The answer is "nothing is wrong with the code". Something is actually wrong with those select servers that I had to test with. They are old or niche, and they are non-compliant to a degree that .NET framework refuses to interoperate with them. As soon as I tested with modern, compliant servers, everything worked as expected, both over HTTP or HTTPS and both with basic or digest authentication.


text:
Q: Why do NOC/Command Centers always have CNN or the Weather Channel on display? I've been inside of a few NOCs in my time, and almost without exception, there are a couple of big screens playing these channels. Why?

A: Bang for buck. You need to get as many colour graphs and cool looking statistical lines onto the screen at the same time as possible. Preferably with sliding news reels and weather information for added real time data awe. This is mostly to convince management types that important things are being done. I know this sounds sarcastic, but it sadly isn't as much as it should be.

A: Well, it does get boring in there sometimes, and I bet if the CIO saw us watching COPS instead of working it wouldn't go so well... :)

A: Weather can affect many things, as can major geopolitical events, that could affect the operations of a network.  At least, that's the "business reason".  The actual reason is exactly what BenGC said - that it's boring as all hell to watch a bunch of monitors that 99% of the time are normal.

A: I'm working at a support center of a French ISP, and we do need those informations for various reasons:

*

*Weather:

*

*Rain: old copper cables (local loop) are sensible to water.

*Thunderstorms: Low-end routers and modems have weak power supplies.

*snow slows down our Field engineers :(

*Some RF links are also affected by bad weather. (fortunately no laser/optical links)

Other events that I can remember of:

*

*2010 Haiti earthquake: several customers impacted

*2010 Chile earthquake: customers & backbone (routers, links) impacted

*2004 Indian Ocean earthquake & tsunami: several submarine communications cables down

But we do have also some customers in countries like Irak or Afganistan, were geopolitical situation can increase difficulty to repair. Green zone for example, is a restricted area where our Field engineers have to go...


text:
Q: Correct way to pass state from one component to another I am getting myself a bit confused with React.
I have a home 'page' which I am breaking up into components. So, I have a hero component which at the moment just has a title which is pulled from mongodb.
So, on the home page I have:
import React, { Component } from "react";
// the axios http request to the server
import { getHero } from "../services/heroService";

//state
class Home extends Component {
  state = {
    title: "",
  };

  async componentDidMount() {
    const response = await getHero();
    this.setState({ title: response.data.title });
  }

  render() {
    return (
      <React.Fragment>
        <Hero title={this.state.title} />
    );
  }
}
export default Home;

Then my hero component:
import React, { Component } from "react";
import { Container } from "react-bootstrap";

class Hero extends Component {
  render() {
    const { title } = this.props;
    return (

        <Container className="text-center text-white">

{title}

        </Container>

    );
  }
}
export default Hero;

I just wanted to know if this was the correct way to pass the data from the state to another component. It seems to work but that does't mean it's right.

A: Yes, that is the right way.
Basically when passing data between components, you can have several cases, here are the canonical "React-way" of doing:

*

* is the parent of , data flows from  to  (your case): data is stored in A.state, and is passed through props:

* is the parent of , data flows from  to : data is stored in A.state, and a listener is passed through props:  this.updateData(newData)}>

* and  are close siblings and share data: data is stored in the closest common ancestor, listeners are passed through props (aka lifting the state up)

* and  are independent and share data: use a state container like Redux

A: Yes, this is right way to pass data from a parent /  container components to child components, in case you are using redux, you can only add the props of parent/container component to store and child /view component can only have responsibility to show /display the data.


text:
Q: Java: Iterate over a set while contents of set are being modified I wish to iterate over a set but the contents of the set will modify during its iteration. I wish to iterate over the original set at the time the iterator was created and not iterate over any of the new elements added to the set. How is this possible? Is this is the default behavior of set or how can I accomplish this?
One way I can think of is to get a new set from the original set which won't be modified but this seems inelegant and there must be a better solution.

A: EDIT: This answer was designed for a single-threaded case, since I had interpreted the OP's question as avoiding comodification rather than avoiding issues from multithreading.  I'm leaving this answer here in case it ends up being useful to anyone in the future who is using a single-threaded approach.
There is no direct way to accomplish this.  However, one option that is quite nice is to have two sets - the main set, which you iterate over, and a secondary set into which you insert all the new elements that need to be added.  You can then iterate over the primary set, and then once that's finished go and use addAll to add all the new elements to the primary set.
For example:
Set<T> masterSet = /* ... */

Set<T> newElems = /* ... */
for (T obj: masterSet) {
     /* ... do something to each object ... */
}

masterSet.addAll(newElems);

Hope this helps!

A: Taking a snapshot of the set sounds like exactly the right solution to me, if you want to make sure you don't see any new elements. There are some sets such as ConcurrentSkipListSet which will allow you to keep iterating, but I can't see any guarantees around behaviour of an iterator in terms of seeing new elements.
EDIT: CopyOnWriteArraySet has the requirements you need, but writes are expensive, which sounds like it's not appropriate for you.
Those are the only sets I can see in java.util.concurrent, which is the natural package for such collections. Taking a copy is still likely to be simpler :)

A: Making a copy of the Set is the elegant solution.
Set<Obj> copyOfObjs = new HashSet<Obj>(originalSet);
for(Obj original : originalSet) {
    //add some more stuff to copyOfObjs
}

A: You can use a ConcurrentHashMap  with dummy keys.
Or a ConcurrentSkipListSet

A: Now that OP has clarified the requirements, the solutions are

*

*Copy the set before iterating

*Use CopyOnWriteArraySet

*Write your own custom code and try to be smarter than a lot of smart people.

The drawback of #1 is that you always copy the set even if it may not be needed (e.g. if no insertions actually occur while you are iterating)  I'd suggest option #2, unless you prove that frequent inserts are causing a real performance issue.

A: As others have suggested here, there is no optimal solution to what you search for. It all depends on the use-case of your application, or the usage of the set
Since Set is an interface you might define your own DoubleSet class which will implement Set and let's say will use two HashSet fields.
When you retrieve an iterator, you should mark one of these sets to be in "interation only mode", so the add method will add only to the other set
I am still new to Stackoverlflow, so I need to understand how to embed code in my answers :( but in general you should have a class called MySet (Generic of generic type T) implementing Set of generic type T.
You need to implement all the methods, and have two fields - one is called iterationSet and the other is called insertionSet.
You will also have a boolean field indicating if to insert to the two sets or not. When iterator() method is called, this boolean should be set to false, meaning you should insert only to the insertionSet.
You should have a method that will synchronize the content of the two sets once you're done with the iterator.
I hope I was clear


text:
Q: Difference between ? or | in regular expression From Wiki,

*

*?  => Matches the preceding element zero or one time. For example, ab?c matches only "ac" or "abc".

*|  => The choice (also known as alternation or set union) operator matches either the expression before or the expression after the operator. For example, abc|def matches "abc" or "def".

Here is the code tried;
String yuStr =  "-7.00, 10.00, 0.00, -212.000";

//Using ?
System.out.println(yuStr.replaceAll("-?(\\d+)\\.\\d+", "$1"));

//Using |
System.out.println(yuStr.replaceAll("-|(\\d+)\\.\\d+", "$1"));

However, both of two ways will give the same output
7, 10, 0, 212

Is my assumption right, according to Wiki doc above, in second way with ?, it is choice between expression before operator - and expression after operator (\\d+) ?
My question is, why the second way (with |) is working the same way like first one (with ?) ?

A: The first expression says
     a decimal number, possibly preceded by a -
The second expression says
     A - or a decimal number
When using the expressions as argument to replaceAll, you'll (incidentally) get the same result in this case since you set $1 as the replacement value.

A: The two expressions have different semantics, even though they happen to produce the same results for this particular input.
On some other inputs their result will differ. Consider, for example 1-2. The first would return 1-2 whereas the second would return 12.

A: ? and | are used for different reasons. For example :
public static void main(String[] args) {
    String yuStr = "--7";
    System.out.println("1 : " +yuStr.replaceAll("-?\\d","")); // replaces the second - and 7
    System.out.println("2 : " +yuStr.replaceAll("-|\\d","")); // replaces all - and all numbers
}

prouces the OP :
1 : -  // first - is not replaced.
2 :    // empty string

It is just a co-incidence that in your case, they produce the same output.
Note : In regex, it is not surprising to have 10 different ways (expressions) to get the same output :)

A: They are not the same, they just happen to produce the same output for your example.
The 4 matches in the first regex:
-7.00, 10.00, 0.00, -212.000
-1---  |   |  |  |  |      |
       11---  |  |  |      |
              1---  |      |
                    -111----

In each match, the capturing group captures the whole part of the decimal number, and all four matches are replaced by the content of the capturing group.
The 6 matches in the second regex:
-7.00, 10.00, 0.00, -212.000
-|  |  |   |  |  |  ||     |
 1---  |   |  |  |  ||     |
       11---  |  |  ||     |
              1---  ||     |
                    -|     |
                     111----

The capturing group only captures some text in 4 matches. In the other 2 matches, the capturing group doesn't capture anything.
In Oracle/OpenJDK, referring to a group that captures nothing in the replacement string will result in empty string. Therefore, the - are simply removed, and for this particular input, the end result is the same.
However, for input such as --7.3, the result will be different.
And in Android and GNU Classpath's implementation, a group that captures nothing is rendered as null when referred to in the replacement string, so your output string in the second case will contain null.


text:
Q: How can I use a string variable in array without splitting it? I'm creating a tool that makes security searches. My printer detection script is getting strings in another .txt file like "Printer Firmware Version" and using grep tool to check if its exist in target host website. But my script split this strings and uses them as different variables like Printer, Firmware, Version. How can I get that strings without splitting them?
   found=(`cat temp.txt`) # <- This line for target
   httarr=(`cat httpport.txt`)
   printer_array=(`cd ..; cat keywords/printerwords.txt`)
   for lo in ${httarr[*]}
   do
     ifacelook=`curl -sSL http://$found:$lo`
     for pr in ${printer_array[*]}
     do
        echo $pr # <-This line is to see incoming variables
        echo $found | grep -o '${pr}' &>/dev/null
        if [ $? -eq 0 ];then
          echo -en "$cyan>$green|${red}printer$green|$cyan>$default This device is a printer check: http://$found:$lo \n"
        fi
     done
   done

Incoming variables:
Printer
Firmware
Version
.
.
.
Variables I want:
Printer Firmware Version
.
.
.

A: Your word splitting occurrs with:
found=(`cat temp.txt`) # <- This line for target
httarr=(`cat httpport.txt`)

(which both include a UUOc (Unnecessary Use Of cat))
Instead use:
mapfile -t found < temp.txt
mapfile -t httarr < httpport.txt

mapfile (synonymous with readarray) will read each line of a file from stdin into the indexed arrays.
Not recommended, but you can also set IFS (Internal Field Separator) to only break on newlines with:
set -o noglob                 ## disable globbing to protect from * in line
oldifs="$IFS"                 ## save current IFS
IFS=$'\n'                     ## set IFS to newline only
found=( $(< temp.txt) )       ## fill arrays
httarr=( $(< httpport.txt) )
IFS="$oldifs"                 ## restore original IFS
set +o noglob                 ## restore globbing  (thanks to Charles)

Look things over and let me know if you have further questions.


text:
Q: Counter not working in CSV reading script this is my first ever Python script/question on Stackoverflow/step into real coding.
I am looking to count the number of times certain strings appear within the rows I am iterating through then print out the values. I have not set up a delimiter so there is only one column. Essentially I am saying, if the column contains said string, add to the counter.
The problem is, I get an output of 0 for all my variables. Any suggestions?
Here is the code (sorry it's long).
# read the CSV file

import csv
with open('example.csv', 'r') as csvfile:

reader = csv.reader(csvfile)

# set up counter variables
googlebot = 0
googlebot_mobile = 0
apis_google = 0
adsense = 0
adsbot_mobile_web_android = 0
adsbot_mobile_web = 0
adsbot = 0
googlebot_images = 0
googlebot_news = 0
googlebot_video = 0
mobile_adsense = 0
mobile_apps_android = 0

# set up counter identifiers
googlebot_string = 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
googlebot_mobile_string = 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
apis_google_string = 'APIs-Google (+https://developers.google.com/webmasters/APIs-Google.html)'
adsense_string = 'Mediapartners-Google'
adsbot_mobile_web_android_string = 'Mozilla/5.0 (Linux; Android 5.0; SM-G920A) AppleWebKit (KHTML, like Gecko) Chrome Mobile Safari (compatible; AdsBot-Google-Mobile; +http://www.google.com/mobile/adsbot.html)'
adbot_mobile_web_string = 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1 (compatible; AdsBot-Google-Mobile; +http://www.google.com/mobile/adsbot.html)'
adsbot_string = 'AdsBot-Google (+http://www.google.com/adsbot.html)'
googlebot_images_string = 'Googlebot-Image/1.0'
googlebot_news_string = 'Googlebot-News'
googlebot_video_string = 'Googlebot-Video/1.0'
mobile_adsense_string = 'compatible; Mediapartners-Google/2.1; +http://www.google.com/bot.html'
mobile_apps_android_string = 'AdsBot-Google-Mobile-Apps'

# iterate and search for/add to counter
for row in reader:
    if googlebot_string in row:
        googlebot += 1

    elif googlebot_mobile_string in row:
        googlebot_mobile += 1

    elif apis_google_string in row:
        apis_google += 1

    elif adsense_string in row:
        adsense += 1

    elif adsbot_mobile_web_android_string in row:
        adsbot_mobile_web_android += 1

    elif adbot_mobile_web_string in row:
        adsbot_mobile_web += 1

    elif adsbot_string in row:
        adsbot += 1

    elif googlebot_images_string in row:
        googlebot_images += 1

    elif googlebot_news_string in row:
        googlebot_news += 1

    elif googlebot_video_string in row:
        googlebot_video += 1

    elif mobile_adsense_string in row:
        mobile_adsense += 1

    elif mobile_apps_android_string in row:
        mobile_apps_android += 1

# print counts
print "Googlebot (Desktop): ", googlebot
print "Googlebot (Mobile): ", googlebot_mobile
print "APIs Google: ", apis_google
print "AdSense: ", adsense
print "AdsBot Mobile Web Android: ", adsbot_mobile_web_android
print "AdsBot Mobile Web: ", adsbot_mobile_web
print "AdsBot: ", adsbot
print "Googlebot Images: ", googlebot_images
print "Googlebot News: ", googlebot_news
print "Googlebot Video: ", googlebot_video
print "Mobile AdSense: ", mobile_adsense
print "Mobile Apps Android: ", mobile_apps_android

A: You are reading the file outside the with context manager.
Your code should be:
with open('example.csv', 'r') as csvfile:
    reader = csv.reader(csvfile)

otherwise you are opening and closing the file before even reading it.
EDIT:
As @yann-vernier has pointed out, reader must be consumed inside the with block. That is, the for loop should be all indented.

A:
I have not set up a delimiter so there is only one column

If you do not specify a delimiter, the default one is used, which is a comma ,. So, there still may be multiple columns and, therefore, multiple elemtns in the list row.
Now, the string in googlebot_string also contains commas, so, if this string is present in your input CSV, it never appears in row as a single element. Therefore googlebot_string in row is always false. Some of the other *_string strings have the same problem.
You can open the file just as a text file (without using the csv module) and iterate over the lines.
A dirty solution would be to specify a character that is not present in your input file as delimiter for csv.reader.


text:
Q: WPF DataGrid TwoWay Binding I have property UserSet which contains from ObservableCollection<GridRow>.
GridRow - my class, which contains 4 properties like this:
public int Id
{
    get { return id; }
    set
    {
        id = value;
        RaisePropertyChanged("Id");
    }
}

I populate UserSet, then Grid binds to it. When I change id field works setter Id. It sets right values.
But, after all changes, when I click other button my UserSet has not modified values. So I can't get updated Grid.
This is my XAML:
<DataGrid ItemsSource="{Binding UsersSet, Mode=TwoWay}" AutoGenerateColumns="True">

</DataGrid>

Please help.

A: You could try and set the UpdateSourceTrigger:
<DataGrid ItemsSource="{Binding UsersSet,
                        Mode=TwoWay,
                        UpdateSourceTrigger=PropertyChanged}"
          AutoGenerateColumns="True">

</DataGrid>

Without knowing the rest of your code it is pretty hard to guess.


text:
Q: Can I share Items between characteers? As in most dungeon games a character in Dungeons of Dredmor finds many many items that are useless to them.  Full plate to the mage, staves to the rogue, etc, etc.  Is there a way in Dungeons of Dredmor to share or gift items between characters?

A: Nope; this game is supposed to be hard (-ish), so no giving your other characters a boost. Dungeons of Dredmor follows "Roguelike" themes, not "MMORPG" themes. Thus, you have (the option of) permadeath, and no sharing items between characters. If you take a crafting skill, you'll be able to get some items for your class; anything else you can't use is either merchant fodder, something you might be able to break down for parts, or fuel for the Horadric Lutefisk Cube.


text:
Q: Uipickerview behind item working I have pickerview in my view controller. I am displaying it by adding into subview and then changing frame of subview. When my pickerview displayed I have one button behind it. When I click on those area after dispalying pickerview still that button action is called. How to set pickerview proper?

A: U subclass the PickerView like below will help u to fix this issue.
//
//  WPCustomPickerView.h
//  test
//
//  Created by VASANTH K on 08/01/14.
//
//

#import <UIKit/UIKit.h>

@interface WPCustomPickerView : UIDatePicker

@end

implementation file
//
//  WPCustomPickerView.m
//  test
//
//  Created by VASANTH K on 08/01/14.
//
//

#import "WPCustomPickerView.h"

@implementation WPCustomPickerView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    id hitview=[super hitTest:point withEvent:event];
     if(!hitview)
     {
     if(point.y<=self.frame.size.height&&point.y>=0)
     return self;
      }
return hitview;
}

@end

Here i override the hitTest to make UIPickerView  response for the user interaction. This is the way how apple make main picker view transparent for user touch by return nil when user directly touch on the main view instead of picker content.


text:
Q: Create a fractions matrix I'm trying to create a fractions matrix.
First, i create a class Matrix, and define methods, like create a new matrix, delete matrix, solve a matrix (Gauss and Gauss-Jordan method). All the values on the matrix are float. I compile all and works :D. But now, I'm trying to create another matrix, exactly equals to the first, but this need to be only for fractions. This is my problem, how i do this? how i create a method that receives 2 number (for example: myMethod(2,3)), regards these like 2/3 and puts in a matrix position? My goal is have something like that:
Matrix:
1/2   2/3   1/5

2/5   3/4   3/2

2/7   3/5   1/3

All the numbers will be sent by the user, for example, cin>>n1>>n2; (Actually this is n1/n2)
PD: i was thinking on create a for loop like:
for(i=0;i<3;i++)
    myMethod(n1,n2);

PD2: Sorry for my english, i hope you understand me :(

A: As far as I understand, c++ cannot handle fractions natively. the best you could do is float. Alternatively, if you just would like to display the Matrix as a fraction (and maybe do some operations on it), you could do something like the following.
Mat numerator[3][3];
Mat denominator[3][3];
cin>>numerator[0][0]>>denominator[0][0];
//.... for all elements

//Display
cout<<numerator[0][0]<<"/"<<denominator[0][0];

//operations
newmatrix[0][0] = numerator1[0][0]*numerator2[0][0] / (denominator1[0][0]*denominator1[0][0]);

Hope this helps.

A: template <typename NumberType>
class Matrix {
   // ...
}:

And think about mathematical operations on each supported number type.


text:
Q: How to only change specific vertex position of a graph? Suppose I plot a graph using the following specifications:
GraphPlot[
    $edges,
    GraphLayout->{"LayeredDigraphEmbedding","Orientation"->Left}
]

Suppose I am happy with the automatic coordinates chosen by the system except for one and I want to translate that by say +{1,2}.
GraphPlot has an option called VertexCoordinates but it requires me to give all the coordinates explicitly but I just want to modify one of them.
One way I found was to Sow the automatically chosen coordinates using Sow[#1] in option VertexShapeFunction then Reap them out to a variable then perform the translation I want to the coordinates outside then rerun the GraphPlot with modified VertexCoordinates.
This is cumbersome there must be a better way to accept all automatically generated coordinates but translate some of them to the better location. Please help.

A: You should use Graph, not GraphPlot, unless there is a very good reason not to. Graph stores an actual graph, with metadata, in a structured way. GraphPlot merely produces graphics, with all structures information getting lost.
You can manipulate the metadata in a graph using the Property* functions such as PropertyValue. These functions tend to be tricky to use and (unfortunately) often inconsistent. But for this purpose, they work straightforwardly.
The following example makes use of my IGraph/M package for convenience, but you do not need to rely on it.
We generate a random tree, and set our preferred layout method:
Needs["IGraphM`"]

SeedRandom[123]
g = IGTreeGame[6, DirectedEdges -> True, GraphStyle -> "DiagramGold",
  GraphLayout -> {"LayeredDigraphEmbedding", "Orientation" -> Left}]

There are no stored vertex coordinates in this graph right now. They are computed, not stored, therefore they cannot be modified. To modify them, we must store them first. With IGraph/M, I'd do:
g = IGVertexMap[# &, VertexCoordinates, g]

but without it you can also do:
g = Graph[g, VertexCoordinates -> GraphEmbedding[g]]

Now we can modify the coordinate of a single vertex:
PropertyValue[{g, 3}, VertexCoordinates] += {-1, 2}

Show the graph:
g

A: Update for Mathematica 12.1+: If you want to fix positions of some vertices and have the rest positioned automatically, we can now use VertexCoordinates, e.g.
Graph[
  {1 <-> 2, 2 <-> 3, 3 <-> 1},
  VertexCoordinates -> {1 -> {0, 0}, 2 -> {1, 1}}
]

See documentation


text:
Q: getting single objects out of $angularfire/$firebase I am trying to follow a tutorial on lynda.com which uses angularfire (angularjs firebase) except it uses stuff like $firebase.$asObject and such, which is now obsolete.  I tried to look at the documentation as well as some other SOF questions, and I finally found something that worked, but it looks ugly and seems quite inefficient since the only way I found for it to work is to iterate through all the objects in an array returned from the database.  This array holds all the users which are registered.  This is how I got it to work, but can someone tell me the correct way to do it, because this does not seem like it should be it.
var ref = new Firebase(FIREBASE_URL);
var auth = firebaseAuth(ref);

auth.$onAuth(function(authUser){
    if(authUser){
        var ref = new Firebase(FIREBASE_URL + 'users/');
        var stuff = firebaseArray(ref);

         ref.on('value', function(snapshot) {
            if(snapshot.val() !== null) {
                var keys = Object.keys(snapshot.val());
                for(var key in keys){
                    if(keys.hasOwnProperty(key)){
                        if(authUser.uid === snapshot.val()[keys[key]].registeredUser){
                           rootScope.currentUser = snapshot.val()[keys[key]];
                        }
                    }
                }
            } else {
                console.log('location does not exist');
            }
          });

        var user = firebaseObject(ref);
        //console.log(user);
        rootScope.currentUser = user;
    } else {
        rootScope.currentUser = '';
    }
});

Here is what my firebase forge looks like:

Thank you in advance!

A: It is usually helpful to store user data like proposed in https://www.firebase.com/docs/web/guide/user-auth.html#section-storing.
You need to use the unique ID as the key for the user object, so you don't have to iterate over all users to search for it. The unique ID is part of the auth data, see https://www.firebase.com/docs/web/guide/user-auth.html#section-monitoring-authentication).


text:
Q: Modal with zoom in zoom functionality in jquery issue So I am using the imgViewer2 plugin.
I need to design a modal with the options to zoom in and out on the image selected.I am facing an issue with the zoom in zoom out option which is appearing on the web page along with the image instead of appearing inside the modal window.
Here is my working link for the same link.

A: on modal popup the zoom in/out are appearing but its not visible because of its low z-
  index value, try to fix it like below.

$(document).ready(function () {
        $('.full-image').imgViewer2({});
        $('.viewport').addClass("CustomStyleForImageViewer");
        $('.map-image').click(function () {
            var $src = $(this).attr('src');
            $('.full-image').attr('src', $src);
            $('.map-image').removeClass('focused-on');
            $(this).addClass('focused-on');
        });
    });

But it leads to further problems which need to be sorted out as well.
  This answer is just a hint on how to make zoom in/out divs visible on modal popup, you will need to fix the further problem which are gonna occur in this scenario , test it and you will know it

A: you can embed your own zoom in zoom out buttons inside modal. I have modified your code a little bit. This is just a hint on how to work out your problem.

                               <input type="button" title="ZoomIn" value="ZoomIn" onclick="funcZoomIn()" style="position:absolute; top:50%;" />

                                <input type="button" title="ZoomOut" value="ZoomOut" onclick="funcZoomOut()" style="position:absolute; top:50%;" />

Ground Floor

First Floor


text:
Q: How to add text to responsive background canvas to a webpage? I want to create a Welcome Page with a responsive background like this fiddle
https://codepen.io/JulianLaval/pen/KpLXOO/.
I tried using
var ctx = canvasDiv.getContext("2d");
ctx.fillStyle = "RGBA(255, 255, 255, 0.8)";
ctx.fillText("Hi", canvasDiv.width / 2, canvasDiv.height / 2);

But it is not working.
Any help?

A: The problem is that you can not simply reuse the canvas of the particle library - at least not without modifications to the particle library itself.
This library has it's own update() function which we can see at this github link: ParticleNetwork.prototype.update
So initially it clears it's canvas, draws the particles and finally schedules a call to itself - so it constantly repaints the canvas with the displays refresh rate.
No here's the problem - if you simply draw something to it's canvas it will ultimately be overwritten by this update function.
If you want to draw text on it's canvas, you have to do it inside this function.
For example, find these lines of code:
  if (this.options.velocity !== 0) {
      requestAnimationFrame(this.update.bind(this));
    }

if you add the following lines before:
this.ctx.fillStyle = "RGBA(255, 255, 255, 0.8)";
this.ctx.fillText("Hi", this.canvas.width / 2, this.canvas.height / 2);

You will have your desired text.


text:
Q: How to make a mail sender application approved as secure by Gmail? I develop an application which has to send emails (by JavaMail) through an external mail server, which can be Gmail too.
First I faced a credentinal error, but it came out that cause of the problem was that Gmail refuses the connection from a less secure application by default. When I enabled this option, the connection worked.
My question is: what should I do to let Google accept the application as a secure one?
My goal is to use the program without setting of the "allow insecure applications" option in.
Is there a validation process at Google to accept an applicaton as secure?
If not, what I need to implement in the sw to meet the requirements?
I've found similar question, but there was only one answer with a guess, instead of a proved solution.
Thank you in advance.

A: From what I'm able to tell, Google's definition of "less secure app" is "an app that doesn't use OAuth". So, if you want your app to be able to use GMail without the whole "less secure app" thing frightening away your customers, you're going to need to implement OAuth.


text:
Q: Moodle Installation not working with local server Repeatedly facing three issue while installing moodle software in local server.

*

*version 5.5.31 is required and you are running 5.5.5.10.1.25

*PHP opcode caching improves performance and lowers memory requirements, OPcache extension is recommended and fully supported.

*It has been detected that your site is not secured using HTTPS. It is strongly recommended to migrate your site to HTTPS for increased security and improved integration with other systems.

A: There is no question in your question, but:

*

*If Moodle discovered that it's running on 5.5.5.10.1.25 PHP - then just upgrade it. If accessing the same server from network you're getting different version of PHP, then it might be that you have inconsistent packages' versions. Try removing them and adding using package manager of your choice (yum on redhat).

*Just add opcache in yum like: yum install php55w-opcache.x86_64

*It's just a message - your choice is if you use http or https.


text:
Q: ArgoCD CLI SSO login not working : PermissionDenied desc = Forbidden Currently I have an sso login associated with ArgoCD and trying to have CLI access to ArgoCD.
but when I run
argocd login argo.domain.com --sso

Getting error
FATA[0001] rpc error: code = PermissionDenied desc = Forbidden

Any suggestions?

A: Whatever SSO you got set up doesn't support the PKCE flow. ArgoCD web UI uses the usual "webapp" flow as it has the client id and the client secret. ArgoCD CLI can use either the PKCE or the implicit flows (neither of which supports the client secret).
Make sure your OIDC provider is configured as appropriate.


text:
Q: Short story: pebble-sized galaxy lost on a beach I read this short story long ago, about a man searching endlessly on a beach for a miniature galaxy he somehow lost.

A: The story is Beachcomber (1952) by Damon Knight, available at the Internet Archive; publication history at ISFDB.
It is not the galaxy but the whole Universe, but I don't think there are many stories with a man endlessly searching on a beach for a miniature cosmic object he somehow lost.

The Beachcomber made an impatient gesture. "You don't think we could bring it back into a space it already occupied, do you? It was in stasis, all but a fraction out of this time-line. Just a miniature left, so that it could be controlled. A model of the universe, so big." He spread his thumb and forefinger
an inch apart — "Just a pebble."

Maxwell's jaw dropped open. He stared at the giant. "You don't mean — you — "

"Oh, yes," said the Beachcomber, "I landed about twenty miles out from shore — five years ago." He stared out across the sea, while his fingers groped nervously among the pebbles at his feet.

"And when I hit the water," he said, "I dropped it."


text:
Q: Merge two variadic templates in one Im trying to implement a variadic template wrapper of the loki typelist.
Merging two typelists in loki-style is easy, but im having problems with merge in variadic-template style.
This is my implementation (Simplified, without push_back , index_of , ... , methods).
template<typename... Ts>
struct dl32TypeList;

template<typename HEAD , typename... TAIL>
struct dl32TypeList<HEAD,TAIL...>
{
    static const unsigned int size = sizeof...(TAIL) + 1;

    using value = dl32Loki_like_TypeList<HEAD, typename dl32TypeList<TAIL...>::value>;
};

template<>
struct dl32TypeList<>
{
    using value = dl32NoType;

    static const unsignedint size = 0;
};

I want something like:
template<typename OTHER_TYPELIST>
using merge = dl32TypeList<HEAD , TAIL... , typename OTHER_TYPELIST::???>;

And this is the problem: We cannot store variadic template args as a using/typedef, so i have any idea about how i can do this. (Note the OTHER_TYPELIST::???).

A: I don't know what Loki or DL32 are, and it's not clear you should be implementing anything at all.
std::tuple is a common tool for type lists. It is designed as a runtime storage container but works as a compile-time utility as long as the types are complete. Here is one way to catenate tuples:
template< typename ... t >
struct tuple_cat
    { typedef decltype( std::tuple_cat( std::declval< t >() ... ) ) type; };

If you want to do it manually, try partial specialization:
template< typename ... t >
struct type_list {};

template< typename ta, typename tb >
struct type_cat;

template< typename ... a, typename ... b >
struct type_cat< type_list< a ... >, type_list< b ... > >
    { typedef type_list< a ..., b ... > type; };

As for the size member, you can make a universal metafunction to solve the problem once and for all.
template< typename >
struct count_types;

template< template< typename ... > class t, typename ... a >
struct count_types< t< a ... > >
    { static constexpr std::size_t value = sizeof ... a; };


text:
Q: dyanamic cluster formation in ns-2 simulator using tcl scripting & AWk language I want to create clusters dynamically with any number of nodes (the number read from command line input). I have deployed nodes using set dest command with x and y values, but I want to implement dynamic cluster formation each time. As shown, I have x and y coordinates hard-coded, but I would like to create them at runtime.
   $ns_ at $tn "$node_(0) setdest 730.061 715.205 750"
   $ns_ at $tn "$node_(1) setdest 1032.95 867.473 750"
   $ns_ at $tn "$node_(2) setdest 941.11 1031.13 750"
   $ns_ at $tn "$node_(3) setdest 1112.75 993.609 750"
   $ns_ at $tn "$node_(4) setdest 1085.21 1176.37 750"
   $ns_ at $tn "$node_(5) setdest 1232.55 821.43 750"
   $ns_ at $tn "$node_(6) setdest 1277.3 1040.56 750"
   $ns_ at $tn "$node_(7) setdest 883.426 466.448 750"
   $ns_ at $tn "$node_(8) setdest 1001.59 290.138 750"
   $ns_ at $tn "$node_(9) setdest 774.005 337.611 750"
   $ns_ at $tn "$node_(10) setdest 636.72 245.85 750"
   $ns_ at $tn "$node_(11) setdest 888.613 195.457 750"

A: Here's how to place twelve nodes with random locations.
for {set i 0} {$i < 12} {incr i} {
    # I've no idea how you *want* to do this, but this works for example
    set xLocation [expr {int(1500 * rand())}]
    set yLocation [expr {int(1500 * rand())}]

    # Place the node (is that what the right name is?)
    $ns_ at $tn [list $node_($i) setdest $xLocation $yLocation 750]
}

The list command is ideal for generating callbacks; it does precisely the quoting that you need.


text:
Q: SQL Server Bulk Insert from UNC location returning no records and no errors I have a CSV file on a network drive that I want to load using bulk insert in a stored procedure in SQL Server. This CSV file has record delimiters like "text1","text2" etc. The file has a total of 27 columns and approximately 90 rows.
I have created the following format file that matches the input file:

When I copy the csv to the server and run the Bulk Insert - it works fine and returns all the records as expected.
SELECT *
FROM OPENROWSET (BULK N'K:\Upload\Shipping\testship.csv',
                 FORMATFILE = 'K:\Upload\Shipping\shipping.fmt',
                 FIRSTROW = 2) j

However, the same does not return any records if I source the file from a UNC.
SELECT *
FROM OPENROWSET (BULK N'\\servername\Marketing\SHIPPING\Vessel_Departures_and_Cut-off\5Aug.csv',
                 FORMATFILE = '\\servername\Marketing\SHIPPING\Vessel_Departures_and_Cut-off\shipping.fmt',
                 FIRSTROW = 2) j

This returns 0 records with just the column headers. No errors even when I specify a error log file!
It's not a permission issue on the network location as I do the same with other files and they work fine (but they don't have record delimiters hence no format file!)
Can someone shed light on why this might be please?
UPDATE:
I had copied the csv from UNC to local. when I compare the two files (from the unc and from the local) Notepadd++ says they are encoded differently! Could be a hint why the UNC files are not loading. How do I specify encoding please? How would I know what encoding to use?
If I open the original file with Notepad ++, copy all the contents into a new file and save it, I can successfully load the new file! What gives!


text:
Q: Handling abandoned/disconnected Sockets If i have 100 devices connected to a socket server and the power goes out on the clients. When the power is reconnected I will get 100 new client socket connections.
The server will now have 200 socket connections. 100 of which are abandoned.
Do I need to detect/handle/close these abandoned connections or will .net/windows detect this and clear it up in the background?

A: the connections will be closed (assuming TCP)
You will know that those connections are dead. Exactly how depends on your coding. Is async you will receive an endreceive event. If sync your next read or write fail.
You already have code for dealing with unusual end of connection (don't you) , in this case you just get a lot of those at once

A: The scenario you describe is one of the purposes of the TCP "KeepAlive" setting.  Because the TCP protocol generally doesn't require either party to say anything except when it has reason to believe that it knows something about the connection that the other party doesn't, connections where neither party has had anything to say since its last data packet was acknowledged don't generate any traffic.  It is thus impossible to distinguish a device which has ceased to exist from one which is alive and connected but simply doesn't have anything it wants to say.
If a party to a connection has "KeepAlive" set, then if a certain length of time (typically a few minutes) elapses without any traffic in either direction, that party will pretend to "forget" that it had received an acknowledgment for the last byte it sent and will consequently resend that byte.  If the other party to the connection is still alive, it will see the retransmission and recognize it as such (ignoring the data therein), but it will send an acknowledgment on the premise that the other side might have missed the earlier acknowledgment, and even if the other side did see the earlier acknowledgment retransmitting it will be harmless.  If the other party to the connection does exist, but knows nothing of the connection, it will immediately send a "reset" packet to indicate that, thus killing the connection.  If the other party to the connection doesn't exist, the retransmitted byte will never get acknowledged; after repeated attempts to resend that byte, the party trying to send it will eventually give up and kill the connection.
Enabling KeepAlive will ensure that if one side of a connection disappears, the other side will eventually find out about it.  KeepAlive times are generally fairly long (minutes), and the KeepAlive time merely sets the point when one party will start looking for the other.  If the other party simply disappears, it may take another minute or so for the system to decide the other party is well and truly gone.  Still, discovering the other party's disappearance after a few minutes is often better than never finding out at all.


text:
Q: Nan output for percent calculation, dice rolling program I'm trying to calculate the the percentage of times two dice were rolled for each total of the two dice. My "actual" value is returning nan, and my expected is returning 0. I know the code is inefficient, we aren't allowed to use arrays in this assignment Can someone please point me in the right direction? Thanks!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {

    int d2 = 0;
    int d3 = 0;
    int d4 = 0;
    int d5 = 0;
    int d6 = 0;
    int d7 = 0;
    int d8 = 0;
    int d9 = 0;
    int d10 = 0;
    int d11 = 0;
    int d12 = 0;

int k, roll_1, roll_2, num_roll, total, count = 0 ;

    float perc, exp;
    srand((long)time(NULL));

    printf("Enter number \n");

    scanf("%d", &num_roll);

for (k = 0; k < num_roll; k++)

            {
            roll_1 = rand() %6 +1;
            roll_2 = rand() %6 +1;
            total = roll_1 + roll_2;
            total++;

            if (total == 2) d2++;
            else if (total == 3) d3++;
            else if (total == 4) d4++;
            else if (total == 5) d5++;
            else if (total == 6) d6++;
            else if (total == 7) d7++;
            else if (total == 8) d8++;
            else if (total == 9) d9++;
            else if (total == 10) d10++;
            else if (total == 11) d11++;
            else if (total == 12) d12++;
     }

printf("Roll\t Total\t Session\tExpected\n\n");

     printf("2:\t %d\t %.3f \t\t %.3f \n", d2, perc, exp);
     printf("3:\t %d\t %.3f \t\t %.3f \n", d3, perc, exp);
     printf("4:\t %d\t %.3f \t\t %.3f \n", d4, perc, exp);
     printf("5:\t %d\t %.3f \t\t %.3f \n", d5, perc, exp);
     printf("6:\t %d\t %.3f \t\t %.3f \n", d6, perc, exp);
     printf("7:\t %d\t %.3f \t\t %.3f \n", d7, perc, exp);
     printf("8:\t %d\t %.3f \t\t %.3f \n", d8, perc, exp);
     printf("9:\t %d\t %.3f \t\t %.3f \n", d9, perc, exp);
     printf("10:\t %d\t %.3f \t\t %.3f \n", d10, perc, exp);
     printf("11:\t %d\t %.3f \t\t %.3f \n", d11, perc, exp);
     printf("12:\t %d\t %.3f \t\t %.3f \n", d2, perc, exp);

  return 0;
  }

A: *

*The total++ seems wrong; what is that for?

*You never assign anything to perc or exp.

*You print out d2 twice, but never d12.
You should probably turn on some warnings.  With -Wall, clang says:
example.c:22:41: warning: unused variable 'count' [-Wunused-variable]
int k, roll_1, roll_2, num_roll, total, count = 0 ;
                                        ^
example.c:58:48: warning: variable 'perc' is uninitialized when used here
      [-Wuninitialized]
     printf("2:\t %d\t %.3f \t\t %.3f \n", d2, perc, exp);
                                               ^~~~
example.c:24:15: note: initialize the variable 'perc' to silence this warning
    float perc, exp;
              ^
               = 0.0
example.c:58:54: warning: variable 'exp' is uninitialized when used here
      [-Wuninitialized]
     printf("2:\t %d\t %.3f \t\t %.3f \n", d2, perc, exp);
                                                     ^~~
example.c:24:20: note: initialize the variable 'exp' to silence this warning
    float perc, exp;
                   ^
                    = 0.0
3 warnings generated.

Adding -Weverything yields one more warning:
example.c:25:11: warning: implicit conversion loses integer precision: 'long' to
      'unsigned int' [-Wshorten-64-to-32]
    srand((long)time(NULL));
    ~~~~~ ^~~~~~~~~~~~~~~~

That one you may or may not care about.


text:
Q: Where is my RAM? Memory leak? I have a bunch of servers. It's a mix of baremetal, VMs. All running Ubuntu Bionic.
This issue has been observed on both types.
FYI, I have read similar questions and I've read the answers. I believe this is a unique problem.
I am the Infra guy here, and I have ran out of ideas. I am unable to find what's using the RAM. And OOM gets invoked once it gets critical. The servers do not use Swap.
# free -h
             total        used        free      shared  buff/cache   available
Mem:           7.7G        7.2G        205M        9.9M        369M        499M
Swap:            0B          0B          0B

# cat /proc/meminfo
MemTotal:        8126308 kB
MemFree:          183608 kB
MemAvailable:     497976 kB
Buffers:           30536 kB
Cached:           263980 kB
SwapCached:            0 kB
Active:          1470404 kB
Inactive:         111476 kB
Active(anon):    1285424 kB
Inactive(anon):     8952 kB
Active(file):     184980 kB
Inactive(file):   102524 kB
Unevictable:           4 kB
Mlocked:               0 kB
SwapTotal:             0 kB
SwapFree:              0 kB
Dirty:               160 kB
Writeback:             0 kB
AnonPages:       1287448 kB
Mapped:           142868 kB
Shmem:             10168 kB
Slab:             279184 kB
SReclaimable:      95864 kB
SUnreclaim:       183320 kB
KernelStack:       11648 kB
PageTables:        18184 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:     4063152 kB
Committed_AS:    4175792 kB
VmallocTotal:   34359738367 kB
VmallocUsed:           0 kB
VmallocChunk:          0 kB
HardwareCorrupted:     0 kB
AnonHugePages:         0 kB
ShmemHugePages:        0 kB
ShmemPmdMapped:        0 kB
CmaTotal:              0 kB
CmaFree:               0 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
DirectMap4k:     7810548 kB
DirectMap2M:      536576 kB
DirectMap1G:           0 kB

# top
top - 16:23:00 up 185 days, 20:54,  1 user,  load average: 0.26, 0.36, 0.43
Tasks: 239 total,   1 running, 144 sleeping,   0 stopped,   1 zombie
%Cpu(s):  1.6 us,  4.0 sy,  0.0 ni, 93.4 id,  0.0 wa,  0.0 hi,  1.1 si,  0.0 st
KiB Mem :  8126308 total,   168140 free,  7534988 used,   423180 buff/cache
KiB Swap:        0 total,        0 free,        0 used.   516260 avail Mem

  PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
16846 freerad   20   0  903852 417960   5392 S   0.0  5.1  14:21.93 freeradius
16864 bind      20   0  927648 242732   2512 S   0.7  3.0  42:38.28 named
29219 tunnelmon  20   0 3869952 107172  23700 S   0.0  1.3  25:58.11 tunnelmonitor.py
16859 scrambl+  20   0  110416  58644   2404 S   0.0  0.7   0:02.08 obfsproxy
26697 root      20   0 3933520  43580   2548 S   0.0  0.5  82:43.79 dockerd
19858 timesca+  20   0  305048  33032   8312 S   0.0  0.4   0:58.58 node
16865 stunnel   20   0 4209416  30900   3092 S   1.7  0.4  26:42.16 stunnel4
11899 diamond   20   0   86376  26956   3216 S   0.0  0.3   0:00.00 diamond
16842 diamond   20   0   86376  26828   3088 S   0.0  0.3   2:03.70 diamond
 3244 root      20   0 1865764  25932    572 S   0.0  0.3 581:23.11 containerd
16144 browser+  20   0  795684  25316   2128 S   2.7  0.3  11:23.89 httpproxy
17278 fpsync    20   0   94484  24516   2324 S   0.0  0.3   0:03.22 gunicorn
18243 diamond   20   0   83908  23584   2412 S   0.0  0.3   0:12.34 diamond
18369 diamond   20   0   83908  23484   2384 S   0.0  0.3   0:35.92 diamond
18280 diamond   20   0   83908  23392   2388 S   0.0  0.3   0:25.64 diamond
17558 diamond   20   0   83776  23176   2344 S   0.0  0.3   0:12.33 diamond
18328 diamond   20   0   83908  23148   2140 S   0.0  0.3   0:07.82 diamond
18150 diamond   20   0   83520  23032   2224 S   0.0  0.3   0:14.70 diamond
17523 diamond   20   0   83388  22668   2160 S   0.0  0.3   0:08.29 diamond
18117 diamond   20   0   83520  22620   1896 S   0.0  0.3   0:13.21 diamond
18208 diamond   20   0   83776  22612   1764 S   0.0  0.3   0:01.44 diamond
17405 diamond   20   0   83132  22032   1624 S   0.0  0.3   1:12.88 diamond
17541 diamond   20   0   83528  21604   1000 S   0.0  0.3   0:41.34 diamond
17576 diamond   20   0   83520  21556    900 S   0.0  0.3   0:30.24 diamond
23418 strongs+  20   0   68596  21324   8268 S   3.3  0.3   0:00.10 python3
16638 root      20   0   69176  21112   2404 S   0.0  0.3  11:32.82 supervisord
22541 root      19  -1  102988  20940  12004 S   0.3  0.3   8:22.35 systemd-journal
17484 strongs+  20   0 1632772  17592   4712 S   0.3  0.2  48:52.86 charon
19628 telegraf  20   0 5037948  16768      4 S   0.0  0.2   3:25.14 telegraf
16843 fpsync    20   0   59092  15752   1676 S   0.0  0.2   0:30.13 gunicorn
19977 obfs4pr+  20   0   66352  14932   5496 S   0.0  0.2   0:00.11 python3
16851 openvpn   20   0   46312  14352   3264 S  24.6  0.2 166:22.47 openvpn
16848 openvpn   20   0   44864  13036   3300 S   1.3  0.2 175:15.40 openvpn
17028 diamond   20   0 1090552  12604      0 S   0.0  0.2   1:56.94 diamond
16850 openvpn   20   0   43948  12160   3348 S   5.0  0.1 167:30.49 openvpn
 6754 root      20   0  169264  10304   8764 S   0.0  0.1   0:00.02 sshd
21308 root      20   0  139148   9616    228 S   0.0  0.1   0:13.55 fail2ban-server
16840 openvpn   20   0  180084   9304   3380 S   0.0  0.1   0:07.93 openvpn-api-gra
16847 openvpn   20   0   40764   9208   3572 S   1.0  0.1  58:54.04 openvpn
 7008 root      20   0  161708   8792   7360 S   0.0  0.1   0:00.68 sudo
30989 syslog    20   0  299448   6288   3152 S   0.3  0.1   2:42.85 rsyslogd
19979 obfs4pr+  20   0 1497424   5712      0 S   1.0  0.1  10:05.53 obfs4proxy
    1 root      20   0  226484   5640   2024 S   0.0  0.1 396:39.45 systemd
 6757 tbear     20   0   76756   5556   4360 S   0.0  0.1   0:00.15 systemd
19816 root      20   0 1670468   4244   1548 S   0.0  0.1   0:19.03 docker-proxy
 2662 message+  20   0   53680   4180      0 S   0.0  0.1 114:04.87 dbus-daemon
 7015 root      20   0   21612   4028   3452 S   0.0  0.0   0:00.16 bash
22288 root      20   0   39828   3876   3096 R   0.3  0.0   0:00.22 top

# uname -r
4.15.0-66-generic

I also did check slabtop and not much in use. Also, as this can be seen from /proc/meminfo. I have also tried different things such as using ps_mem to track memory usage. I have ran out of ideas. I'd appreciate if anyone has any ideas. Thanks
Note: A reboot fixes issue temporarily but that's not a practical solution.

A: Is your system feeling better if you run the following command:
#memory before
free -h

#clear pagecache, dentries, inode
sync
echo 3 > /proc/sys/vm/drop_caches

#memory after
free -h

If is it going better and you have more free memory, you may consider adding this command to a daily CRON JOB: An CRON example of this command on a daily basis is given here


text:
Q: How to add required true on collection_select type field I have already tried to add required=> true and :prompt=>"select..." on the collection_select field, but every time I get syntax error. How to solve this error which is below.
.field
  = f.label "Receiver"
  = f.collection_select(:receiver_admin_id,
        Admin.agent_and_admin(current_admin.id, current_admin.parent_master_agent_id),
        :id,
        :agent_name,
        :prompt => 'Select receiver',
        {multiple: true}),
      :required => true

  = f.collection_select(:receiver_admin_id,
        Admin.agent_and_admin(current_admin.id, current_admin.parent_master_agent_id),
        :id,
        :agent_name,
        :prompt => 'Select receiver',
        {multiple: true, required: true})

  = f.collection_select(:receiver_admin_id,
        Admin.agent_and_admin(current_admin.id, current_admin.parent_master_agent_id),
        :id,
        :agent_name,
        :prompt => 'Select receiver',
        {},
        {multiple: true}),
      :required => true

  = f.collection_select :receiver_admin_id,
        Admin.agent_and_admin(current_admin.id, current_admin.parent_master_agent_id),
        :id,
        :agent_name,
        :prompt => 'Select receiver',
        {multiple: true},
        :required => true

A: Try this please:
  = f.collection_select :receiver_admin_id, Admin.agent_and_admin(current_admin.id, current_admin.parent_master_agent_id), :id, :agent_name, {prompt: 'Select receiver'}, {multiple: true, required: true}

A: Your were close almost everytime :) From the docs in the rails guide you have:
collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})

Using the form helpers (f.) mean that the object (first argument) is taken care of so you're left with:
method, collection, value_method, text_method, options, html_options
Both the multiple and required need to be in the html_options so:
= f.collection_select(:receiver_admin_id, Admin.agent_and_admin(current_admin.id, current_admin.parent_master_agent_id), :id, :agent_name, { :prompt => 'Select receiver' }, multiple: true, :required => true)


text:
Q: ROS2 topic "statustext" doesn't execute I want to see some status messages from my drone using "ros2 topic echo /mavros/statustext/recv" in the terminal.
After subscription, I just waiting for a message,(in this time my drone do mission, do takeoff, do landing...) but there's nothing received in that topic.
How to get any message in this topic?

A: ros2 param set /mavros/sys heartbeat_mav_type "GCS"


text:
Q: BeginForm with null controller and action missing parameters I want to add an ID attribute to my form, so I follow the answer here
Originally my code was using:
Html.BeginForm()

and the output looks like this:
<form action="/Controller/Action?Id=5" method="post">

but when I replace the Html.BeginForm() with:
Html.BeginForm(null, null, FormMethod.Post, new { @Id = "blah" });

the output form is missing the parameter:
<form action="/Controller/Action" method="post">

It all seems to just work "magically" if I replace the BeginForm with <form action="" method="post"> but I'd like to understand what's going wrong with the helper version.

A: You're trying to use this version of the method, correct?
<ExtensionAttribute> _
Public Shared Function BeginForm ( _
    htmlHelper As HtmlHelper, _
    actionName As String, _
    controllerName As String, _
    method As FormMethod, _
    htmlAttributes As Object _
) As MvcForm

Couple of things:

*

*htmlAttributes is the attributes of your form tag, and has nothing to do with the ?Id=5 part of your query string.

*Why is your "Id" variable prefixed with an '@' symbol anyway? But again, because of #1 above, it doesn't matter. You don't need to use this.

*I'm guessing that Html.BeginForm() "just works" because you are viewing this as the result of a GET request on /Controller/Action/5. The default POST, then, would have the same URL.

*The same goes if you do  -- in HTML, when you specify the empty string ("") for the URI in the action parameter, it will interpret that as the current URI. See RFC 2396:

4.2. Same-document References

A URI reference that does not contain a URI is a reference to the
    current document.  In other words, an empty URI reference within a
    document is interpreted as a reference to the start of that document,
    and a reference containing only a fragment identifier is a reference
    to the identified fragment of that document.  Traversal of such a
    reference should not result in an additional retrieval action.
    However, if the URI reference occurs in a context that is always
    intended to result in a new request, as in the case of HTML's FORM
    element, then an empty URI reference represents the base URI of the
    current document and should be replaced by that URI when transformed
    into a request.

Does this answer your questions?
Edit: Ah, I see what you're asking now. I'm not sure why passing null doesn't include the same URI. If you explicitly include the action name and controller name, does it work? I've done it this way in MVC applications and it has worked properly.


text:
Q: Catching the output of a console app in visual studio I have a simple console app providing me with some pre-build functionality in Visual Studio 2010. It goes on to spawn other child processes (though waits for the termination of those child processes.
When I run the app outside visual studio all its messages, etc, appear in the console window (ie stdout).  However when I run this app under VS then I don't see any of the output in the build window.
Does anybody know why this is?
Its very annoying.
Edit: On further inspection I have managed to get the stdout of my app to appear but the stdout of the child processes are not appearing.  Any ideas?
I re-direct the stdout of the child processes using the following code:
STARTUPINFO si;
GetStartupInfo( &si );

si.dwFlags      = STARTF_USESTDHANDLES;
si.hStdError    = GetStdHandle( STD_ERROR_HANDLE );
si.hStdInput    = GetStdHandle( STD_INPUT_HANDLE );
si.hStdOutput   = GetStdHandle( STD_OUTPUT_HANDLE );

PROCESS_INFORMATION pi;

// Create the process.
if ( !CreateProcess( applicationName.GetCStr(), cmd.CStr(), NULL, NULL, TRUE, 0, NULL, workingDir.GetCStr(), &si, &pi ) )
{
    // Failed to create process!!
    return false;
}

A: I believe you need to make explicit handles for the child process to hook them up. MSDN has an article on it (or several), see http://msdn.microsoft.com/en-us/library/ms682499%28v=vs.85%29.aspx for example.
Child processes inherit open object handles, but have their own stdin/stdout/etc. handles, unless you go through the proper hoops to create them explicitly for it. That's my understanding, anyway; read the article for more info.


text:
Q: Network service can't access network share under local system account Am running an application as a windows service but when i trying to run it under local system account my service is not able to access network share .but when i run it under a valid user account my service able to acees network share .. but o would like to run it under local system account ??
nd i can n't set full control for everyone on that network share and am on Windows NT machine

A: You shared drive is mapped to a user account with AD domain access.  The network service account has no such access on the other server.  Use a AD domain ID to map the shared drive or run the service under a user account.


text:
Q: GMPY2 install: DLL load failed: %1 is not a valid Win32 application I tried to install gmpy2 on my python distribution (Anaconda 64bit) and I did this by downloading the precompiled .PYD file from http://www.lfd.uci.edu/~gohlke/pythonlibs and put the file in the site-packages folder (I tried this with both the 32 bit and 64 bit versions). However when I ran it and tried to import gmpy2 it gave the following error: DLL load failed: %1 is not a valid Win32 application. I do not know how to fix this as everything I am using is 64 bit. I have looked at some of the other answers on this site but none of them seem to help. Does anyone know what I might try to do?

A: After downloading the GMPY wheel file from Christoph Gohlke's site, you need to open a command window and change to the folder where you downloaded GMPY, and use pip to install it:
~\Downloads\> pip install gmpy2‑2.0.5‑cp27‑none‑win_amd64.whl

If you don't have pip, use conda to install it first:
~> conda install setuptools pip

Note: I used the tilde to represent C:\Users\<username>\.


text:
Q: python numpy mask mean performance Ok, after some searching I can't seem to find a SO question that directly tackles this. I've looked into masked arrays and although they seem cool, I'm not sure if they are what I need.
consider 2 numpy arrays:
zone_data is a 2-d numpy array with clumps of elements with the same value. This is my 'zones'.
value_data is a 2-d numpy array (exact shape of zone_data) with arbitrary values.
I seek a numpy array of same shape as zone_data/value_data that has the average values of each zone in place of the zone numbers.
example...in ascii art form.
zone_data (4 distinct zones):
1, 1, 2, 2
1, 1, 2, 2
3, 3, 4, 4
3, 4, 4, 4

value_data:
1, 2, 3, 6
3, 0, 2, 5
1, 1, 1, 0
2, 4, 2, 1

my result, call it result_data:
1.5, 1.5, 4.0, 4.0
1.5, 1.5, 4.0, 4.0
2.0, 2.0, 1.0, 1.0
2.0, 2.0, 1.0, 1.0

here's the code I have. It works fine as far as giving me a perfect result.
result_data = np.zeros(zone_data.shape)
for i in np.unique(zone_data):
    result_data[zone_data == i] = np.mean(value_data[zone_data == i])

My arrays are big and my code snippet takes several seconds.  I think I have a knowledge gap and haven't hit on anything helpful. The loop aspect needs to be delegated to a library or something...aarg!
I seek help to make this FASTER! Python gods, I seek your wisdom!
EDIT -- adding benchmark script
import numpy as np
import time

zones = np.random.randint(1000, size=(2000,1000))
values = np.random.rand(2000,1000)

print 'start method 1:'
start_time = time.time()

result_data = np.zeros(zones.shape)
for i in np.unique(zones):
    result_data[zones == i] = np.mean(values[zones == i])

print 'done method 1 in %.2f seconds' % (time.time() - start_time)

print
print 'start method 2:'
start_time = time.time()

#your method here!

print 'done method 2 in %.2f seconds' % (time.time() - start_time)

my output:
start method 1:
done method 1 in 4.34 seconds

start method 2:
done method 2 in 0.00 seconds

A: You could use np.bincount:
count = np.bincount(zones.flat)
tot = np.bincount(zones.flat, weights=values.flat)
avg = tot/count
result_data2 = avg[zones]

which gives me
start method 1:
done method 1 in 3.13 seconds

start method 2:
done method 2 in 0.01 seconds
>>>
>>> np.allclose(result_data, result_data2)
True

A: I thought I had seen this in scipy somewhere, but I can't find it anymore. Have you looked there?
Anyway, you can get a first improvement by changing your loop:
result_data = np.empty(zones.shape)  # minor speed gain
for label in np.unique(zones):
    mask = zones==label
    result_data[mask] = np.mean(values[mask])

That way you don't needlessly do the boolean comparison twice. That 'll cut down the execution time a bit.


text:
Q: How to multiply or add the values of a dictionary if the value of the dictionary is a list import csv

ratings_file = open("ratings.txt","r")
book_file = open("booklist.txt","r")
ratinglist = open("ratings.txt").readlines()
booklist = open("booklist.txt").readlines()
keys = [key.strip('\n') for key in ratinglist[0::2]]
values = [value.strip(' \n').split(' ') for value in ratinglist[1::2]]
my_dict = dict(zip(keys, values))
print(my_dict)

My dictionary:
{'Nathan': ['0', '0', '0', '0', '0', '0', '0', '-5', '0', '5', '1', '0', '0',
            '0', '1', '0', '5', '0', '-3', '0', '3', '0', '0', '0', '0', '0',
            '0', '-5', '0', '0', '-3', '5', '0', '5', '0', '3', '0', '0', '1',
            '0', '3', '1', '3', '5', '0', '0', '0', '0', '0', '1', '-5', '0',
            '0', '0', '0']}

I have this dictionary that has a key that is a name, and then the value is a list of values.
I'm wondering if it is possible to add all of the values to the associated key and make it into another dicitonary with a value of keys.
For instance, I was wondering if I could do this:
'Nathan' : ['241']

instead of all of the values being the different integers
I know how to add all of the values together for a list, or a dictionary, but I dont understand how to do it for a dictionary with a list of values.
Thanks

A: Utilising sum() and type() can achieve this.
d = { 'test': [1, 2, 3, 4, 5] }

result = {key: sum(value) for key, value in d.items() if type(value) is list}

#{'test': 15}

If you input is strings, you can change sum(value) to sum(map(int, value))
This will iterate over every key, value pair in the dictionary, check if the value is a list, and sum() the result if True.
To Multiply, you can import numpy and change the above to;
import numpy as np
result = {key: np.prod(value) for key, value in d.items() if type(value) is list}

#{'test': 120}

A: You will have to convert all of the stings to integers before summing.
new_dict = {
    k: [str(sum(map(int, v)))] for k, v in my_dict.items()
}

To multiply, you can use the reduce function:
from functools import reduce

new_dict = {
    k: [str(reduce(lambda x, y: x*y,
                   map(int, v) ))]
    for k, v in my_dict.items()
}

A: First you should convert those strings to int, so :
my_dict['Nathan'] = [int(element) for element in my_dict['Nathan']]

then you add them up to make the final result :
my_dict['Nathan'] = sum(my_dict['Nathan'])

A: Given
d = {'Nathan': ['0', '0', '0', '0', '0', '0', '0', '-5', '0', '5', '1', '0', '0',
        '0', '1', '0', '5', '0', '-3', '0', '3', '0', '0', '0', '0', '0',
        '0', '-5', '0', '0', '-3', '5', '0', '5', '0', '3', '0', '0', '1',
        '0', '3', '1', '3', '5', '0', '0', '0', '0', '0', '1', '-5', '0',
        '0', '0', '0']}

Do
d2 = {k: str(sum(map(int, v))) for k, v in d.items()}

If you want to multiply all items in list do
from operator import mul
from functools import reduce

a = [2, 5, 7, 9]
answer = reduce(mul, a)  # 2 * 5 * 7 * 9 = 630


text:
Q: Having problems with fluent api and relationships I'm having trouble with entity framework 4.1 and relationships.
Here are my classes:
[Table("PROJTABLE")]
    public class Certifikat {
        [Key]
        public long Recid { get; set; }

        public String Projid { get; set; }
        public virtual StandardAndScope StandardInfo { get; set; }
}

[Table("DS_CRT_PROJSTANDARDSCOPE")]
    public class StandardAndScope {
        //[Key]
        //public long RECID { get; set; }
        [Key]
        public String Projid { get; set; }

        public String Standard { get; set; }
        public String Scope { get; set; }
    }

Since I have no control over the databases, I can't change the keys and id's to support the conventions, and I'm stuck with this setup.
My problem is, Certifikat CAN have a relationship with one StandardAndScope. The key in both tables are called Projid - but this isn't strictly the primary key in the database for either tables.
All I really want is to say: "certifikat c join standardandscope s on c.Projid=s.Projid"
How do I accomplish this with fluent api?

A: I think you are looking for something like this:
var result = dataContext.Certifikats
    .Join(dataContext.StandardAndScopes,
        c => c.Projid,
        s => s.Projid,
        (c, s) => new
        {
            Certifikat = c,
            StandardAndScope = s
        });

Where dataContext is an instance of your DbContext class.


text:
Q: If a variable is a pointer to a structure, then which operator is used to access data members of the structure through the pointer variable? If a variable is a pointer to a structure in c, then which operator is used to access data members of the structure through the pointer variable?

A: Use the arrow -> operator.
Example:
structPointer->member
Here's a more in-depth explaination: https://en.cppreference.com/w/c/language/operator_member_access


text:
Q: Ubuntu 14.10 will not reboot or shutdown on dual boot with win 8.1? My system won't even shut down from the command line. I have to do a hard shutdown every time. How can I fix it?

A: The problem carried over to 16.04. I didn't have it on 14.04 because of the earlier kernel.  It seems to be an issue with Bay Trail processors.
Now it seems I solved the issue on 16.04 by upgrading to kernel 4.6.


text:
Q: NuGet push to TFS Feed publishes nuget as V2 but TFS Build expect to restore V3 I have setup a NuGet Package feed in TFS 2017 Update 1.
The NuGet Source is as following

http://tfsserver:8080/tfs/defaultcollection/_packaging/NuGet-Feed/nuget/v3/index.json

Following the instructions stated when connecting to TFS Package Feed, I added NuGet source locally and also try to publish package(s) to the NuGet Feed with following format as an example:
nuget.exe  push -Source "NuGet-Feed" -ApiKey INCTX Microsoft.AspNetCore.Http.Abstractions.1.1.2.nupkg

The result of executing above command is as following:
Pushing Microsoft.AspNetCore.Http.Abstractions.1.1.2.nupkg to 'http://tfsserver:8080/tfs/DefaultCollection/_packaging/23093bd8-41aa-403d-9d3f-5c713b14ce32/nug
et/v2/'...
  PUT http://mtrlpqdc2av-053:8080/tfs/DefaultCollection/_packaging/23093bd8-41aa-403d-9d3f-5c713b14ce32/nuget/v2/
  Accepted http://mtrlpqdc2av-053:8080/tfs/DefaultCollection/_packaging/23093bd8-41aa-403d-9d3f-5c713b14ce32/nuget/v2/ 1702ms
Your package was pushed.

As it shows, the package is published to 'nuget/v2' endpoint.
Running TFS Build with NuGet Restore task: the following command expects
 nuget/V3/ endpoint from the TFS Feed which does not exists.
Note: NuGet restore task in TFS build is customized to use NuGet 4.. version.
GET http://tfsserver:8080/tfs/DefaultCollection/_packaging/23093bd8-41aa-403d-9d3f-5c713b14ce32/nuget/v3/flat2/microsoft.aspnetcore.http.abstractions/1.1.2/microsoft.aspnetcore.http.abstractions.1.1.2.nupkg
The question I guess is why NuGet Push will publish to 'nuget/v2/' endpoint.
TFS Build NuGet Restore Task output:
2017-07-06T15:58:13.0657118Z CredentialProvider.TeamBuild: URI: http://tfsserver:8080/tfs/defaultcollection/_packaging/INCTX-NuGet-Feed/nuget/v3/index.json

2017-07-06T15:58:13.0657118Z CredentialProvider.TeamBuild: Is retry: False
2017-07-06T15:58:13.0657118Z CredentialProvider.TeamBuild: Matched prefix:
2017-07-06T15:58:13.2688422Z CredentialProvider.TeamBuild: This provider only
handles URIs from the build's Team Project Collection
2017-07-06T15:58:13.6125991Z   GET tfsserver:8080/tfs/DefaultCollection/_packaging/23093bd8-41aa-403d-9d3f-5c713b14ce32/nuget/v3/flat2/microsoft.netcore.app/index.json
2017-07-06T15:58:13.6125991Z   GET tfsserver:8080/tfs/DefaultCollection/_packaging/23093bd8-41aa-403d-9d3f-5c713b14ce32/nuget/v3/flat2/microsoft.netcore.app/index.json
2017-07-06T15:58:13.7219799Z   NotFound
Thanks,
Mamrez

A: You may want to check your nuget.config and reference the following:
https://learn.microsoft.com/en-us/nuget/tools/nuget-exe-cli-reference#push
it says you can either specify it on push or define DefaultPushSource in the config. I might suspect your v2 source is defined as DefaultPushSource in the config.
try: nuget.exe config DefaultPushSource to see what it is set to.

A: Running on the TFS App-Tier through command line also issued an error which stated the NuGet source couldn't be reached.
Finally figured out that which NuGet.config file was being used and as the result, the NuGet publish from TFS start working both on App Tier and in the TFS build.


text:
Q: c# - how to copy a section of "byte[]" to another array?
Possible Duplicate:
How to copy part of an array to another array in C#

c# - how to copy a section of "byte[]" variable to another array?

A: how about something like:
var byteArray = new byte[] { 1, 0, 1 };
var startIndex = 1;
var length = 2;

byteArray.Skip(startIndex).Take(length).ToArray();


text:
Q: How do I make it so players can only place one type of item in a chest in minecraft? While creating player interface on a server, I have a place where the players can put items in a chest to get a reward. However, If they place other items in the chest it will still give them the reward, because I'm using comparators. Is there a way I can block them from placing anything other than the items I want them to get a reward for in the chests?

A: You can't, but you can make the counter increment for only a certain type of items:

The redstone part, as visible, consists of a AND gate with a clock as one input and a comparator as the second input, with it's output leading to the dropper (under the chest).
The command part consists of four command blocks, the first (leftmost) one set to Repeat Need Redstone and all the others to Chain Always Active. Here are the commands, explained, from left to right:

*

*/scoreboard objectives add itemOnGround dummy

*

*Explanation:
/scoreboard objectives add   % create a new scoreboard objective (variable)
itemOnGround                 % named "itemOnGround"
dummy                        % and make it self-standing

*/scoreboard players set @e[type=Item,c=1,r=4] itemOnGround 1 {Item:{id:minecraft:stone}}
The above command will check for an item that has an id minecraft:stone. Change that to your preferred item ID. You can as well adjust the r value.

*

*Explanation:
/scoreboard players set   % set scoreboard objective (variable)
@e[type=Item,c=1,r=4]     % for the 1 closest 'Item' entities under 4 blocks away
itemOnGround              % named 'itemOnGroud'
1                         % to 1
{Item:{id:minecraft:stone}}       % with 'Item' selecting only dropped items with id 'minecraft:stone'

*execute @e[score_itemOnGround_min=1] ~ ~ ~ /say hello
Runs the command /say hello each time there is a stone item (less than 4 blocks away) on the ground. Replace /say hello with any command you'd like to run for each item.

*

*Explanation:
execute                         % for all
@e[score_itemOnGround_min=1]    % entities with a score of 'itemOnGround' bigger than 1
~ ~ ~                           % run at their coordinates
/say hello                      % the command '/say hello'

*/kill @e[score_itemOnGround_min=1]
Just kills (deletes) all already counted items, so they don't get counted twice. Doesn't kill other items. Explanation is trivial here.
Update: Since it may seem complicated, I created a one-command version, rewarding you by saying "hello" for a stone block item, for you to try it out. You can copy it from here (pastebin) (paste into command block and power it. Do not move when running the command!!).

Old solution:
You can block any other items getting the player points by placing hoppers under the chest, in a way blocking all items other than the preferred ones to the "score updater":

(source)

Then, if your award item is 64-stackable, place 22 of it into the topmost hopper, if 16-stackable, place 5 (one in each slot): 1
If a container above the hopper contains any other item then your, it'll remain in the container; else, it'll get transported down the hoppers into the downmost container.
Connect a comparator to that container (chest) to get your item score.

1: non-stackable items can't be detected so.

A: If I understand correctly, you are not using any plugins that could help you.
To do it in normal Redstone, just place hoppers underneath the chest to take the items out automatically. After that, make an item sorter (see Minecraft Wiki: Hoppers) and test the output with your comparator only after the sorting of the specific items.
(You can also give the wrong items back if needed)


text:
Q: Python how to take a list as a parameter and edit its values? I have the following code:
def radixSort(A):

    #get max amount of digits

    A = sortByDigit(A, maxDigits) #this works
    print(A) #prints A as sorted

if __name__ == "__main__":
    A = [int(100*random.random()) for i in range(10)]
    radixSort(A)
    print(A) #prints unsorted

Why does changing A in radixSort not change A in the main method ? I realize I could simply add a return statement in radixSort, and an assignment statement in the main method, but the code has to pass the following test case:
    def testrRadixSort(self):
        A = [4, 3, 2]
        radixSort(A)
        self.assertEqual(A, [4,3,2])

A: sortByDigit isn't sorting inplace. It's creating a new list and returning a reference to that.
You can replace the contents of A with the content of the new list with this simple change
A[:] = sortByDigit(A, maxDigits) #this works

Alternatively you could modify sortByDigit so it does sort inplace

A: The problem is on this line:
A = sortByDigit(A, maxDigits)

You created a local assignment of A, which does not overwrite the global copy of A.
You need to make sortByDigit modify the contents of A, not return a new list.
An alternative is to add
global A

Before that line so it will modify the global A.
However with regards to global variables see kindall's comment below.

A: This behaviour is about passing arguments by reference or by value.  There already is a great explanation of this behaviour on StackOverflow.
This means:  You cannot reassign the given list, but you can modify the existing instance, e. g. with the append method.

A: I'm assuming sortByDigit() returns a sorted copy of the list rather than sorting it in place. In which case, simply replace the contents of the list with the result of that call, via slice assignment:
A[:] = sortByDigit(A, maxDigits)

A: Nah, you can't change A like that. Keep in mind that A in your radixSort function (local scope) is different with A in your main function (global scope).
To achieve what you need, you can declare it as a global variable. However, this is not the best method since using global vars can get you to a confusing scope problem, therefore it's not recommended. But this how to do it:
def radixSort(lst): #we can refer to the passed variable as lst
    global A

This doesn't sort A inplace, but it assigns the sorted lst to A.
Or better, assign the sorted value to A with slice notation:
A[:] = sortByDigit(A, maxDigits) #store the sorted list in A

Or even better, return it as sorted, and then reassign A with the sorted value:
def radixSort(A):

    #get max amount of digits

    A = sortByDigit(A, maxDigits) #this works
    print(A) #prints A as sorted
    return A

And in your main program:
if __name__ == "__main__":
    A = [int(100*random.random()) for i in range(10)]
    A = radixSort(A)
    print(A) #prints sorted
    self.assertEqual(A, [4,3,2]) #self.assertEqual(sorted, unsorted)

Also, it's not a good practice to capitalize identifiers. Capitalized words is usually reserved for classes.
So:
def radixSort(a):

    #get max amount of digits

    a = sortByDigit(a, maxDigits) #this works
    print(a) #prints A as sorted
    return a

if __name__ == "__main__":
    a = [int(100*random.random()) for i in range(10)]
    a = radixSort(a)
    print(a) #prints sorted
    self.assertEqual(A, [4,3,2]) #self.assertEqual(sorted, unsorted)

Hope this helps!


text:
Q: Variável JS para PHP ou direto no BD Bom dia. Sou um programador iniciante, e estou desenvolvendo um app web de vendas, que soma todos os preços dos produtos incluídos dinamicamente por javascript:

E joga nesta div:

            <?php echo "O total é R$ " ?>

Banco:
 <?php

     $connect = mysqli_connect("localhost", "root", "", "narguile");

     $number = count($_POST["input_quantidade_venda"]);

     $soma_venda = $_POST['soma_venda'];

     if($number > 0) {

         for($i=0; $i<$number; $i++) {

             if(trim($_POST["input_quantidade_venda"][$i] != '')) {

                 $sql = "INSERT INTO vendas(quantidade, total) VALUES('".mysqli_real_escape_string($connect, $_POST["input_quantidade_venda"][$i])."', '$soma_venda')";
            mysqli_query($connect, $sql);
             }
         }

         echo "Venda cadastrada!";
     }

     else {

         echo "Não rolou";
     }
 ?>

Mas preciso colocar o valor desse "soma_venda" no Banco de Dados, e sinceramente, não faço ideia de como. Se alguém puder me ajudar, eu agradeço.

A: Crie um input hidden para receber o valor total e enviar junto no serialize.
Coloque-o após essa div:

<input type="hidden" name="soma_venda">

E na função que faz a soma, acrescente:
("[name=soma_venda]").val(total);

Ficando assim:
function somaTotal(){
   var total = 0;

   $(".input_preco_venda").each(function(){
      total += parseFloat($(this).text());
   });

   $(".soma_venda").text(total);
   $("[name=soma_venda]").val(total);
}

Pronto. O valor da soma total irá junto no serialize e será recebida no PHP na variável $soma_venda = $_POST['soma_venda'];.


text:
Q: Calculate the inverse of a matrix that is a sum of outer products I am trying to find the inverse of matrix in the following form
$\mathbf{R}=\sigma_0\mathbf{I} + \Sigma_{k=1}^{P}\sigma_k\mathbf{d}_k\mathbf{d}_k^H$
where $\mathbf{I}$ is an $M\times M$ identity matrix and $\mathbf{d}_k$ is an $M\times1$ complex column vector. $\sigma_0$ and $\sigma_k$ are real, positive constants.
For $P=1$ and $P=2$, by using matrix inverse lemma, the inverse can be written as a weighted sum of outer products between column vectors $\mathbf{d}_k$. I guess for other values of $P$, it can still be written in such form.
But for $P\ge3$, the calculation is lengthy, tedious and seems impossible.
Is my guess right? If so, what is the general formula for the inverse?
Thank you!