Woocommerce wrong fragments passed back from woocommerce_add_to_cart_fragments

Question: I'm creating a custom WooCommerce cart and updating the quantity of a cart item works correctly. The only problem is that it doesn't automatically refresh, only works after page load.
My current code, which uses the woocommerce_add_to_cart_fragments hook and uses the passed in $fragments object. According to what I've seen around this is the correct way to go, but this doesn't work and I've debugged and to me the problem seems to be that the $fragments I get in the hook doesn't have my original html but instead a html that looks like this:

            ×
                <img width="300" height="300"
                    src="http://velosity-dev-wordpress.local/wp-content/uploads/2021/09/mathilde-langevin-WxHJEMUnlIM-unsplash-300x300.jpg"
                    class="attachment-woocommerce_thumbnail size-woocommerce_thumbnail" alt="" loading="lazy"
                    srcset="http://velosity-dev-wordpress.local/wp-content/uploads/2021/09/mathilde-langevin-WxHJEMUnlIM-unsplash-300x300.jpg 300w, http://velosity-dev-wordpress.local/wp-content/uploads/2021/09/mathilde-langevin-WxHJEMUnlIM-unsplash-150x150.jpg 150w, http://velosity-dev-wordpress.local/wp-content/uploads/2021/09/mathilde-langevin-WxHJEMUnlIM-unsplash-100x100.jpg 100w"
                    sizes="(max-width: 300px) 100vw, 300px" />Subber One
            2 × <bdi>$349.00</bdi>

        Subtotal: <bdi>$698.00</bdi>

View cartCheckout

I don't really know how to pass in the correct 'active' html in to this hook, so any pointer would be greatly appreciated! Big thanks in advance!
My custom cart html/php (inside a file called header-shopping-cart.php)

    <?php foreach(WC()->cart->get_cart() as $cart_item_key => $cart_item) : ?>

        <?php echo $cart_item['data']->get_image(); ?>

<?php echo $cart_item['data']->get_title() ?>

                <input type="number" id="quantity_614459a588590" class="input-text qty text" step="1" min="0" max=""
                    name="cart[<?php echo $cart_item_key ?>][qty]" value="<?php echo $cart_item['quantity']  ?>"
                    title="Qty" size="4" placeholder="" inputmode="numeric">

<?php echo $cart_item['data']->get_price_html() ?>

    <? endforeach; ?>

My JS function (inside custom.js)
jQuery(function ($) {
  $(document).on("change", "input.qty", function () {
    var $thisbutton = $(this);
    var cart_item_key = $(this)
      .attr("name")
      .replace(/cart\[([\w]+)\]\[qty\]/g, "$1");
    var item_quantity = $(this).val();
    var currentVal = parseFloat(item_quantity);

    $.ajax({
      type: "POST",
      url: cart_qty_ajax.ajax_url,
      data: {
        action: "my_cart_qty",
        cart_item_key: cart_item_key,
        quantity: currentVal,
      },
      success: function (response) {
        jQuery(document.body).trigger("added_to_cart", [response.fragments, response.cart_hash, $thisbutton]);
      },
    });
  });
});

My php-functions (inside functions.php)
<?php
function enqueue_cart_qty_ajax() {
        wp_register_script( 'my_cart_qty-ajax-js', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ), '', true );
        wp_localize_script( 'my_cart_qty-ajax-js', 'cart_qty_ajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
        wp_enqueue_script( 'my_cart_qty-ajax-js' );
    }
    add_action('wp_enqueue_scripts', 'enqueue_cart_qty_ajax');

    function ajax_my_cart_qty() {
        // Set item key as the hash found in input.qty's name
        $cart_item_key = $_POST['cart_item_key'];
        $quantity = $_POST['quantity'];

        // Get the array of values owned by the product we're updating
        $threeball_product_values = WC()->cart->get_cart_item( $cart_item_key );
        // Get the quantity of the item in the cart
        $threeball_product_quantity = apply_filters( 'woocommerce_stock_amount_cart_item', apply_filters( 'woocommerce_stock_amount', preg_replace( "/[^0-9\.]/", '', filter_var($_POST['quantity'], FILTER_SANITIZE_NUMBER_INT)) ), $cart_item_key );
        // Update cart validation
        $passed_validation  = apply_filters( 'woocommerce_update_cart_validation', true, $cart_item_key, $threeball_product_values, $threeball_product_quantity );

        // Update the quantity of the item in the cart
        if ( $passed_validation ) {
            WC()->cart->set_quantity( $cart_item_key, $threeball_product_quantity, true );
        }

        // Refresh the page
        echo do_shortcode( '[woocommerce_cart]' );

        die();
    }
    add_action('wp_ajax_my_cart_qty', 'ajax_my_cart_qty');
    add_action('wp_ajax_nopriv_my_cart_qty', 'ajax_my_cart_qty');

    //Responsive cart
    add_filter( 'woocommerce_add_to_cart_fragments', 'ajaxify_components', 10, 1 );
    function ajaxify_components( $fragments ) {
        ob_start();
    ?>

        <?php foreach(WC()->cart->get_cart() as $cart_item_key => $cart_item) : ?>

            <?php echo $cart_item['data']->get_image(); ?>

<?php echo $cart_item['data']->get_title() ?>

                    <input type="number" id="quantity_614459a588590" class="input-text qty text" step="1" min="0" max=""
                        name="cart[<?php echo $cart_item_key ?>][qty]" value="<?php echo $cart_item['quantity']  ?>"
                        title="Qty" size="4" placeholder="" inputmode="numeric">

<?php echo $cart_item['data']->get_price_html() ?>

        <? endforeach; ?>

    <?php
        $fragments['#cart-items'] = ob_get_clean();

        return $fragments;
    }

Hope someone can give me a pointer in the right direction. Thanks!
Answer: I just tested your code, and it seems to work:

On click, the ajax is made and my cart content is updated
the echo do_shortcode( '[woocommerce_cart]' ); is not working atm, as it thinks the cart is empty (and returns "empty cart" HTML message). But I don't see why you need the complete woocommerce cart HTML as a response here. Also, you use the response in tour JS as an object, but returning the do_shortcode will return a raw HTML string only.
the AJAX ends, and jQuery(document.body).trigger("added_to_cart") is called, which trigger the Woocommere cart fragment to refresh. As the AJAX call shortcode response is "wrong", the response object is not correct, but we can still trigger the event. Just make sure your custom listener handle the "no parameter" case
the cart fragment is refreshed, with your custom HTML

Take care about your <? endforeach; ?> that misses the <?php.

EDIT: After a quick test, it seems the woocommerce_cart shortcode output uses the woocommerce templates. So you could try to edit the Woocommerce Cart template files in your child theme to change the HTML output. (if you really need the cart HTML as the response to your custom ajax call).


How much material would it take to cement a 1 mile driveway

Question: How much material would it take to cement a 1 mile driveway
I would like to know, in pounds, how much material it would take to cement a driveway, exactly 1 mile in length, how many pounds of sand, cement mixture and finally gravel//brick
I think it is 2 parts sand, to 1 part cement mix to 4 parts gravel, so 2 pounds of sand 1 pound of cement and four pounds of gravel, but I also do not know how much area that would cover, the road I'm also unsure how thick it should be, some people do 2 inches the real roads I think are poured 8-12 inches
Its about 10-12 foot in width, not many sharp turns, 2 which is the same turn actually.
Two steep hills, one hill about a fifth of a mile couldn't tell on the angle.
An answer below has given me pretty much what I needed. The other thing, was that I read concrete mix could be halfed out for half its part in volcanic ash to make a mix that would last two to three times as long. I'm sorry it has taken me all day to come back and update this comment.
Comment: You need to know the width of the driveway and the depth/thickness you want to concrete (depends on the load you expect it to handle).
Comment: 2 inch won't hold up to a pickup truck , 4" won't hold up to a dump truck, what is the base available? Lots of questions including the width already asked. We usually calculate yards required not by weight.
Comment: A lot. Like more than one truck. Wait, you're going to mix it on site? Uh... I'ma be outta town that week.
Answer: Wow, this is complicated. Good road design requires a good base and any turns require an added width due to a turning vehicle. (The added width at turns depends on the size of any anticipated vehicles.)
Let's start with the basics. Let's say it's straight and it's 10' wide. Depending on soils conditions, I'd use a minimum of 6" gravel base. I like 3" minus crushed rock. So, for the base: 5,280 ft x 10' wide x .5' deep = 26,400 cu. ft. OR 26,400 cu. ft. / 27 = 978 cu. yards. You want it in lbs., so gravel can weigh about 2,800 lbs. per cubic yard...so 2800 x 978 = 2.7 mil. Lbs.
Now the concrete. I'd recommend a 4" minimum slab of 3,000 psi concrete. So, 5,280 x 10' x .33 = 17,424 cu. ft. OR, 17,424 / 27 = 645 cu. yards.
There are lots of mix designs for 3,000 psi concrete. You should order it from the local concrete company because you'll want air entrainment too.
Big job....next: Determine how many corners and if you'll be driving over your base before you pour, because some of the will be pushed into the ground and you'll need to "re-level" before you pour.
Comment: For a UK flavoured answer, see http://www.pavingexpert.com/concrete.htm
Comment: Driving over the base is a goodvthing, though, tamps it down.
Comment: @Harper Yes compaction is key, but will create ruts that need to be fixed or the thickness of the concrete slab increased accordingly.


Software that clicks e-mail links on page?

Question: We are experiencing a strange bug on our website which we think is related to the software installed on user's computers. We have an e-mail link on a lot of pages, which is created using Javascript (so spambots won't get it).
It seems the link is "clicked" automatically on some user's machines. Some users then discard the window by clicking Send on the e-mail window that pops up, resulting in a ton of e-mails to us.
When inspecting the Apache log, nothing weird can be seen in the browser string. Can this be a download accelerator/prefetcher gone haywire? Any other theories as to what this might be?
The link in the HTML is written like this (it is autogenerated by Smarty):

Answer: Could something in the browser be prefetching the links? For example, the Firefox  extension Fasterfox does that (which is the reason why I don't use it). I seem to remember Google at one time also had brought out a browser accelerator using the same concept. And the AVG antivirus' Linkscanner is infamous for doing it too (all in the name of scanning for bad sites).
In short: don't use links for something that changes a state, for example for logging out, deleting a record (gasp!) or sending email. Use a button instead.
Comment: I don't think Fasterfox can be stupid enough to click an e-mail link? This is a HTML -style link. I'm going to test FasterFox just to be sure.
Answer: My only suggestion would indeed be that some program (browser, extension, bot, indexer) reads the page and then opens the link and sends the mail, but I've never seen that before.
Is there anything you can see from the mail messages you get? Recurring IP addresses or X-Mailer?
Perhaps you can ask one of the users about their system setup - you have their e-mail address.
Comment: These come from actual users, not a bot. We have made contact with one user, who confirmed the event order mentioned in the question. Our users view a lot of pages, so one e-mail per page becomes a lot of e-mails.
Answer: Personally, I'd try to solve this by changing from a mailto: link to a contact form - though that doesn't directly answer the question you asked.
The other suggestions of link pre-fetchers seem the most probable.
I suppose it might even be related to caching from an ISP, if it's trying to pre-spider a page so the linked-to pages load quicker?


What do you do/ask when hiring a contractor?

Question: In a world where every guy with a truck full of tools is a "contractor", how do you weed out the good from the bad?
Answer: A few ideas:

Ask for references.  This can work nice, but since the contractor can choose which references to give you, doesn't always give an accurate picture.
If they are in a regulated trade (electrician, plumber, builder, etc.) ask your local city code inspector.  They know all the contractors and know which ones do good work and which ones do just enough to pass inspection.
Check with your local building/plumbing/electrical supply stores.  They know the contractors and which ones are good or bad.
Comment: Ask for references AND then go look at their work (and talk to the owner that had them do the work).
Comment: +1 for recommending a local store. Best electrician i found was recommended by the owner of a local hardware store.
Comment: If you know people in related industries, ask for referrals.  For example, a friend of mine from our church is a high-end builder, and I've had "his" electrician and roofer out before to look at various issues.
Answer: My Significant Other owns a small millwork shop dealing in interior and exterior remodeling projects. I have worked for him for the past 10 summers doing finish work. We both know many, many other contractors; the good and the bad. Here are some guidelines from the inside:

If the price seems really steep, the contractor doesn't want your job. He's busy, but since many contractors live from job to job, they feel compelled to bid on jobs and give you a "go away" price. This means you will have to take a number and wait for him to finish whoever was ahead of you. So ask: If you can't do this job, who would you recommend?
Asking for money up front is NOT a no-no in big remodeling jobs or expensive custom projects.The traditional rule is: 1/3 up front, 1/3 halfway through (this is where you check for change orders, mistakes, add-ons, etc.) and 1/3 upon completion. Good independent contractors get stiffed all the time. The contractor plans on the payment schedule to cover his costs for special materials, such as custom wood or hardware for your cabinets, colored pavers for your driveway, special order paint or finishes, or special historic houseparts. The contractor cannot always front you for your expensive tastes or special orders that may exceed his estimates when transportation costs rise suddenly. If you have concerns about itemizing, ask for daily receipts or a work journal.
Show the contractor pictures of what you want. Be specific. It is easier for a contractor to try to match a picture than try to read your mind.  If you want a tree cut down, did you ask him to haul the wood out, too? If he's putting in a furnace, who's taking the old one out?  The old adage about not assuming rings true.
Plan ahead. Don't call someone to make a mantel for Christmas stockings in November.He has customers who called in October and put down a deposit. If he does manage to fit you in and get your rush job done,  pay him in cash.
Don't judge a book by it's truck. "Work trucks" should look like that. Ours is about 15 years old, with a trailer hitch for the tool trailer and materials. Look for solid carrying racks, good tires, and a trailer hitch. A rusted-out junker, however is a pretty good sign that he's a hack. Any kind of sedan means it's his first job.
Engage in a planning meeting  when he comes to do the estimate. Talk to him.Share your budget. Ask questions like: What are the steps in this remodel? How long has he been in the business? Does he have an area of specialty? If you have a timeline, ask how realistic it is. Ask about disruption to the household- for example, will he have to shut a water main off? What material will he put in the windows when they are being repaired?
Be flexible to minor setbacks. If you're getting a new shower installed, and  a problem with your plumbing arises, realize that every additional thing that needs to be fixed within the range of the job pushes your original deadline back.
Speak up if it's not going right. If the cabinet doors aren't flush, the hardware is wrong, or the trim colors look ugly, say something. Don't wait until he's done. If you're not happy, speak up ASAP-  don't wait until the end of the job, when he has to rip it all out or start over.
Finally, many left-brain, handy guys are not super articulate or chatty- they focus on the job. Super chatty, charming guys are going to take longer on the job, but you'll have some nice conversations.
Answer: In the US, check their status with the Better Business Bureau.  Also, if you hire contractors frequently, you should probably look into subscribing to Angie's List, which crowdsources customer reviews of contractors and other service providers.
Answer: Talk to at least 2.
Every contractor does things differently. Each will bring up concerns and ideas that others do not. You will learn a lot from these conversations that will help you make a good decision.
Answer: I rarely post on any forum, but I think I can provide some helpful suggestions, due to years of experience. I hope you find my suggestions more useful.
Often the quality of the contractor or more importantly, the quality of the work, is a direct reflection of who controls: the timing/amount of payments and who controls when the job ends.

I agree 100% with other posts, never, ever pay anything up front, the peace of mind alone is worth any possible discount or benefit the contractor could offer. If he refuses and demands upfront payment, he just did you a favor, you know to move on.
Craig's List is great to post your needs, its free and typically generates 10-20 very motivated contractors or laborers.  Many can be screened via simple emails asking for pictures of work or asking them how they would address your problem. Dealing directly with the person doing the work not only saves $$$ the quality of the work will be better (unlikely to sub out to someone you haven't interview).
Perhaps surprisingly, I believe contracting by the hour is your best bet. You can dictate the rate ($15-$25 an hour) or you can allow the rate to vary by market.  Because the contractor will likely add $$$ to his "by the job quote" to cover any unknown issues (regardless of the likelihood), paying by the hour will typically result in tremendous savings to you.  A by the hour arrangement allows for a sharing of unknown risks, in a "by the job" quote, the contractor effectively transfers the risk of the unknown to you.
Not only will a by the hour arrangement be cheaper, the quality will also likely be better.  In a "by the job" quote, the contractor/worker is incented to take as many short-cuts (reductions in quality) as possible to get the job done and get paid. Paying by the hour better aligns the contractor/laborer's interests and yours – both want the job to take as long as necessary to create a higher quality result.  Of course if you can't check in to ensure he/she isn't standing around texting, paying by the hour can be less beneficial, however it still might be cheaper than a bloated for uncertainties in a "by the job" quote.
Control of the when payments are made also results in more of the contractor/ laborer and thus higher project quality.  The contractor/laborer will be encouraged to provide high quality at a minimum of hours – he doesn't want to jeopardize payments or future work.
The old adage "you get what you pay for" not longer applies (if it ever did). Just because someone charges you a higher price doesn't mean they are better. Accepting the lowest price is also not a guarantee of lowest quality.
Lastly, by the hour is a lower risk strategy, if they are not performing, you can easily fire them, you're not stuck for the duration of the job with a low quality resource.
Comment: +1 for the suggestion to pay by the hour and fire them if they aren't performing
Answer: I've learned from dealing with contractors recently that I have to define exactly what I want done so that there is no misunderstanding or room to scale back on the required work.
For example, if I want a tree removed I have to describe whether or not I want the roots removed, stump grounded down, etc. You don't want to have to say, "I just assumed you were going to do X, Y, and Z." Consider all of the details you can think of. This can be difficult if you're not familiar with the various approaches and don't know all of the details involved in a job (it's why we hire professionals in the first place), but the more you can research and document the better.
Comment: However, you can use this to your advantage in making a decision.  A good contractor will ask you about these specs. up front.  Do you want the roots removed? Do you want me to haul away the wood?  Would you like the trunk cut up for firewood?   All these questions would indicate to me that this contractor has done this type of work before.

As a software developer, it is contingent on ME to draw the requirements out of the client, as I am the expert.  I expect the same from a contractor.
Answer: I always try and get 3 or 4 different quotes.
You'd be amazed at that difference in price and analysis of the problem/work involved. I have had differences, major differences; one person quoted £1,500, another £6k.
The major thing I have learnt is that you have to manage contractors - don't assume anything, every little detail. And get it all written up. And obviously don't pay for time, pay for a job, and of course don't pay until yr happy with the work.
If anyone starts quoting a daily rate I run a mile.
People have mentioned looking at peoples cars etc I don't think this is useful, who cares what car etc. As logn the work is up to standard and the price is reasonable  - I expect a decent worker to make a healthy profit, so why not ?
If the work is not up to standard or there a various problems call a stop to the work, I guess you could even include that in your original contract.
The other thing I have learnt, try and do things yourself, some of these things are not that hard. Its just having the confidence to do them. Even if you do make a mistake it can normally be rectified.
Answer: Ask for proof of insurance that covers you if something happens while they are doing the job. Even painters we've hired gave us a copy of their insurance.
Answer: Ask to see some of their work and talk to previous clients. The good ones will put you in touch with previous clients straight away. The bad ones will prevaricate.
Don't employ the ones that come round touting for business. If they have the time to drive around looking for "damaged" roofs, driveways in need of repair etc. then they can't be that good. Having a full schedule is usually a good sign.
Comment: Because I didn't know that word: http://en.wiktionary.org/wiki/prevaricate
Answer: Find out the payment terms.  If they want all or most up-front, it is generally a bad sign.
Answer:
If he's the lowest bidder, watch out.
If he (or she) promises too much, watch out.
I agree with the post above that said "Get it in writing". Get changes in writing too.
If you make the deal with the Dad and then he drops his son and son in law off to do the work, you might have a problem, although the phrase "Don't make me call your Daddy" is helpful in this case.

Money up front is a no-no.
As for cars, if a contractor is driving a shiny new Linconln Navigator (think Radon guys), then I think he's ripping me off. I want to see an honest work vehicle, but no junker either.
Answer: I typically ask around at work for referrals - we have a junk mail board that's a great place for posts like that.  You could also look at the Better Business Bureau for your area, or look at a site like Angie's List. You could also ask the contractor for references.
Answer: There are a number of good ideas already given, I would add to check their license.  I know Florida keeps a nice online presence http://www.myflorida.com/licensee/
Answer: @Eric's list is great.  I'd add a few more:

Ask what they do to keep up with developments in their trade.  Most will give you a blank look but some will be incredibly excited to tell you about the latest issue of FHB or Journal of Light Construction.
More of a negative thing, but if anybody "helps" you by telling you how to get around permits, etc., then move on to the next candidate.
Look at the condition of their tools and vehicles.  The don't have to be new, obviously, but I've found that respect for tools goes hand-in-hand with good work.
Comment: On the other side of things, if it looks like they just loaded up their toolbox down at Lowes, they probably don't have much experience either...
Answer: I don't know of any contractor who will quote a job by the hour. On the contrary a knowledgeable contractor knows exactly how long a given job will take and will do his best to finish the job within that time frame.  He will also do his best to do it right to avoid call backs which cost him time and money. A good contractor will provide a punch list, that is a list of things which need to be corrected before final payment.
Answer: One of the best pieces of advice someone gave us when my partner and I bought our first house (an 1867 fixer upper) was to find out what work a potential contractor was doing at that moment, and ask to go see it. I had no idea that this was something you could do, but it's apparently not uncommon. It's even in some contractors' contracts that homeowners are expected to be available to show off the work they had done and talk to potential future clients. It's a great way to know that you're getting a real look at their work. And if they're hesitant to show you, that might be a bad sign.
But this obviously isn't always possible, so another great option is to ask for the contact info for recent clients. This is also a lot more trustworthy than online reviews- those can be faked so easily. Or they can be from a long time ago. This article (https://makeitright.ca/holmes-advice/bathroom-renovation/how-to-hire-a-contractor-do-a-background-check/) recommends getting 10 numbers from previous clients. I'm not sure I'd be dedicated enough to do that much research, but I'm sure it would be good to be that thorough!
A few other things that have helped us over the years (sorry if I'm listing stuff that's already been gone over in other comments..)
Don't trust a contractor that can't (or won't) give you a good idea of timelines and cost. If there's any amount of vague language, treat that like a red flag. Ask very specifically for clarification up front, and make sure the contract includes those details. Obviously, complications can come up that change the price, but they can be clear with you ahead of time about what those may be. This is an example of one company's list of potential problems that could make the price (or timeline) go up (under the question "Is there a possibility my project could go over the initial estimated price?" https://keselmangroup.com/frequently-asked-questions/)
And we've found all of our favorite contractors either through family/ friends/ neighbors recommendations, OR going to our local hardware store and asking around there. That's actually been a goldmine of info for us. We've met lots of handy people with knowledge and connections.
Lastly, you don't necessarily need to avoid contractors who ask for cash. We heard the advice never to pay a contractor cash over and over, but if we had listened to this, we would have missed out on some great work. Just make sure that they're vetted, carry all necessary insurance, give you a thorough contract, and provide you with a detailed receipt after you pay them. Here's an article that has the same advice: https://money.com/paying-handyman-cash-home-repairs/.
Again, I hope I didn't just rehash a lot of advice that's already been given here- I tried not to- but I thought I'd add my two cents from our experience.


nail pop in bathroom ceiling

Question: Should I be concerned about this nail pop. I live in an apartment so I can't really do much to the ceiling. Is it just a cosmetic thing? Is my safety at risk? Will it cause water leaks? Please help
Comment: Got any... White out? Chalk? Paper spit ball....
Comment: With nails, it's only a question of *when* they will pop.
Answer: Just one nail is not a safety risk. There drywall is not supposed to be a barrier to water infiltration, so this popped nail will not risk water getting in. Watch out if you see water stains on the ceiling, or nearby nails popping. That means that water is getting in the drywall, where it should not be. Then call your landlord.
Comment: Wouldn't hurt to call the landlord/maintenance crew _now_. At a minimum, it gets it on the record for when you've noticed it and that you've taken appropriate action. This way, they can't come back late claiming "you should have told us sooner, we're going to charge you for the repair!".

nail pop in bathroom ceiling


List active rules in Iptables

Question: I would like to help me check the active rules in the iptables firewall.
My S.O is Ubuntu Server 14.04.3 LTS Trusty.
Answer: You can list the rules with the following two commands:
sudo iptables -v -x -n -L
sudo iptables -t nat -v -x -n -L

Those are the ones I prefer, because it can be informative to observe the packet counters, particularly when trying to debug. Also, not doing name resolution can save a lot of time.
However, there is another command, which pretty much provides the same information:
sudo iptables-save -c

Answer: sudo iptstate -1
Depends:
sudo apt-get install iptstate
sudo modprobe ip_conntrack
PS: I don't recommend to use sudo iptstate, cause sometimes, something goes wrong about Segmentation Fault.

List active rules in Iptables


Number of join-irreducibles and rank in a finite lattice

Question: Let $(L, r)$ be a finite, ranked lattice. Is
$$r(x) = \#\{j \leq x : j \in L \text{ is join-irreducible}\}$$
for all $x \in L$?
This may be a naive question, though my lattice theory is weak.
Answer: I could give a very trivial negative answer just by stating that, if $|L|=n$, and we define a rank function such that $r(0)=n+1$, then the formula can't hold (notice that, at least in the Wikipedia article, it's not necessary that $r(0)=0$).
That said, it's reasonable to think that what you have in mind is a rank function $r$ such that $r(0)=0$.
Even in that case, the result doesn't hold, as the following example shows:

This is a ranked lattice with ranks $0,1,2,3$, but for the top element, $1$, which satisfies $r(1)=3$, we have $4$ join-irreducibles below it.
All other elements satisfy your formula.

Update
As I noted in a comment below, the $\mathbf M_3$ lattice (see here) is an even simpler counter-example.
Comment: Thanks for the counterexample. Of course $r(0) = 0$ is required. After looking around some more I believe the equality holds for distributive lattices, though I didn't immediately find a citation (...or try to prove it...). Does $\leq$ always hold?
Comment: @JSwanson Yes, you can prove the inequality by induction, for the general case, using the fact that in every finite lattice, each element is the join of the join-irreducible elements below it. In the case of a distributive lattice, I believe you are right, that your formula holds, and that the [Birkhoff's representation theorem](https://en.wikipedia.org/wiki/Birkhoff%27s_representation_theorem) should be helpful in proving it; but it might be true in more general settings (modular lattices?).
Comment: Well, actually, not true in modular lattices, as the $\mathbf M_3$ example shows...


Humble Bundle Closure Game: controls problem

Question: When I start the Closure game the character keeps moving to the left as if I was pressing the left key on the keyboard. When I try to change the controls configurations the game closes.
Any advice?
Comment: Have you tried pressing the left key?  I sometimes experience this (not in this game) and pressing the same key usually corrects it.
Comment: Yes, I tried to press the left key but the problem persisted.
Comment: I have the same problem. Still no fix found
Comment: is there a log file? if so post it. another trick is to start the game via the terminal. If there is stderr, that should output to the terminal window,in which case you can see why your program crashes.
Answer: It may be that some device (your keyboard for instance) is being detected as a joystick/gamepad, and this ruins the input. If you don't actually have/use any gamepads/joysticks, try removing the joystick support module:
<code>sudo rmmod joydev
</code>
I had this problem myself, and found this quick fix here: http://ubuntuforums.org/showthread.php?t=1996702. I'm actually using this Microsoft Wired 600 keyboard mentioned in the forum, so it would be interesting to know if you're using the same keyboard.


call parent method in child component using vue.js

Question: hello everyone i jusy wanna know how to call a perent function from a child component
i've tried to use the $parent to call the perent method but i have this error typeError: _this.$parent.forceRender is not a function
here's the parent method that i'm trying to call
methods: {
      forceRender() {
        this.componentKey += 1
      }
    },

and here's the child component as you can see i'm trying to call the parent method using the $parent
this.$parent.forceRender()

Comment: By the way: `forceRerender` sounds like it's a bad idea. You usually should not have to do something like that.
Answer: You can send the functions as a props to the child component jus like follows
<child-component :forceRender="forceRender" />

inside the child component you can received it like this
props: ['forceRender']

and then call it as
this.forceRender()

Answer: You should emit an event from child to parent component in order to run a parent method :
in child component:
this.$emit('force-render')

in parent component add @force-render to component tag with forceRender as handler :
<child-component @force-render="forceRender" />


display inline-block with 50% doesn't line up?

Question: i just want to create a simple horizontal list with some divs. Therefor i did this:
Demo
Now as you can see in the result the divs are not next to each other. But i used width of 50%. So what is wrong?
Comment: use `float:left;` instead of `display:inline-block;` or do [these tricks](https://css-tricks.com/fighting-the-space-between-inline-block-elements/)
Comment: @Alex float is good way but in question op asked issue with display:inline-block so better to stick with tricks given by you like margin-right:-4px will be great.
Answer: Elements with inline-block have a little margin on the right side. You can see this with this Code:

div {
  background:black;
  display:inline-block;
  width:20%;
}

Test #1

Test #2

To solve your problem, you can use the following:

body, html {
  padding:0;
  margin:0;
}
.list{
  width:100%;
  height: 100%;
  background: black;
}
.list div{
  float:left;
  display: block;
  width: 50%;
  height: 100px;
  background: red
}

1

2

3

4

Comment: thanks. Didn't know that. Floats are a good alternative :)
Answer: actually, this is a problem of inline-block so if you want to use it, you can't have whitespace between elements ;)
check your fiddle: https://jsfiddle.net/ks0t1xoy/13/
after removing all whitespaces from your .list all elements align nicely, without touching your CSS


Max size of data an iOS can save locally

Question: Is there a limit to the maximum size of data my iOS app can store on the device.
This is not the size of the App but the data it can store.
Answer: You are only limited by the storage capacity of the device. The 2GB maximum (per https://stackoverflow.com/a/4753253/1415038) only applies to your app before it is downloaded from the app store.
Answer: I do not think Apple has set a limit for storing app data so far. No mention is made of a data storage limit in their "The iOS Environment" document or the "About Files and Directories" document.


Wrong IR keytable loaded for Hauppauge soloHD TV

Question: I have a Hauppauge soloHD TV USB device on Ubuntu Focal (20.04 LTS). When it is inserted, the wrong key table seems to be loaded by the kernel (also fails on Groovy 20.10)
[25082.688138] usb 1-1: new high-speed USB device number 6 using xhci_hcd
[25082.836822] usb 1-1: New USB device found, idVendor=2040, idProduct=8268, bcdDevice= 1.00
[25082.836828] usb 1-1: New USB device strings: Mfr=3, Product=1, SerialNumber=2
[25082.836831] usb 1-1: Product: soloHD
[25082.836834] usb 1-1: Manufacturer: HCW
[25082.836837] usb 1-1: SerialNumber: xxxxxx
[25082.837790] em28xx 1-1:1.0: New device HCW soloHD @ 480 Mbps (2040:8268, interface 0, class 0)
[25082.837795] em28xx 1-1:1.0: DVB interface 0 found: bulk
[25082.896253] em28xx 1-1:1.0: chip ID is em28178
[25084.931009] em28xx 1-1:1.0: EEPROM ID = 26 00 01 00, EEPROM hash = 0x3ccac980
[25084.931013] em28xx 1-1:1.0: EEPROM info:
[25084.931017] em28xx 1-1:1.0:  microcode start address = 0x0004, boot configuration = 0x01
[25084.937641] em28xx 1-1:1.0:  AC97 audio (5 sample rates)
[25084.937644] em28xx 1-1:1.0:  500mA max power
[25084.937649] em28xx 1-1:1.0:  Table at offset 0x27, strings=0x0e6a, 0x1888, 0x087e
[25084.996137] em28xx 1-1:1.0: Identified as PCTV tripleStick (292e) (card=94)
[25084.996142] em28xx 1-1:1.0: dvb set to bulk mode.
[25084.996200] em28xx 1-1:1.0: Binding DVB extension
[25085.003353] i2c i2c-3: Added multiplexed i2c bus 4
[25085.003354] si2168 3-0064: Silicon Labs Si2168-B40 successfully identified
[25085.003355] si2168 3-0064: firmware version: B 4.0.2
[25085.005053] si2157 4-0060: Silicon Labs Si2147/2148/2157/2158 successfully attached
[25085.005067] dvbdev: DVB: registering new adapter (1-1:1.0)
[25085.005068] em28xx 1-1:1.0: DVB: registering adapter 0 frontend 0 (Silicon Labs Si2168)...
[25085.005070] dvbdev: dvb_create_media_entity: media entity 'Silicon Labs Si2168' registered.
[25085.006181] dvbdev: dvb_create_media_entity: media entity 'dvb-demux' registered.
[25085.006767] em28xx 1-1:1.0: DVB extension successfully initialized
[25085.006769] em28xx 1-1:1.0: Registering input extension
[25085.006886] Registered IR keymap rc-pinnacle-pctv-hd
[25085.007016] rc rc0: PCTV tripleStick (292e) as /devices/pci0000:00/0000:00:14.0/usb1/1-1/1-1:1.0/rc/rc0
[25085.007061] rc rc0: lirc_dev: driver em28xx registered at minor = 0, scancode receiver, no transmitter
[25085.007089] input: PCTV tripleStick (292e) as /devices/pci0000:00/0000:00:14.0/usb1/1-1/1-1:1.0/rc/rc0/input13
[25085.007160] em28xx 1-1:1.0: Input extension successfully initialized

The remote does not work, likely because of Registered IR keymap rc-pinnacle-pctv-hd. If I manually do
ir-keytable -c -w /etc/rc_keymaps/hauppauge.toml

Then it works ok. According to /lib/udev/rules.d/60-ir-keytable.rules then it should be reading the configuration from /etc/rc_maps.cfg, but this doesn't seem to work (I've tried modifying the rules to use hauppauge.toml). I've also tried blacklisting the rc_pinnacle_pctv_hd module, but this doesn't seem to work.
Is there any way to configure the system to use the correct key table when the device is inserted? (It does get removed often).
Comment: I do not know if this helps as you never said how it was installed. https://hauppauge.com/pages/support/support_linux.html
Comment: @David: the card is automatically detected so I haven't installed anything
Answer: As a temporary workaround I have the following installed. Better answers are welcome.
In /lib/udev/rules.d/99-tv-card.rules I put:
ATTRS{idVendor}=="2040", ATTRS{idProduct}=="8268", RUN+="/usr/bin/ir-keytable -c -w /etc/rc_keymaps/hauppauge.toml"

After reloading with udevadm control --reload-rules it seems to work ok.


Convert UIImage to grayscale keeping image quality

Question: I have this extension (found in obj-c and I converted it to Swift3) to get the same UIImage but grayscaled:
public func getGrayScale() -> UIImage
{
    let imgRect = CGRect(x: 0, y: 0, width: width, height: height)

    let colorSpace = CGColorSpaceCreateDeviceGray()

    let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue).rawValue)
    context?.draw(self.cgImage!, in: imgRect)

    let imageRef = context!.makeImage()
    let newImg = UIImage(cgImage: imageRef!)

    return newImg
}

I can see the gray image but its quality is pretty bad... The only thing I can see that's related to the quality is bitsPerComponent: 8 in the context contructor. However looking at Apple's doc, here is what I get:

It shows that iOS only supports 8bpc... Thus why can't I improve the quality ?
Comment: Check your width and height to make sure the original is not 2x the size.
Comment: This is technically not an answer to your question but assuming that you want to display your gray UIImage in an UIImageView, you can add a layer to that view with a compositing filter as described here: https://stackoverflow.com/a/67436327/5561658
This workflow has a few advantages: light, less code, can easily be toggled.
Answer: Try below code:
Note: code Updated and error been fixed...

Code tested in Swift 3.
originalImage is the image that you trying to convert.

Answer 1:
     var context = CIContext(options: nil)

Update: CIContext is the Core Image component that handles rendering and All of the processing of a core image is done in a CIContext. This is somewhat similar to a Core Graphics or OpenGL context.For more info available in Apple Doc.
     func Noir() {

        let currentFilter = CIFilter(name: "CIPhotoEffectNoir")
        currentFilter!.setValue(CIImage(image: originalImage.image!), forKey: kCIInputImageKey)
        let output = currentFilter!.outputImage
        let cgimg = context.createCGImage(output!,from: output!.extent)
        let processedImage = UIImage(cgImage: cgimg!)
        originalImage.image = processedImage
      }

Also you need to Considered following filter that can produce similar effect

CIPhotoEffectMono
CIPhotoEffectTonal

Output from Answer 1:

Output from Answer 2:

Improved answer :
Answer 2: Auto adjusting input image  before applying coreImage filter
var context = CIContext(options: nil)

func Noir() {

    //Auto Adjustment to Input Image
    var inputImage = CIImage(image: originalImage.image!)
    let options:[String : AnyObject] = [CIDetectorImageOrientation:1 as AnyObject]
    let filters = inputImage!.autoAdjustmentFilters(options: options)

    for filter: CIFilter in filters {
       filter.setValue(inputImage, forKey: kCIInputImageKey)
   inputImage =  filter.outputImage
      }
    let cgImage = context.createCGImage(inputImage!, from: inputImage!.extent)
    self.originalImage.image =  UIImage(cgImage: cgImage!)

    //Apply noir Filter
    let currentFilter = CIFilter(name: "CIPhotoEffectTonal")
    currentFilter!.setValue(CIImage(image: UIImage(cgImage: cgImage!)), forKey: kCIInputImageKey)

    let output = currentFilter!.outputImage
    let cgimg = context.createCGImage(output!, from: output!.extent)
    let processedImage = UIImage(cgImage: cgimg!)
    originalImage.image = processedImage

}

Note: If you want to see the better result.You should be testing your code on real device not in the simulator...
Answer: A Swift 4.0 extension that returns an optional UIImage to avoid any potential crashes down the road.
import UIKit

extension UIImage {
    var noir: UIImage? {
        let context = CIContext(options: nil)
        guard let currentFilter = CIFilter(name: "CIPhotoEffectNoir") else { return nil }
        currentFilter.setValue(CIImage(image: self), forKey: kCIInputImageKey)
        if let output = currentFilter.outputImage,
            let cgImage = context.createCGImage(output, from: output.extent) {
            return UIImage(cgImage: cgImage, scale: scale, orientation: imageOrientation)
        }
        return nil
    }
}

To use this:
let image = UIImage(...)
let noirImage = image.noir // noirImage is an optional UIImage (UIImage?)

Comment: How do you use this in the code? Can you give an example usage?
Comment: Works perfectly in Swift 5.1
Answer: Joe's answer as an UIImage exension for Swift 4 working correctly for different scales:
extension UIImage {
    var noir: UIImage {
        let context = CIContext(options: nil)
        let currentFilter = CIFilter(name: "CIPhotoEffectNoir")!
        currentFilter.setValue(CIImage(image: self), forKey: kCIInputImageKey)
        let output = currentFilter.outputImage!
        let cgImage = context.createCGImage(output, from: output.extent)!
        let processedImage = UIImage(cgImage: cgImage, scale: scale, orientation: imageOrientation)

        return processedImage
    }
}

Comment: Also how can we get back the original image?
Comment: @SasukeUchiha please see CodeBender's answer. I'm afraid there is no way to get original image back, as most colour information is lost after applying noir filter
Answer: I'd use CoreImage, which may keep the quality.
func convertImageToBW(image:UIImage) -> UIImage {

    let filter = CIFilter(name: "CIPhotoEffectMono")

    // convert UIImage to CIImage and set as input

    let ciInput = CIImage(image: image)
    filter?.setValue(ciInput, forKey: "inputImage")

    // get output CIImage, render as CGImage first to retain proper UIImage scale

    let ciOutput = filter?.outputImage
    let ciContext = CIContext()
    let cgImage = ciContext.createCGImage(ciOutput!, from: (ciOutput?.extent)!)

    return UIImage(cgImage: cgImage!)
}

Depending on how you use this code, you may want to create the CIContext outside of it for performance reasons.
Answer: Here's a category in objective c.  Note that, critically, this version takes scale into consideration.
- (UIImage *)grayscaleImage{
    return [self imageWithCIFilter:@"CIPhotoEffectMono"];
}

- (UIImage *)imageWithCIFilter:(NSString*)filterName{
    CIImage *unfiltered = [CIImage imageWithCGImage:self.CGImage];
    CIFilter *filter = [CIFilter filterWithName:filterName];
    [filter setValue:unfiltered forKey:kCIInputImageKey];
    CIImage *filtered = [filter outputImage];
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef cgimage = [context createCGImage:filtered fromRect:CGRectMake(0, 0, self.size.width*self.scale, self.size.height*self.scale)];
    // Do not use initWithCIImage because that renders the filter each time the image is displayed.  This causes slow scrolling in tableviews.
    UIImage *image = [[UIImage alloc] initWithCGImage:cgimage scale:self.scale orientation:self.imageOrientation];
    CGImageRelease(cgimage);
    return image;
}

Comment: but he's not the only person there :), thanks @arsenius
Comment: Yup, this was exactly what I needed :)
Answer: All the above solutions rely on CIImage, while UIImage will often have CGImage as its underlying image, not CIImage. So it means you have to convert your underlying image into CIImage in the beginning, and convert it back to CGImage in the end (if you don't, constructing UIImage with CIImage will effectively do it for you).
Although it probably OK for many use cases, the conversion between CGImage and CIImage is not free: it can be slow, and can create a big memory spike while converting.
So I want to mention a completely different solution, that doesn't require converting image back and forth. It's using Accelerate, and it's perfectly described by Apple here.
Here's a playground example that demonstrates both methods.
import UIKit
import Accelerate

extension CIImage {

    func toGrayscale() -> CIImage? {

        guard let output = CIFilter(name: "CIPhotoEffectNoir", parameters: [kCIInputImageKey: self])?.outputImage else {
            return nil
        }

        return output
    }

}

extension CGImage {

    func toGrayscale() -> CGImage {

        guard let format = vImage_CGImageFormat(cgImage: self),
              // The source image bufffer
              var sourceBuffer = try? vImage_Buffer(
                cgImage: self,
                format: format
              ),
              // The 1-channel, 8-bit vImage buffer used as the operation destination.
              var destinationBuffer = try? vImage_Buffer(
                width: Int(sourceBuffer.width),
                height: Int(sourceBuffer.height),
                bitsPerPixel: 8
              ) else {
            return self
        }

        // Declare the three coefficients that model the eye's sensitivity
        // to color.
        let redCoefficient: Float = 0.2126
        let greenCoefficient: Float = 0.7152
        let blueCoefficient: Float = 0.0722

        // Create a 1D matrix containing the three luma coefficients that
        // specify the color-to-grayscale conversion.
        let divisor: Int32 = 0x1000
        let fDivisor = Float(divisor)

        var coefficientsMatrix = [
            Int16(redCoefficient * fDivisor),
            Int16(greenCoefficient * fDivisor),
            Int16(blueCoefficient * fDivisor)
        ]

        // Use the matrix of coefficients to compute the scalar luminance by
        // returning the dot product of each RGB pixel and the coefficients
        // matrix.
        let preBias: [Int16] = [0, 0, 0, 0]
        let postBias: Int32 = 0

        vImageMatrixMultiply_ARGB8888ToPlanar8(
            &sourceBuffer,
            &destinationBuffer,
            &coefficientsMatrix,
            divisor,
            preBias,
            postBias,
            vImage_Flags(kvImageNoFlags)
        )

        // Create a 1-channel, 8-bit grayscale format that's used to
        // generate a displayable image.
        guard let monoFormat = vImage_CGImageFormat(
            bitsPerComponent: 8,
            bitsPerPixel: 8,
            colorSpace: CGColorSpaceCreateDeviceGray(),
            bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue),
            renderingIntent: .defaultIntent
        ) else {
                return self
        }

        // Create a Core Graphics image from the grayscale destination buffer.
        guard let result = try? destinationBuffer.createCGImage(format: monoFormat) else {
            return self
        }

        return result
    }
}

To test, I used a full size of this image.
let start = Date()
var prev = start.timeIntervalSinceNow * -1

func info(_ id: String) {
    print("\(id)\t: \(start.timeIntervalSinceNow * -1 - prev)")
    prev = start.timeIntervalSinceNow * -1
}

info("started")
let original = UIImage(named: "Golden_Gate_Bridge_2021.jpg")!
info("loaded UIImage(named)")

let cgImage = original.cgImage!
info("original.cgImage")
let cgImageToGreyscale = cgImage.toGrayscale()
info("cgImage.toGrayscale()")
let uiImageFromCGImage = UIImage(cgImage: cgImageToGreyscale, scale: original.scale, orientation: original.imageOrientation)
info("UIImage(cgImage)")

let ciImage = CIImage(image: original)!
info("CIImage(image: original)!")
let ciImageToGreyscale = ciImage.toGrayscale()!
info("ciImage.toGrayscale()")
let uiImageFromCIImage = UIImage(ciImage: ciImageToGreyscale, scale: original.scale, orientation: original.imageOrientation)
info("UIImage(ciImage)")

The result (in sec)
CGImage method took about 1 sec. total:
original.cgImage        : 0.5257829427719116
cgImage.toGrayscale()   : 0.46222901344299316
UIImage(cgImage)        : 0.1819549798965454

CIImage method took about 7 sec. total:
CIImage(image: original)!   : 0.6055610179901123
ciImage.toGrayscale()       : 4.969912052154541
UIImage(ciImage)            : 2.395193934440613

When saving images as JPEG to disk, the one created with CGImage was also 3 times smaller than the one created with CIImage (5 MB vs. 17 MB). The quality was good on both images. Here's a small version that fits SO restrictions:
Answer: As per Joe answer we easily converted Original to B&W . But back to Original image refer these code :
var context = CIContext(options: nil)
var startingImage : UIImage = UIImage()

func Noir() {
    startingImage = imgView.image!
    var inputImage = CIImage(image: imgView.image!)!
    let options:[String : AnyObject] = [CIDetectorImageOrientation:1 as AnyObject]
    let filters = inputImage.autoAdjustmentFilters(options: options)

    for filter: CIFilter in filters {
        filter.setValue(inputImage, forKey: kCIInputImageKey)
        inputImage =  filter.outputImage!
    }
    let cgImage = context.createCGImage(inputImage, from: inputImage.extent)
    self.imgView.image =  UIImage(cgImage: cgImage!)

    //Filter Logic
    let currentFilter = CIFilter(name: "CIPhotoEffectNoir")
    currentFilter!.setValue(CIImage(image: UIImage(cgImage: cgImage!)), forKey: kCIInputImageKey)

    let output = currentFilter!.outputImage
    let cgimg = context.createCGImage(output!, from: output!.extent)
    let processedImage = UIImage(cgImage: cgimg!)
    imgView.image = processedImage
}

func Original(){
    imgView.image = startingImage
}

Comment: this is not the way to restore the origin photo. what if add filter 2 times and wanna restore to original photo? this solution is not gonna work.


Can I repair a chain saw chain?

Question: I have a chain saw (one of the ones for pruning trees) and the chain popped off.  I went to put it back on but one of the teeth is damaged on the part that slides along the arm of the chain saw.  It looks like it is only this single tooth that is causing the chain not to slide into the arm.  Is there anything I can do to repair the chain or am I going to have to buy a new one?
Comment: To avoid this in the future, make sure you oil and tighten the chain before each use if it's been a while.  And if you've been cutting for long enough to heat it up, maybe an hour or so, check and re-tighten the chain if necessary.
Comment: @BMitch - This is probably exactly what happened.  It was near the end of the job so I imagine things had loosened and the oil was low.
Answer: One of my dad's words of wisdom to me was "Don't mess around with chainsaws."  While he meant be careful when using them, I'd say it applies here.  While you could try to repair the chain, if it caused something to bind and caused kickback while sawing, the results could be disastrous.
And new chains are cheap compared to prosthetic limbs- $20-$30.  So do yourself a favor, throw the old chain away, and buy a new one.
Comment: Didn't mean for it to be fear filled (the prosthetic comment was more tongue in cheek than anything.). That being said, a faulty chain on a chainsaw can be dangerous, and if you've ever had a saw catch you off guard and kick back, a small dose of fear is well placed.  My main point was that a faulty chain can put you in a dangerous situation, and even though it isn't highly likely, chains are so cheap that it is hardly worth the risk.
Comment: Chains can be fixed/sharpened shortened/extended by a qualified person. The danger is when the chain is loose or sticking like ops says. but yes +1 for get a new one and +1 for PUT OIL IN :)
Comment: There's a lot of fear in the post, but the point is correct: saw chains are neither expensive not repairable.
Comment: @MarkD I took your advice and bought a new chain.  Only $15 so definitely not worth taking any chances here.  Thanks again!
Comment: I keep 2 spare chains on hand, so I have no need to keep running a dull or damaged chain just to finish a job.
Comment: @ppumkin : sharpening isn't that difficult ... they sell file guides that make it quite easy ... but for all other repairs, I'd say don't do it yourself.  (and I speak from the experience of someone who got slapped in the leg by a thrown chain; luckily, the guard caught it and took most of the energy, so it was only a scratch and some torn pants, rather than anything more serious)

Can I repair a chain saw chain?


how to remove a foreign architecture?

Question: On Ubuntu 12.04 LTS x64, we'd like to remove the i386 foreign architecture it comes with, but I don't see a dpkg command to do this cleanly.
In Stuck with foreign-architecture=i386 when using apt-get, the user is advised to just remove the line from /etc/dpkg/dpkg.cfg.d/multiarch, I can do that (or even remove that file altogether), but I was wondering whether there is a more "appropriate" way to do that.
The reason we want to do that is that we maintain a large number of continuous integration agents using Puppet and want to stick to "pure 64". We install our own Debian packages from our own maintained repository and this fails unless we provide an i386 version of the package. I'm aware that it's possible to override the architecture in the specific repository configuration but it'll be cleaner to just disable the non-64 architecture altogether.
Comment: You could add an empty i386 architecture to the repo. Or you could put `deb [arch=amd64] ...` in the `sources.list`
Comment: I don't understand why you have to provide i386 versions of your packages. On an amd64 machine, the installability of any i386 packages shouldn't be matter, unless you specifically install i386 packages.
Comment: What we found is that "apt-get update" fails when our internal repo is configured since it looks for i386 packages which don't exist.
Answer: The standard way to remove an architecture would be through dpkg:
sudo dpkg --remove-architecture i386

Tested on Ubuntu 16.0.4 LTS.
It is also faster & simpler than to add architecture after every deb ... in sources.list.
Comment: Thanks. This sounds like the kind of answer I was after. Perhaps it was added in the 4+ years since I asked this question.
Answer: It appears that tumbleweed's comment solved your issue.
You can add an option to the Apt sources definition that restricts the architectures of that source:
deb [arch=amd64] ...

For more information see the Community Wiki page on multi-architecture package management.

how to remove a foreign architecture?


Clicking on Image using Sikuli and Env.isLockOn(Key.NUM_LOCK) not working

Question: I am trying to Click on image and also i need to check if NUM_LOCK is on or off if it is on i need to switch if off and for that i am using below sikuli script and running it using executescript command of seleniumDriver code is as below but its is giving me error as
"Exception Occured ::org.openqa.selenium.WebDriverException: No signature of
method: static org.sikuli.script.Env.isLockOn() is applicable for argument
types: (java.lang.String) values: [?]
Possible solutions: isLockOn(char)"

Below Code
String typeFromDate = "import org.sikuli.script.Screen;\n"+
                "import org.sikuli.script.Key;\n"+
                "import org.sikuli.script.KeyModifier;\n"+
                "import org.sikuli.script.Env;\n"+
                "Screen screen = new Screen();\n"+
                "screen.doubleClick(\""+fromDateImgPath.trim()+"\");\n"+
                "Thread.sleep(2000);\n"+
                "if(Env.isLockOn(Key.NUM_LOCK))screen.type(Key.NUM_LOCK);"+
                "screen.type(Key.HOME); \n"+
                "Thread.sleep(5000);\n"+
                "screen.keyDown(Key.SHIFT) \n"+
                "screen.type(Key.END) \n"+
                "screen.keyUp(Key.SHIFT) \n"+
                "Thread.sleep(5000);\n"+
                "screen.type(\""+fromDate+"\"); \n"+
                "Thread.sleep(2000);\n"+
                "return null;\n";

 returnfrDt = (String) aDriver.executeScript(typeFromDate, new String[]
{"GROOVY"});

Comment: I don't understand, all your code is a String. How do you expect it to do anything?
Comment: I am working on WorkFusion Tool  which is an automation tool in which we can write sikuli scripts as strings and then we can execute it using this command aDriver.executeScript(typeFromDate, new String[]
{"GROOVY"});
Comment: That sounds like extremely complicated way to do that but whatever. In your case, the issues is the type you provide into `isLockOn` method. It complains that you give it a String when it expects something else.
Answer: With Jython, it is pretty simple:
if Env.isLockOn(Key.NUM_LOCK):
    print('NUM_LOCK is ON')


Pandas: mapping list from column values to columns?

Question: I got a pandas dataframe like below after prefixspan algorithim and I want to map those into columns.
id  ps_results
...
28  [(301, [1-1]), (63, [1-1, 0-5]), (35, [1-1, 1-...
29  [(265, [0-37]), (31, [1-1, 0-5]), (25, [0-1, 1-1, 0-1...
...

For ps_results column, there is a very long list of (frequency, [patterns]), e.g.(63, ['1-1', '0-5']), I want to generate many columns according to this list.
[
   (301, ['1-1']),
   (63, ['1-1', '0-5']),
   (35, ['1-1', '1-5']),
   (61, ['1-1', '0-3']),
   (21, ['1-1', '0-3', '1-1']),
   (125, ['1-1', '1-1']),
   (32, ['1-1', '1-1', '0-2']),
   (21, ['1-1', '1-1', '0-2', '1-1']),
   (46, ['1-1', '1-1', '1-1']),
   (20, ['1-1', '1-1', '1-1', '0-1']),
   (50, ['1-1', '1-1', '0-1']),
   (27, ['1-1', '1-1', '0-1', '1-1']),
   (22, ['1-1', '1-1', '0-5']),
   (26, ['1-1', '1-1', '0-4']),
   (25, ['1-1', '1-1', '1-2'])
   ...
]

For example, I want to get some dataframe like below,
sum_of_freq = 301 + 63 + 35 + 61 + ... + 25 + ... (for id = 28)
sum_of_freq = 265 + 31 + 25 ... (for id = 29)
id  ps_results    ['1-1']           ['1-1', '0-5']    ['1-1', '1-5']    ['0-37']  ...rest_of_the_columns
...
28  [(301,[...    301/(sum_of_freq)  63/(sum_of_freq)  35/(sum_of_freq)  0 <--this for other rows
29  [(265, [0...  0                  31/(sum_of_freq)  0                 265/(sum_of_freq)
...

Note, the length of ps_result for each id will vary, there probably have thousands of columns generated at the end.
Below is a small data for experiments.
a = {
    'id': ['22', '23'],
    'ps_results': [[(301, ['1-1']), (63, ['1-1', '0-5']), (35, ['1-1', '1-5']),
                    (61, ['1-1', '0-3']), (21, ['1-1', '0-3', '1-1']),
                    (125, ['1-1', '1-1']), (32, ['1-1', '1-1', '0-2']),
                    (21, ['1-1', '1-1', '0-2', '1-1'])],
                   [(46, ['1-1', '1-1', '1-1']),
                    (20, ['1-1', '1-1', '1-1', '0-1']),
                    (50, ['1-1', '1-1', '0-1']),
                    (27, ['1-1', '1-1', '0-1', '1-1']),
                    (22, ['1-1', '1-1', '0-5']), (26, ['1-1', '1-1', '0-4']),
                    (67, ['1-1', '0-1', '1-1'])]]
}
pd.DataFrame(data=a)

Supply table
Answer: Not sure if this is what you want. Let me know if not:
a = {
    'id': ['22', '23'],
    'ps_results': [[(301, ['1-1']), (63, ['1-1', '0-5']), (35, ['1-1', '1-5']),
                    (61, ['1-1', '0-3']), (21, ['1-1', '0-3', '1-1']),
                    (125, ['1-1', '1-1']), (32, ['1-1', '1-1', '0-2']),
                    (21, ['1-1', '1-1', '0-2', '1-1'])],
                   [(46, ['1-1', '1-1', '1-1']),
                    (20, ['1-1', '1-1', '1-1', '0-1']),
                    (50, ['1-1', '1-1', '0-1']),
                    (27, ['1-1', '1-1', '0-1', '1-1']),
                    (22, ['1-1', '1-1', '0-5']), (26, ['1-1', '1-1', '0-4']),
                    (67, ['1-1', '0-1', '1-1'])]]
}
data = DataFrame(data=a)
data['sum_of_freq'] = data['ps_results'].map(
    lambda tuples: sum(t[0] for t in tuples)
)
exploded = data.explode(column='ps_results')
exploded['freq'] = exploded['ps_results'].map(lambda v: v[0])
exploded['pattern'] = exploded['ps_results'].map(lambda v: v[1])
exploded['freq_ratio'] = exploded['freq'] / exploded['sum_of_freq']
exploded['pattern'] = exploded['pattern'].map(lambda l: tuple(l))
pivot = exploded.pivot(
    index='id', columns='pattern', values='freq_ratio'
).fillna(0).reset_index()

Comment: Not what I want, I want frequency / sum(t[0] for t in tuples) and map each ['1-1', '1-1', '1-2'] in to a column
Comment: Added a table ask me if you not clear
Comment: Oh I didn't look at your table properly. I don't think you can have lists as pandas columns so I turned them into tuples for this.
Comment: Alternatively, you could replace `lambda l: tuple(l)` with `lambda l: str(l)` if you care about the column looking right, but it won't be a list anymore
Comment: How to reset index so I can only have id column and (1-1,),... columns?
Comment: add `.reset_index()` to the last line
Comment: When I apply to more data I got :  `Cell In [3], line 4, in extract_feat_from_pfs..(tuples)
      1 def extract_feat_from_pfs(data:pd.DataFrame):
      3     data['sum_of_freq'] = data['ps_results'].map(
----> 4         lambda tuples: sum(t[0] for t in tuples)
      5     )
      6     exploded = data.explode(column='ps_results')
      7     exploded['freq'] = exploded['ps_results'].map(lambda v: v[0])

TypeError: unsupported operand type(s) for +: 'int' and 'str'`
Comment: I found it is list in the example, but the string in real data, I will change the type...
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/249412/discussion-between-yiffany-and-vahndi).


Why do people steal less stuff than they should?

Question: I'm in the maxing out stage of my Town Hall 8 village, which means I don't use elixir much, and I have full elixir storages all the time, with a capacity of 6,000,000 elixir (3 level 11 storages).
According to the wiki, level 11 elixir storages give 10% of their current resources when destroyed during an attack. There is a maximum cap for amount of elixir stolen from storages, which is 450,000 elixir.
However, most of the times when my village gets completely destroyed, 3-star raid, the amount of elixir stolen is only about 350,000. This is way less than the maximum cap or 10% of the resources, and I'm not even taking into account collectors, the Town Hall and the Clan Castle.
Why?
Comment: what level townhall do the people have who are attacking you?
Comment: The title of this question looks really weird out-of-context.
Comment: Mostly level 9, sometimes even level 10.
Comment: @pppery That's why it's important to write titles that accurately reflect what their asking rather than generic, vague things that could apply to any number of questions.
Answer: When a higher townhall level than you attacks you, they suffer a loot penalty. The current loot penalty is show in the following graph.

You can also find out more on how the loot you can get is calculated here under section "Loot".


Destiny expansions 1 and 2 and taken king

Question: Will the expansions download right away?
I redeemed my codes but nothing happened. I have enough space and I'm playing on a first gen 360.
Will it download once I progress to that point in the story?
Comment: I think it just enables them for you account, as the new Destiny client includes those expansions by default. I would hold on to your codes though, to be safe. Hopefully someone has a concrete answer.
Comment: I believe those expansions are included in The Taken King download, so you should be okay. Not 100% sure as I purchased them both last year.
Comment: Well I used both codes and nothing happened. Is it suppose to download immediately or just once you have done everything in the original destiny?
Answer: If you have redeemed the codes and they are valid, and you have enough space, they should start downloading automatically.
If the downloads for the expansions don't start automatically, you can start them manually by going to the store page for each expansion and start the download from there (if the redeem was successful, you will not have to buy the expansions, it should just say "download").
You do not need a certain completion in-game to be able to download the expansions.
Comment: This is a bit misleading because the codes actual download a very small file and not the expansion itself. The base game contains all the necessary data and all you need is an appropriate licence. On my xb1 the two downloads for the expansions were about 10 meg each.
Comment: Indeed, the additional content supplemented to the game will download when starting the actual game. The files you download when you redeem your code is basically an activator, telling the game that you are enrolled to access this content. I was assuming this is what @Jeff was relating to when he said _"I redeemed my codes but nothing happened."_? Without these files downloaded first, the game will not let you access the content of the expansions.
Answer: Some DLC that are activated with a code can download automatically. If it hasn't downloaded then, go into the online store on you xbox and search for the DLC.
I hope this helped.
Answer: They have probably downloaded, but you won't see any real changes in game until you're far enough along in the story.
Answer: The data for the expansions is rolled up into the base game itself. When you purchase any of the addons you are basically just buying a licence and on the XB1 at least these files are about 10Mb each. I mention this because you may well have been expecting a large and lengthy download whereas in fact what downloaded probably happened almost instantly.
You should be able to access all features from the expansions immediately once you reach appropriate level to actually do so with no additional download needed.
You should also be able to view what DLC you have installed on your system. I'm sadly not 100% sure how on the 360 (been a while since I used mine) but I'll try to find some instructions somewhere.


What does the -rd option mean in the cp command?

Question: I have found a reference using the following command
cp -rd  *  /folder_1/

and another one as
cp -dr * /folder_2/

Can you please advise what are these options "rd" or "dr"?
Comment: @moibrahim next time consider reading the manual ,  `man cp` or `info cp` or `cp --help` would have given you the same answers given below
Answer: The order does not matter - you can give the options in any order
This combination will copy directories recursively (including all the contents) and copy symlinks as symlinks instead of copying the files they point to.
-d is only needed when using -r : it is used to override the default behaviour, which is not to follow symlinks when copying recursively
from info cp

'-r' '--recursive'
       Copy directories recursively.  By default, do not follow symbolic
       links in the source unless used together with the '--link' ('-l')
       option; see the '--archive' ('-a'), '-d', '--dereference' ('-L'),
       '--no-dereference' ('-P'), and '-H' options.
'-d'
       Copy symbolic links as symbolic links rather than copying the files
       that they point to, and preserve hard links between source files in
       the copies.  Equivalent to '--no-dereference --preserve=links'.
Answer: In many command line utilities, single-letter options can be written together. In your case, the longer form would be
cp -r -d  *  /folder_1/

which can be shortened to
cp -rd  *  /folder_1/

The other version
cp -dr  *  /folder_1/

is the same as
cp -d -r  *  /folder_1/


Import a CSV file to my datagridview

Question: I am working on a project where I have to import a CSV file, and display the results in a DataGridView. I am struggling to display my data fields to my datagridview, I want to be able add each row at a time so it parses them correctly. Here is my code so far.
   csv.MissingFieldAction = MissingFieldAction.ReplaceByNull;
   int fieldCount = csv.FieldCount;
   string[] headers = csv.GetFieldHeaders();
   fieldCount = fieldCount - 1;

   //TO DO: Reading Header Information

   for (int i = 0; i <= fieldCount; i++)
   {
       DataGridViewTextBoxColumn headerRow = new DataGridViewTextBoxColumn();
       headerRow.Name = headers[i];
       headerRow.HeaderText = headers[i];
       headerRow.Width = 100;
       dgvComplianceImport.Columns.Add(headerRow);
   }

   while (csv.ReadNextRecord())
   {
       //for (int i = 0; i < fieldCount; i++)
       //    string.Format("{0} = {1};",
       //                    headers[i],
       //                    csv[i] == null ? "MISSING" : csv[i]);

       //TO DO: for loop to add each data field row

       DataGridViewRow dgvr = new DataGridViewRow();
       for (int fieldCount = 0; fieldCount <= csv.FieldCount; fieldCount++)
       {
           string field = csv[fieldCount];

       }
       dgvr.Cells.Add(new DataGridViewCell());
       dgvComplianceImport.Rows.Add(dgvr);
   }

   dgvComplianceImport.DataSource = csv;

}

Comment: Hi! Welcome to Stackoverflow! Do you have a question? Why are you struggling? whats it doing?
Comment: What exactly are you struggling with?
Answer: A CSV file is a normal text file that's just comma delimited.
Basically what you want to do is open the text file and read through each line and split by the comma (",")
Use these links. They should help.
http://www.codeproject.com/Articles/16951/Populating-data-from-a-CSV-file-to-a-DataGridView
http://www.c-sharpcorner.com/uploadfile/ankurmee/import-data-from-text-and-csv-file-to-datagridview-in-net/
http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/9efdbbd7-bfd9-4c7f-9198-791a4ca88a44/
Let me know if you still need some help writing the code.
Comment: Hi Thank you for your response. The trouble is I don't want to spilt it by the comma because the csv file might have cells with commas within them. So I used this link to be able to parse the CSV  File: http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader#latup. However, it hasn't worked exactly how I planned as when I display the results in the datagridview it doesn't let me edit it and I need to be able to edit the dgv and resave it.
Comment: In order to prevent this I am trying to make it so it doesn't do this, I need to make loop through each data row in the CSV File and add each row at a time to the dgv. Sorry if this is a bit confusing.
Comment: Can you tell me where you are getting the CSV file? Are you generating it from another application that you wrote? or is it some other application?
Comment: Same application I just have a browse button to open a csv file from my documents.
Comment: @JoeMarsden You don't need to do that work by yourself. See my answer.
Comment: Sorry I meant to ask how you are generating it? I'm not 100% sure about this but if you have commas as part of your cell value then yes there will be that issue and then you could not open and parse the file.. but if you could just take it up a notch and maybe convert the cell values that have a comma to something else for the import process and then when you import it you could change it back. So what I'm trying to say is...example: cell 1 = 13,99 cell 2 = 15,00 then in the CSV file it would be 13,99,15,00 so you just make it convert 13,99 to 13ô99 and 15,00 to 15ô99
Comment: and then you can change it back in the import code... you can try Oscars solution. It may be better... but if you can't get it then you can solve it by this way
Comment: @BeginnerCoder If your separator char is `,`, CSV allows you to have fields with `,` on it. The following is valid: `john,doe,"1st Ave, City, CA"`. You just need to place that cell inside `"`. That's why you can't just split the string by `,`. You don't need to worry about that work, since there already are libraries that parsae CSV file correctly for you.
Comment: Joe use Oscars solution. It would work for you! Thanks Oscar :-)
Comment: Both ideas are good. I will have a look into both, but just a querying if I was to be able to try and replace the commas in cells with nothing. Do you have a idea how I would go about this?
Answer: This is what I usually do:

Define a class where each property represents a CSV column
Use LINQToCSV (see here and here) to read the CSV file. It already gives me an IEnumerable<T> where T is my class.
Populate the DataGridView as you usually do (either manually, through bindings, etc.)

An example of how to read a CSV file
Let's assume the CSV file has the columns Name, Last Name, Age
Then you do define the following class:
class Person {
    [CsvColumn(FieldIndex = 0, CanBeNull = false, Name = "Name")]
    public string Name { get; set; }
    [CsvColumn(FieldIndex = 1, CanBeNull = true, Name = "Last Name")]
    public string Last Name { get; set; }
    [CsvColumn(FieldIndex = 2, CanBeNull = true, Name = "Age")]
    public int Age { get; set; }
}

Once you have it, you can read a list of Person from a CSV file like this:
public IEnumerable<Person> ReadFromCsv(string csvFile) {
    //Here you set some properties. Check the documentation.
    var csvFileDescription = new CsvFileDescription
    {
        FirstLineHasColumnNames = true,
        SeparatorChar = ',' //Specify the separator character.
    };

    var csvContext = new CsvContext();

    return csvContext.Read<Person>(csvFile, csvFileDescription);
}

Comment: @JoeMarsden Test it and let us know how it went
Answer: This is a class i use:
Call lCsv.ReadCsv("your file path"), the method returns a datatable created from the .csv file.
The separator in the file are ";", and the first row of the .csv file is the header names. If you what to change this check out lCsv.ReadCsv method
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Data;

namespace ReadWriteCsv
{
///
/// Class to store one CSV row
///
public class CsvRow : List<string>
{
    public string LineText { get; set; }
}

///
/// Class to read data from a CSV file
///
public class CsvFileReader : StreamReader
{
    public CsvFileReader(Stream stream)
        : base(stream)
    {
    }

    public CsvFileReader(string filename)
        : base(filename)
    {
    }

    ///
    /// Reads a row of data from a CSV file
    ///
    /// <param name="row"></param>
    /// <returns></returns>
    public bool ReadRow(CsvRow row)
    {
        row.LineText = ReadLine();
        if (String.IsNullOrEmpty(row.LineText))
            return false;

        int pos = 0;
        int rows = 0;

        while (pos < row.LineText.Length)
        {
            string value;

            // Special handling for quoted field
            if (row.LineText[pos] == '"')
            {
                // Skip initial quote
                pos++;

                // Parse quoted value
                int start = pos;
                while (pos < row.LineText.Length)
                {
                    // Test for quote character
                    if (row.LineText[pos] == '"')
                    {
                        // Found one
                        pos++;

                        // If two quotes together, keep one
                        // Otherwise, indicates end of value
                        if (pos >= row.LineText.Length || row.LineText[pos] != '"')
                        {
                            pos--;
                            break;
                        }
                    }
                    pos++;
                }
                value = row.LineText.Substring(start, pos - start);
                value = value.Replace("\"\"", "\"");
            }
            else
            {
                // Parse unquoted value
                int start = pos;
                while (pos < row.LineText.Length /*&& row.LineText[pos] != ','*/)
                    pos++;
                value = row.LineText.Substring(start, pos - start);

            }

            // Add field to list
            if (rows < row.Count)
                row[rows] = value;
            else
                row.Add(value);
            rows++;

            // Eat up to and including next comma
            while (pos < row.LineText.Length /*&& row.LineText[pos] != ','*/)
                pos++;
            if (pos < row.LineText.Length)
                pos++;
        }
        // Delete any unused items
        while (row.Count > rows)
            row.RemoveAt(rows);

        // Return true if any columns read
        return (row.Count > 0);
    }
}

public class lCsv
{
    public static DataTable ReadCsv(string sPath)
    {
        DataTable dtIssues = new DataTable();
        int iRowCount = 0;
        int iColumnCount = 0;
        // Read sample data from CSV file
        using (CsvFileReader reader = new CsvFileReader(sPath))
        {
            CsvRow row = new CsvRow();
            while (reader.ReadRow(row))
            {
                foreach (string fullrow in row)
                {
                    if (iRowCount == 0)
                    {
                        foreach (string sName in fullrow.Split(';'))
                        {
                            dtIssues.Columns.Add(sName);
                            iColumnCount++;
                        }
                        iRowCount++;
                    }
                    else
                    {
                        DataRow drIssue = dtIssues.NewRow();
                        int iAddCount = 0;
                        foreach (string sName in fullrow.Split(';'))
                        {
                            if (iAddCount < iColumnCount)
                            {
                                drIssue[iAddCount] = sName;
                                iAddCount++;
                            }
                        }

                        dtIssues.Rows.Add(drIssue);
                    }
                }
            }
        }

        return dtIssues;
    }
}

}
Answer: Why reinvent the wheel? FileHelpers is your friend.
Example of how to import a CSV to a DataTable is given here:
http://www.filehelpers.net/docs/html/M_FileHelpers_CsvEngine_CsvToDataTable_2.htm
The static method signature under the relevant class (CsvEngine) is as easy as this:
public static DataTable CsvToDataTable(
string filename,
string classname,
char delimiter
)

Sweet, right?
Answer: Short and works, hope it helps
    DataGridView my_dgvCSV = new DataGridView();
    DataTable my_dataTable = new DataTable();

    private void Form1_Load(object sender, EventArgs e)
    {
        this.Size = new Size(750, 450);
        my_dgvCSV.Size = new Size(600, 400);
        my_dgvCSV.Location = new Point(5, 5);

        string[] raw_txt = File.ReadAllLines(@"D:\urPath\xyz.csv");
        string[] data_col = null;
        int x = 0;

        foreach (string txt_line in raw_txt)
        {
            data_col = txt_line.Split(';');
            // My .csv wanted (';') if it looks weird/wrong use (',')

            if (x == 0)
            {//header
                for (int i = 0; i <= data_col.Count() -1; i++)
                {
                    my_dataTable.Columns.Add(data_col[i]);
                }

                x++;
            }
            else
            {//data
                my_dataTable.Rows.Add(data_col);
            }
         }

         my_dgvCSV.DataSource = my_dataTable;
         this.Controls.Add(my_dgvCSV);
      }

Import a CSV file to my datagridview


jQuery AJAX form how to get data

Question: I have a form in my ASP.NET MVC 3 application that will use jquery to send it's data to the controller action instead of doing a normal postback:
$('.AjaxForm').live("submit", function (event) {
            event.preventDefault();
            $.validator.unobtrusive.parseDynamicContent('.uiModalContent input');
            console.log($(this).attr('action'));
            $.ajax({
                type: 'POST',
                url: $(this).attr('action'),
                data: data,
                success: function (responseHtml) {
                    alert(responseHtml);
                },
                error: function (responseHtml) {
                    alert('error');
                },
                statusCode:
                {
                    404: function (responseHtml) {
                        alert('404');
                    },
                    500: function (responseHtml) {
                        alert('500');
                    }
                }
            });
        });

However I get an error saying data is undefined... How do I get the data from the form and send it? Also does the built-in validation in ASP.NET MVC 3 work with my code or will I have issues? Thanks
Answer: You should use form.serialize() to make data value. Your code should be changed to:
url: $(this).attr('action'),
data: $('.AjaxForm').serialize(),

Answer: you can use the serialize or serializeArray method with form to pass all parameters with the ajax call.
data: $('.AjaxForm').serialize(),

http://api.jquery.com/serialize/
http://api.jquery.com/serializeArray/

jQuery AJAX form how to get data


What is Cat & Mouse?

Question: On your phone, if you to Extras and click on Stats, there's a large amount of information about your various statistics about your game.
On page 10 of 11 at the top of the page, there are two statistics that read as follows:
Cat & Mouse: Most Points Earned: 0
Cat & Mouse: Cash Earned: $0.00
I've finished the main campaign, and I'm currently working my way through the diversions. I've not heard any mention of "Cat & Mouse" at all. I know it's not a diversion.
What is this? Is it something that is co-op only (I've only played single player)?
Answer: Cat and Mouse is indeed a co-op side mission.  In Saints Row 2, you entered it by killing your co-op partner - the killed partner was then presented with a menu whereby they could choose one of two games to play in retaliation.  Saints Row 3 does something similar.
Cat and Mouse is where one player has a car, and is trying to hit checkpoints similar to a checkpoint race.  The other player has an attack helicopter and has to stop the other player from hitting the checkpoints.  After a set period of time, they switch.  Whoever hit more check points when both timers expire is the winner.
Comment: For me it was a tank on Saints Row the Third, not an attack helicopter.

What is Cat & Mouse?


Are periods after numbers of a list an international convention?

Question: In English this is pretty standard:

The first thing
The second thing
The third thing

Are these periods an international convention? For example:

最初のもの
二つ目のこと
三つ目のこと

This question assumes Arabic numerals are used world-wide. My question is not about that.
Thanks!
Comment: One data point to consider: Even if the writing happens to be the same, different languages may interpret the numbers differently. Case in point: In English, ordinal numbers are written by appending a suffix (usually *th*, with exceptions for 1, 2, and 3). For instance: "1st, 2nd, 3rd, 4th, 5th" In German, on the other hand, ordinal numbers are written by appending a period: "1., 2., 3., 4., 5." Therefore, in a German text, putting a period behind the numbers of a numbered list makes them inherently ordinal numbers, whereas this *might* be perceived differently in an English text.
Answer: Short answer:
Periods are the default counter suffix for ordered list implementation in web browsers.
Long answer:
If you are using ordered lists in web pages, browses are implementing them using period after. If not specified, the default value will be "\2E\20" (". ", a full stop followed by a space).
You can check a specification example: https://html.spec.whatwg.org/multipage/grouping-content.html#attr-ol-type
The Arabic numerals is just a type from possible predefined counter styles the https://drafts.csswg.org/css-counter-styles-3/#predefined-counters. Because of typography and internationalisation demands, the W3C invented ways to overwrite the defaults.
The suffix for the counter can be changed from the default period to <string>, <image>, or <custom-ident>.
Also common I've seen parentheses (")", closed round bracket, called unpaired parenthesis). Depending on the hierarchy of your ordered lists you might need to go multiple levels down, so you might need multiple counter suffix styles (periods '.' for level 1, single parentheses ')' for level 2, paired parentheses '()' for level 3, colon ':' for level x, etc. ).
1.
  1.1 ...
     (a) ...
       a.1: ...
2)  or (2) ...
3)  or (3) ...

Regarding your question about international convention. I don't know, but you can read more about the topic at https://writing.stackexchange.com/a/5685

From an usability point of view, I think a suffix is needed since it clearly states to the user that it is a list-item and not a value.
For example, reading:
1. apples
2. oranges

I will know it's an enumeration and not a quantitative information:
1 apple
2 oranges

So whatever suffix you will be using (if it's an international convention or not) I would suggest to use a suffix in order to mark ordered lists accordingly.
Comment: Thanks. That writing stackexchange thread is somewhat helpful. Nobody in that presumably fairly diverse thread mentioned internationalization concerns. Browser defaults for ols is also a good point.


Get the value inside a dictionary

Question: im fairly new to python and im doing a RPG to practice what i'm learning. I have a dictionary of items and i want to get the name of one of them, but when i call it i get a message :
You don't have any<classes.inventory.Item object at 0x7f52e39bce48>left!

My dictionary is this one:
player_items = [{"item":potion, "quantity": 15},
                {"item":hipotion, "quantity": 10},
                {"item":superpotion, "quantity": 8},
                {"item":elixir, "quantity": 3},
                {"item":hielixir, "quantity":1},
                {"item":grenade, "quantity": 12}]

item = player.items[item_choice]["item"]
player.items[item_choice]["quantity"] -= 1

if player.items[item_choice]["quantity"] == 0:
    print(bcolors.FAIL+"\n"+"You don't have any"+str(item)+"left!"+bcolors.ENDC)

class Item:
    def __init__(self, name, type, description, prop):
        self.name = name
        self.type = type
        self.description = description
        self.prop = prop

class Person:
    def __init__(self, hp, mp, atk, df, magic, items):
        self.maxhp = hp
        self.hp = hp
        self.maxmp = mp
        self.mp = mp
        self.atkhigh = atk+10
        self.atklow = atk-10
        self.df = df
        self.items = items
        self.magic = magic
        self.actions = ["Attack", "Magic", "Items"]

Anyone know what im doing wrong? Thanks in advance for your time.
EDIT : Found the error. I need to learn more. I just needed to add the name property when i called the item :
print(bcolors.FAIL+"\n"+"You don't have any"+str(item.name)+"left!"+bcolors.ENDC)

Sorry i wasted your time guys.
Comment: Are you sure this is the code in your program? your dictionary is called `player_items` but you perform your operations on `player.items`. so is the dict a global scoped dict or is it a member of a player instance?
Comment: This code is fine, and you're doing nothing wrong
Comment: Welcome to StackOverflow.  Please read and follow the posting guidelines in the help documentation, as suggested when you created this account.  [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here.  We cannot effectively help you until you post your MCVE code and accurately describe the problem.
We should be able to paste your posted code into a text file and reproduce the problem you described.
Comment: Yes, this is the code, the inventory has a Item class and is part of the player too, let me paste the rest of the code :                                                     class Item:
    def __init__(self, name, type, description, prop):
        self.name = name
        self.type = type
        self.description = description
        self.prop = prop
Comment: Could you please edit the code in your comment into the question? It would make it easier to read
Comment: Sure, done editing.
Answer: item isn't the string "potion", for instance; it's a reference to an instance of Item that represents a potion. You need to provide an appropriate __str__ method for your Item class.
Comment: Thanks, i'll check that.
Answer: @Ifsalazar2010 welcome to python. here are a few things I see you may be doing wrong.
First, your dict values need to be string, otherwise python will try to look for those as object. So write "potion" instead of potion
player_items = [{"item":"potion", "quantity": 15},
            {"item":"hipotion", "quantity": 10},
            {"item":"superpotion", "quantity": 8},
            {"item":"elixir", "quantity": 3},
            {"item":"hielixir", "quantity":1},
            {"item":"grenade", "quantity": 12}]

Next, you need to use the proper object player_items and not player.items. Your object is a list of dictionaries, which you can call by index and you haven't defined item_choice. I am using the index 1 as example.
item = player_items[1]["item"]
print(item)
player_items[1]["quantity"] -= 1
print(player_items)

In short, seems like you didn't provide detail in your example to replicate your errors. for example what is bcolors.FAIL
Comment: oh, bcolors is a class for colors for the font. I have them in bash saved in those variables, for example bcolors.FAIL = '\033[91m'

Get the value inside a dictionary


Disable Intellij IDEA code reformatting when closing brace is typed in

Question: Intellij IDEA seems to like to reformat the code block inside braces once the closing brace is entered. For example, if I have a block of code that I now want to wrap in a try/catch block, once I type in the closing brace of the try block, the entire try block automatically gets reformatted. I have searched in settings but was not able to find anything that would turn this off. Any ideas?
Answer: Yes.
File --> Settings --> Editor --> General --> Smart Keys
Then uncheck the option "Reformat block on typing '}'"
Apply --> OK
Answer: You must check the option "Enable formatter markers in comments" in
File -> Settings... -> Code Style -> Formatter Control
and then you must put your code between comments: // @formatter:off and // @formatter:on
From the documentation about the option "Enable formatter markers in comments":

If this check box is selected, the fragments of code
  between the line comments with the formatting markers will not be
  reformatted but will preserve the original formatting. After you
  select the check box, the fields below become available and you can
  specify the character strings to be treated as formatting markers.
If the check box is cleared, the formatting markers will be ignored and
  the code between the line comments with markers will be reformatted.
Comment: Thanks. I have this turned on but I do not want to have specify // @formatter:on for every block. The other answers does exactly what I need.


Files (Nautilus) appearing twice in GNOME dash (Ubuntu Dock)

Question: Ever since installing Ubuntu 18.04, I've been having the following intermittent fault in my GNOME dash. For no discernible reason, I will have an extra shortcut to Files (i.e. Nautilus) appear on my GNOME dash in addition to the one that I already have as a favorite and this will not go away until reboot.

Closing all occurrences of Files will not have any effect, nor will
removing the old Files from my favorites (aside from removing the
original occurrence of Files).
The new Files shortcut can be added to favorites (and then removed),
but this will also do nothing if Files is already favorited. If Files
is not favorited, it will favourite a new instance of Files that
works just like the oldest one.
If clicked, the new shortcut does not open Files under its own icon. Instead, if will either use the old shortcut as the
location of the application (i.e. Files is managed as if it was
opened by the old shortcut), or if Files is not a favorite,
it will make a new icon for Files that works as any other
non-favorite application should.

This tends to happen infrequently, but I suspect that sleep mode may have some part in the blame.
Update: After a series of misclicks I've just seen this issue occur. I don't know if these misclicks have caused the issue, but I've just seen it triggered by opening Files via the 'Places status indicator' GNOME extension whilst in the 'Show Applications' menu of Ubuntu. I'm fairly confident that I was having this issue prior to having said extension installed, but it's a start.
Update 2: Uninstall the Places status indicator' GNOME extension fixed the issue for a while, but I've just trigger it again by putting a USB drive in and copying a few files to it before (safely) removing said drive.
Update 3: 'Open with Files' seems to be the culprit.
Update 4: This even appears to be replicable via 'Open with Files' after a download.
Comment: Have you tried removing Nautilus from the dock ('remove from favourites') and re-adding?
Comment: @pomsky I'm sure that I have. From memory, the extra icon persists and the original one if, of course, removed and re-added.
Answer: I faced the same issue in Ubuntu 18.04 and found that there is an additional .desktop entry for nautilus under the /usr/share/applications directory (nautilus-folder-handler.desktop).
This happened after I opened an archive and extracted it with the 'open with other application' -> 'Files' option.
Just remove the extra nautilus-folder-handler.desktop entry and close any open nautilus instances, and the extra dock icon should go away.
you may do a sudo rm /usr/share/applications/nautilus-folder-handler.desktop from a terminal to remove it.
Comment: perhaps be more clear on how you deleted it - some might have a difficulty with that
Comment: @db429 Thanks. I have updated my answer.


Certain light bulbs not working in fixture

Question: I have recessed lighting in my eaves outside, 8 in front 4 in the back.  Most of them were blown and I bought 12 Great Value Led 8W (60W Equivalent) Daylight Color Frosted Light Bulbs to replace them all so they all match in brightness and color.
After replacing 7 of the front ones, the last one didn't work.  I tried 4 different bulbs, none of them worked in the socket.  The incandescent 25W that was there worked fine, and I had an older LED I snagged and that worked fine so I left it there.  I had all the lights on and from the road, the one bulb was noticeably a different color.  I could try to find a similar color and style bulb that is a different brand and try it.
What would cause this particular bulb to not work in this socket?  All of the fixtures appear to be identical, all on the same switch, and now all using less wattage than before using LEDs.  These bulbs are dimmable and the switch is a dimmer switch, which works fine with the alternate bulb put in.
Comment: Are you saying the switch is a dimmer?
Answer: Last time I had this problem it turned out the spring in the fixture that makes contact with the bulb tip had weakened, so it only made contact with some bulbs. That's how I discovered that on some bulbs the tip sticks out a little bit more than on others.

Then right as I was thinking "bad contacts can heat and start fires" the thing started to make "kzzzzt" noises. Apparently contact was really bad.
Fix was to Turn off the breaker to the fixture and test to be sure there is no power at the fixture and then pull the spring in the socket a little bit with needle nose pliers   to make sure it made contact again. Or change the socket.
Could also be a bad contact with the wires, or a loose screw, that happened to make contact after you fiddled with it. That's another fire hazard.
Comment: I just had to pull the spring back down and it worked.
Comment: All good advice above. Last thing to check is for a rubber collar that prevents you screwing the bulb in completely.