Creating picture gallery

Question: I want to create a gallery of pictures for my website and upload those pictures from the administration panel of the website. I am going to show all pictures in a page with a very small size, and one place I will separate for each picture to show the selected picture (from small ones) with big size.
I know two ways of doing that:

I create 2 pictures for uploading from administration panel, one big and one small with a fixed size. So the big one I will load in the separate big space. And small will be shown in the small places. So the administrator of the site should CREATE 2 pics.
The second way I know is to use the GD library of PHP to be able to upload only the big picture, and in each place a PHP function will resize the big picture and get the 2 sizes that I need for the gallery.

The first method's disadvantage is, that the user of the site should use Photoshop or some other tool before uploading. Let's agree that this is not a pleasant thing for the site user.
The second approach is not good either, as GD resizes the picture by lowering quality. And that loss is inadmissible because it is too much.
What is a way that does that resize operation while maintaining close to the original picture quality?
Or what is another approach that is better that these two?
Comment: You've put a bounty on this question but haven't commented on any of the answers here, what's wrong with them and what exactly do you need?
Comment: I want more variants of answers to be able to choose a better one for me, as I don't consider that these answers satisfying.
Answer: GD doesn't lose quality any more than Photoshop. Just make sure you are using imagecopyresampled() and NOT imagecopyresized() as that does not do any kind of resampling. Then save the resulting image in high enough quality; for JPEG's, that's around 80.
Then do a similar resize in Photoshop and you'll see there's not much difference. You can also use GD to sharpen your thumbnails, that'll give them a little extra crispness.
EDIT
I made a tool to compare different resize methods, try it out and see for yourself what is the best method: http://www.ulmanen.fi/stuff/downsample/
Comment: @Narek: I also don't think GD loses quality, what I've noticed is a slightly change in color variation. Either you stick to that or use ImageMagik (not sure if the image loses quality, but most people say not) or you just ask your uploaders to use Photoshop and upload 3 separate images. There is no golden solution here.
Comment: I don't agree, that GD doesn't lose quality. Even Microsoft Picture Manager is processing pictures better than GD, even if I programm with imagecopyresampled() with 100% quality.
Comment: +, very nice showcase =) bigger pictures would be nice though, also this image is quite nice to see small differences http://upload.wikimedia.org/wikipedia/commons/c/ce/Quality_comparison_jpg_vs_saveforweb.jpg
Comment: @Alix, the point was to show the differences (or lack of) between downsizing algorithms, that's the reason for small images.
Answer: Use the following function like this:
Image('/path/to/original.image', '1/1', '150*', './thumb.jpg'); // thumb, width = 150 px
Image('/path/to/original.image', null, '600*', './full.jpg'); // full, width = 600 px

You can specify the crop ratio via the second argument (w/h) if you wish, you can also specify the width and/or height of the resized image via the third argument (w*h).
function Image($source, $crop = null, $scale = null, $destination = null)
{
    $source = @ImageCreateFromString(@file_get_contents($source));

    if (is_resource($source) === true)
    {
        $size = array(ImageSX($source), ImageSY($source));

        if (isset($crop) === true)
        {
            $crop = array_filter(explode('/', $crop), 'is_numeric');

            if (count($crop) == 2)
            {
                $crop = array($size[0] / $size[1], $crop[0] / $crop[1]);

                if ($crop[0] > $crop[1])
                {
                    $size[0] = $size[1] * $crop[1];
                }

                else if ($crop[0] < $crop[1])
                {
                    $size[1] = $size[0] / $crop[1];
                }

                $crop = array(ImageSX($source) - $size[0], ImageSY($source) - $size[1]);
            }

            else
            {
                $crop = array(0, 0);
            }
        }

        else
        {
            $crop = array(0, 0);
        }

        if (isset($scale) === true)
        {
            $scale = array_filter(explode('*', $scale), 'is_numeric');

            if (count($scale) >= 1)
            {
                if (empty($scale[0]) === true)
                {
                    $scale[0] = $scale[1] * $size[0] / $size[1];
                }

                else if (empty($scale[1]) === true)
                {
                    $scale[1] = $scale[0] * $size[1] / $size[0];
                }
            }

            else
            {
                $scale = array($size[0], $size[1]);
            }
        }

        else
        {
            $scale = array($size[0], $size[1]);
        }

        $result = ImageCreateTrueColor($scale[0], $scale[1]);

        if (is_resource($result) === true)
        {
            ImageFill($result, 0, 0, IMG_COLOR_TRANSPARENT);
            ImageSaveAlpha($result, true);
            ImageAlphaBlending($result, true);

            if (ImageCopyResampled($result, $source, 0, 0, $crop[0] / 2, $crop[1] / 2, $scale[0], $scale[1], $size[0], $size[1]) === true)
            {
                ImageConvolution($result, array(array(-1, -1, -1), array(-1, 16, -1), array(-1, -1, -1)), 8, 0);
                ImageJPEG($result, $destination, 90);
            }
        }
    }

    return false;
}

The image is automatically enhanced (sharpened) and saved as a JPEG with high quality.
Enjoy!
Answer: You can use ImageMagick instead of GD to get probably better results. I'm not sure what level of integration with your website you need but I suggest checking the open source Gallery project before you start coding.
Answer: Why not use phpThumb()?

You only need to generate src-links for your image tags.
Automatic cache.
Offers a lot of options to manipulate images. See the demo page.
Uses ImageMagick and as fallback GD, that you do not have to care about (but you can).
Nearly everything can be configured. See: phpThumb.config.php.
Comment: phpThumb is pretty good, you can also easily save a copy of the transformation in a cache so you don't have to do the resizing on each load
Answer: How about using the quality argument of imagejpeg when outputting your image?
Answer: I use this simple shell script, which needs convert from ImageMagick:
#!/bin/sh

W=256
T="Some recent photos"

cat <<EOF

<TITLE>$T</TITLE>
<META HTTP-EQUIV="content-type" CONTENT="text/html; charset=iso-8859-1">

$T

Click on the photos to enlarge

EOF

for i
do
convert -resize $W "$i" "T$i"
cat <<EOF

EOF
done

cat <<EOF

EOF

Answer: I would use one file upload and then use ImageMagick to create the thumbnail on the server
(http://www.imagemagick.org/script/index.php)
Answer: If you're not picky about where the images are stored, you could use the Flickr PHP API. Since flickr provides the images in a variety of sizes, it leaves you with making the layout for the gallery.
Check out http://phpflickr.com/
I've used this for a project and was surprised at how easy it was. You can basically do every operation through that API, and you can do it for several users too, so you're going to save yourself and others lots of time. And not to mention space!-)

Creating picture gallery


React unmount a Paypal button

Question: I have a Paypal button rendered with a Modal component. What is the proper way to unmount the Paypal Button without raising a clean up error?
Here is the implementation for the Dialog
<Drawer anchor="bottom" open={open} onClose={() => setStatus(false)}>

            {loading ? '' : 'Checkout'}

          <PaypalButton
            ...props
          />

  </Drawer>

And the button
const Button = paypal.Button.driver('react', { React, ReactDOM });

return (
    <Button
      env={PAYPAL_ENV}
      client={client}
      payment={(data, actions) => payment(data, actions)}
      onAuthorize={data => execute(data.payerID, data.paymentID)}
      style={{
        size: 'medium', // tiny, small, medium
        color: 'blue', // orange, blue, silver
        shape: 'rect', // pill, rect
      }}
    />
  );

The error message I get:

Uncaught Error: No response from window - cleaned up

I do not get this error message when the un-mount is successful, which happens when I processed with a payment.
link:
https://codesandbox.io/s/r4zvkjm2kq
Comment: When do you get that error?
Comment: during `onClose` event. When I try to close the Drawer, which unmounts the paypal button
Comment: I see. Is the Drawer component developed by you? Or is it from a third-party library?
Comment: material ui component
Answer: I couldn't reproduce your issue, but I've tried to do the same code you're doing.
In this example, the PayPal button is mounted in the Drawer element, which is mounted after a button click. The Drawer is unmounted when you click in any place outside the drawer.
class Modal extends React.Component {
    constructor() {
      super()
      this.state = {
        open: false
      }
    }

    render () {
      return (

          <button onClick={() => this.setState({ open: true })}>Open Drawer</button>
          {
            this.state.open &&
            <Drawer anchor="left" open={true} onClose={() => this.setState({ open: false })}>
              <PayPalButton
                commit={this.state.commit}
                env={this.state.env}
                client={this.state.client}
                payment={(data, actions) => this.payment(data, actions) }
                onAuthorize={(data, actions) => this.onAuthorize(data, actions)}
                />
            </Drawer>
          }

       )
    }
  }

Working demo: https://codepen.io/herodrigues/pen/gqQEgr
Comment: The problem with doing it this way the drawer is not controlling the state which losses its transition effects. I tried your code by removing `this.state.open &&`, and pass it to open `props`. The error surfaces.

React unmount a Paypal button


Bad return status for module build on kernel: 3.2.0-56-generic-pae

Question: Description:    Ubuntu 12.04.3 LTS
Release:    12.04
Codename:   precise

Error! Bad return status for module build on kernel: 3.2.0-56-generic-pae (i686)
Consult /var/lib/dkms/alsa-hda/0.201204101019~maverick1/build/make.log for more information.
dpkg: error processing alsa-hda-dkms (--configure):
 subprocess installed post-installation script returned error exit status 10

How can I fix this?
This worked (sudo apt-get purge alsa-hda-dkms ), Thanks,  new to this but not afraid to try.
Comment: What are you trying to do? Maverick is a obsolete version.
Answer: Try this:
sudo apt-get purge alsa-hda-dkms

then install the program again.
Answer: Open a terminal by pressing Ctrl+Alt+T. Write the following command in the terminal and follow the onscreen instructions.
sudo apt-get autoremove
sudo apt-get autoclean
sudo apt-get install --reinstall linux-generic-pae linux-headers-generic-pae

It will reinstall those packages. It may help.


How to call a script inside a template view?

Question: I'm using CodeIgniter and I've actually created a template.php file which have the following structure:
<!DOCTYPE html>

   <?php $this->view('partials/header') ?>

   <body class="<?= !isset($backend) ? 'off-canvas-sidebar' : '' ?>">

         <div class="<?= isset($backend) ? 'main-panel' : '' ?>">

               <?php $this->view($content) ?>

            <?php $this->view('partials/footer') ?>

      <?php
         //Load dynamic scripts
         if(isset($scripts))
         {
            foreach($scripts as $script)
            {
               echo '';
            }
         }
      ?>

essentially when I need to load a view I write in the controller:
$view['content'] = 'auth/login';
$view['scripts'] = ['assets/js/general/auth.js'];
$this->load->view('partials/template', $view);

where content is the path of the view to load inside the template and scripts contains all the javascript files which must be loaded.
The problem is that inside the login.php file, I have:

and this code is executed before the page load, so actually I have this loading execution:

Load header
Load content with script (Auth.initialize)
Load the dynamic script

the auth.js is loaded after the step 2, so I will get an error like:

ReferenceError: $ is not defined

that is because these script are loaded after.
For fix the problem I could add the script in the header but I don't want to do that.
Is there a way to fix this?
Answer: You can rather use the load callback

function require(url, callback) {
  var e = document.createElement("script");
  e.src = url;
  e.type = "text/javascript";
  e.addEventListener('load', callback);
  document.getElementsByTagName("head")[0].appendChild(e);
}

require("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js", function() {
  $(document).ready(function() {
    setTimeout(function() {
      $('.card').removeClass('card-hidden');
    }, 400);
  });
  console.log('loaded');
});


What is the difference between `true` and `isTrue` or `false` and `isFalse` in dart test?

Question: I already know using the isTrue and isFalse matchers can make test assertions more descriptive and easier to read. However, I want to know if there are any other benefits or reasons for using them instead of boolean values.
expect(actual, isTrue);
expect(actual, isFalse);

vs.
expect(actual, true);
expect(actual, false);

Comment: There is no significant difference.  `isTrue` and `isFalse` are `Matcher`s; using `true` or `false` directly will automatically create `equals(true)` and `equals(false)` `Matcher`s for you.  The error messages are slightly different (personally I prefer the `equals` versions).  I would speculate that `isTrue`/`isFalse` perhaps exist as a historical artifact from before `equals` `Matcher`s` were automatically created.
Answer: There is no meaningful behavior difference, it is strictly a style choice. The choice exists for legacy reasons - it is not an intentional design for the library.
There is an insignificant difference in the output when it fails: "Expected: <true>" vs "Expected: true".


Add a word before the last occurrence of double quote

Question: I'm using sed for auto-setup programs with shell scripts. I'm trying to add a word before last quote, the rules are:

Must have double quotes in first argument because of variables
The word before last quote is unknown
I prefer a solution with sed command

The file:
values="word anotherword anyword foo"

The script:
#!/bin/sh
wordtoadd="bar";
sed -i "s/^values=\(*.\)\"/\1$wordtoadd\"/" filetomodify.txt;

The desired result:
values="word anotherword anyword foo bar"

Answer: One way:
sed '/^values=/s/\([^"]*\)"$/\1 '"$wordtoadd"'"/' input

Which, if finds a line starting with values=, replaces the longest match of a series of non-quote characters ([^"]) followed by a quote and the end-of-line ("$) with the match and wordtoend, also putting back the quote (\1 '"$wordtoadd"'").
In your sed expression, \(*.\) should be \(.*\) to quantify the .. And you should also put back the value= part when substituting.
Comment: @Lyoneel, added some explanation.
Comment: ty, i fix my sed command with your suggestions :), works well, can explain better your command syntax?, specially ( $ and [^"]*).
Answer: This might work for you (GNU sed):
sed -r 's/(.*)"/\1'"$wordtoadd"'"/' file


Lexical or Preprocessor issue: 'realm/keys.hpp' file not found

Question: I recently switched to Xcode 11.4 and using Swift 5. I run pod install, Realm and RealmSwift installed with the latest version till date. Now when I run the project, its showing me an error:
..../Pods/Realm/include/binding_context.hpp:24:10: 'realm/keys.hpp' file not found

Podfile:
pod 'Realm', git: 'https://github.com/realm/realm-cocoa.git', branch: 'master', submodules: true
pod 'RealmSwift', git: 'https://github.com/realm/realm-cocoa.git', branch: 'master', submodules: true

Realm framework version: 4.4.1
Cocoapod version: 1.9.1
Xcode version: 11.4
Why is the error occurring and how can we get rid of the same?
Answer: To resolve the issue, I had to:

remove pod 'RealmSwift' from my podfile
run pod install
re-add pod 'RealmSwift' in my podfile
run pod install again to get latest version. It resolved the issue.
Answer: I got rid of the error by updating my pods. I ran pod update in the terminal after navigating to the project folder.


Count the number of non-null values in a Spark DataFrame

Question: I have a data frame with some columns, and before doing analysis, I'd like to understand how complete the data frame is. So I want to filter the data frame and count for each column the number of non-null values, possibly returning a dataframe back.
Basically, I am trying to achieve the same result as expressed in this question but using Scala instead of Python.
Say you have:
val row = Row("x", "y", "z")
val df = sc.parallelize(Seq(row(0, 4, 3), row(None, 3, 4), row(None, None, 5))).toDF()

How can you summarize the number of non-null values for each column and return a dataframe with the same number of columns and just a single row with the answer?
Comment: thanks very much, I'd appreciate if you can share some snippets to better understand the logic you propose: I can write a UDF to do this, but I don't get how I can write a code that will execute the UDF for each column
Answer: One straight forward option is to use .describe() function to get a summary of your data frame, where the count row includes a count of non-null values:
df.describe().filter($"summary" === "count").show
+-------+---+---+---+
|summary|  x|  y|  z|
+-------+---+---+---+
|  count|  1|  2|  3|
+-------+---+---+---+

Comment: this works only for numeric columns, not for String... right?
Comment: This works for string columns with Spark 2.2.1:  Load with a schema so that we get a string column filled with nothing but nulls: `val xx = spark.read.schema(StructType(Seq(StructField("a", LongType, true), StructField("b", LongType, true), StructField("c", StringType, true), StructField("d", StringType, true)))).json("/tmp/toy.jline")` Then describe.
Answer: Although I like Psidoms answer, often I'm more interested in the fraction of null-values, because just the number of non-null values doesn't tell much...
You can do something like:
import org.apache.spark.sql.functions.{sum,when, count}

df.agg(
   (sum(when($"x".isNotNull,0).otherwise(1))/count("*")).as("x : fraction null"),
   (sum(when($"y".isNotNull,0).otherwise(1))/count("*")).as("y : fraction null"),
   (sum(when($"z".isNotNull,0).otherwise(1))/count("*")).as("z : fraction null")
 ).show()

EDIT: sum(when($"x".isNotNull,0).otherwise(1)) can also just be replaced by count($"x") which only counts non-null values. As I find this not obvious, I tend to use the sum notation which is more clear
Answer: Here's how I did it in Scala 2.11, Spark 2.3.1:
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types._

df.agg(
    count("x").divide(count(lit(1)))
        .as("x: percent non-null")
    // ...copy paste that for columns y and z
).head()

count(*) counts non-null rows, count(1) runs on every row.
If you instead want to count percent null in population, find the complement of our count-based equation:
lit(1).minus(
    count("x").divide(count(lit(1)))
    )
    .as("x: percent null")

It's also worth knowing that you can cast nullness to an integer, then sum it.
But it's probably less performant:
// cast null-ness to an integer
sum(col("x").isNull.cast(IntegerType))
    .divide(count(lit(1)))
    .as("x: percent null")

Comment: you can also use `count("*")` instead of `count(lit(1))`, I think this is a bit more readable
Answer: Here is the simplest query:
d.filter($"x" !== null ).count

Answer: df.select(df.columns map count: _*)

or
df.select(df.columns map count: _*).toDF(df.columns: _*)

Answer: Spark 2.3+
(for string and numeric type columns)
df.summary("count").show()
+-------+---+---+---+
|summary|  x|  y|  z|
+-------+---+---+---+
|  count|  1|  2|  3|
+-------+---+---+---+


Installing smart switch in a double gang box with a switch loop (?) - everything in the same circuit - Montreal, Canada

Question: First of all, my terminology may not be the most official or correct, forgive me in advance.
I have this double-gang box, which holds two switches (switch1 and switch2 in the picture).
Switch1: simple switch, lights the corridor lights. The corridor lights have yet another switch on the other side of the room.
Switch2: dimmer switch, lights the living room lights, it's the only switch that controls the living room lights. BK and YL in the diagram refer to the labels on the switch.
Both lights and switches are connected to the same circuit (When I shut the circuit off, both of them go dead)
I would like to replace switch2 with a smart switch, preferably without running any new cables, but I can't figure out how to rearrange the cables. I've searched high and low for days and can't seem to find a single wiring diagram that matches what I have here.
I have a multimeter available if any testing needs to be done, but again, I don't know exactly what I should be looking for.
EDIT: Not shown in the diagram are 4 bare copper wires coming in the box from out of each of the cables, and attached to screws on the box.
Any help would be appreciated :)
Thank you so much!
Answer: This isn't so hard
Since we're only dealing with switch 2 here, we only have to worry about the wires connected to it, which are merely an always-hot coming in, an always-hot feeding off to the other switch, and our switched-hot going out.  The two always-hots get nutted to each other and to a pigtail off to the new smart switch (or to the smart-switch's built-in pigtail if it has one), and the switched-hot in the far right-hand cable gets connected to the switched-hot terminal/lead on the smart-switch. The neutral connection on the smart-switch then goes in with the bundle of white neutral wires already present. Finally, the smart-switch ground wire gets connected to the back of the box, or simply nutted off if your Codes permit switches to be grounded via their mounting screws.
Comment: @JACK -- thanks, fixed!
Comment: So I just need to try to replicate the original connections from the dimmer I want to replace? That was exactly the information I was looking for, thank you so much, I'll try that!
Comment: @GrizzlyFoxCat -- that, and adding the neutral from the smart-dimmer into the neutral bundle


"Pixels out of bounds" error in IRAF

Question: I am trying to do a PSF fitting on a fits image using SNOOPY (a point spread function fitter) and IRAF. I can open this image fine using imexam but when I select a point (a star or whatever) I get an error:
<code>Warning: Pixels out of bounds
</code>
It seems that what I am seeing and what IRAF is seeing (behind the scenes) are not the same. As if there is some kind of a co-ordinate off-shift or something.
How would one go about fixing this ?
[Scientific Linux 6, 16bit , IRAF v2.16]
Answer: If you're using DS9 v7.2 then the problem is a bug in the DS9 cursor read causing the offset.  The only workaround is to use an earlier version of DS9 or a more recent beta.
Comment: Worked perfectly my friend . I was in fact using v7.2 . There is a Beta version v7.3b5 . http://ds9.si.edu/site/Beta.html Not sure what other differences there are between v7.2 and v7.3b5 but this problem is certainly solved . Thanks.
Answer: I am also getting the "Warning Pixels out of bounds" error in imexamine for parts of images in the 8th frame only of an 8 frame FITS image, using DS9 7.3.2 with pyraf.  The 7.3 beta is no longer available.
A workaround is to load the subimage into ds9 using iraf, rather than loading it directly in ds9.

"Pixels out of bounds" error in IRAF


How often can animals breed?

Question: After I've bred two animals, there is a time frame where they wont accept wheat/seeds/carrots, in order to breed again. However I've only got a couple of animals at this stage, and I would like to maximise the efficiency (i.e, minimise the time) in which I get to a relatively large flock/herd.
So, how long do I have to wait before trying to breed them again?
Answer: As stated below on the minecraft wiki about breeding. Breeding has a 5 minute cooldown before they can be bred again.

Each animal which is fed its food will enter "love mode", preparing to breed with another animal in love mode. Animals in "love mode" emit hearts constantly and will path towards nearby animals of the same species that are also in love mode. The two animals will "kiss" for about two and a half seconds, and then a baby animal of the same species spawns either in between the parents or on the same blocks as the parent that was spawned first, which ends love mode for the parents. They will not be able to enter love mode again for 5 minutes. However, they can still be herded with the appropriate material, as can the baby. After the baby animal has spawned, it will follow its parents for 20 minutes before growing to full size.

A little math for a starting animal farm. Lets say you start off with 2 animals of the same species. You mate them and they generate a litte guy. The breeding gets on a 5 min cooldown and the cub starts his 20min journey to maturity. By the time your first cub reaches maturity and is also able to mate you have an additional 3 cubs maturing in 5 - 10 and 15 minutes. So after just 25 minutes you have a second pair of animals which you can breed. This wil double your breeding rate and nog have 2 cubs every 5 minutes. This takes 20 minutes to get effect as for the produced cubs take 20 minutes to reach maturity. In about 1 hour you have around 14 mature animals and around 10 cubs. At this time you have a proper farm going and you can go and do more interesting stuff.
Comment: Well humans are even worse. We have a nine month cooldown ;)
Comment: 5 minute cooldown? I guess if spawning only takes 2.5 seconds, recover would want to be fast ;)

How often can animals breed?


Error while adding IronPython 2.7 in as interpreter to pydev in eclypse juno windows 8

Question: I have iron Python 2.7 installed in:
C:\Program Files (x86)\IronPython 2.7

Iv'e added it to my environment variables as follows
path: [...] ;C:\Program Files (x86)\IronPython 2.7\

When I try to add it as an interpreter in pydev i get the following:
"Error getting info on interpreter"

And in the error log:
org.xml.sax.SAXParseException; lineNumber: 4; columnNumber: 35; The entity name must immediately follow the '&' in the entity reference.

When googling solutions i found a suggestion to make sure i have no environment variables
containing older versions of python (done)
otherwise only solutions for macOS (where this seems to be a common issue)
This problem is not specific to Iron python- the same thing happens when i try the same with python 3.3.2
Answer: Issue fixed buy re-installing pydev from a different repository
initially was installed from http://pydev.org/updates repository. reinstalling from this repository did not help- maybe a temporary issue.
reinstalled from http://pydev.org/nightly repository- this did the trick.
Note- the "contact all update sites during install to find required software" was unchecked.


How to write c# query to find the maximum and minimum value in mongodb

Question: how to write the below queries in c# to find maximum and minimum values
db.col.find().sort({val: 1}).limit(1); //min
db.col.find().sort({val: -1}).limit(1); //max

this is the query which I tried
var cursor = collection.FindAs<BsonDocument>
    (Query.Null).SetSortOrder(SortBy.Descending("_id")).SetLimit(1)
    .SetFields(Fields.Exclude("_id"));

Please help me to proceed.
Comment: Do you use an ORM? Please post more info.
Comment: @Cristian Chereches: yes I'am using ORM. this is the query which I tried    `var cursor = collection.FindAs(Query.Null).SetSortOrder(SortBy.Descending("_id")).SetLimit(1).SetFields(Fields.Exclude("_id"));`  to find maximum value but not getting result
Comment: If you have all the entities in a collection (something like IEnumerable) then you can use collection.Min(item => item.PropertyUsedToCompare) and the same for Max.

This might also help http://stackoverflow.com/questions/1107868/linq-min-max
Answer: You could find the min and max document this way:
var min = collection.FindAll().SetSortOrder(SortBy.Ascending("val")).SetLimit(1).FirstOrDefault();
var max = collection.FindAll().SetSortOrder(SortBy.Descending("val")).SetLimit(1).FirstOrDefault();

Assuming your collection is of type MongoCollection<T>, then your min and max variables are documents of type <T>.
This is what's going on internally:

FindAll returns a MongoCursor<T>
SetSortOrder modifies the cursor by setting a sort order
SetLimit modifies the cursor by setting a limit
FirstOrDefault (a standard .NET LINQ method) enumerates over the cursor and returns the one and only document
Answer: var sort =  Builders<BsonDocument>.Sort.Descending("columnName"); //build sort object
var result = db.Find().Sort(sort).FirstOrDefault(); //apply it to collection


Cublas_Dgemm() not giving me what I expect

Question: I was trying out the library function Cublas_Dgemm() on a small matrix, but it's not giving me what I expect.
So I declare and initialize the matrix in the following way:
<code>    double alpha = 1.0, beta = 0.0;
    double * sa = (double *)malloc(6*sizeof(double));
    double * sb = (double *)malloc(6*sizeof(double));
    double * sc = (double *)malloc(4*sizeof(double));

    for( a = 0; a<2; a++)
            for (b = 0; b < 3; b++){
                    sa[a*3+b] = a+b+1.0;
                    sb[a*3+b] = a+b+1.0;}
</code>
Just for record, I also tried
<code>for( a = 0; a<2; a++)
    for (b = 0; b < 3; b++){
        sa[IDX2F(a, b)] = a+b+1.0;
        sb[IDX2F(a, b)] = a+b+1.0;}
</code>
where
<code>#define IDX2C(i,j,ld) (((j)*(ld))+(i))
</code>
This gives me:
sa:
1.00    2.00    3.00
3.00    2.00    3.00
sb:
1.00    2.00
3.00    2.00
3.00    4.00
And then I allocate memory on GPU as follows:
<code>    double *dsa, *dsb, *dsc;
    cudaMalloc((void **) &dsa, 6*sizeof(*sa));
    cudaMalloc((void **) &dsb, 6*sizeof(*sb));
    cudaMalloc((void **) &dsc, 4*sizeof(*sc));

    cublasSetMatrix(2, 3, sizeof(*sa), sa, 2, dsa, 2);
    cublasSetMatrix(3, 2, sizeof(*sb), sb, 3, dsb, 3);

    cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, 2, 2, 3, &alpha, dsa, 2, dsb, 3, &beta, dsc, 2);

    cublasGetMatrix(2, 2, sizeof(*sc), dsc, 2, sc, 2);
</code>
However, when I print the matrix Sc, I got
sc:
16.00    18.00
23.00    26.00
When it's supposed to be(according to matlab):
16.00    18.00
18.00    22.00
I'm not sure why I'm getting this wrong answer, would anyone spot a possible mistake I made? Thanks tons!
Comment: In addition to the answer of @Robert Crovella, take into account that the values of `sa` that you reported in the question are incorrect (maybe a typo). According to the initialization loop, they are the same as `sb` which are correct.
Answer: I would recommend doing proper error checking on all your cublas calls.
The result you are getting is because cublas expects the matrices given to it to be in column-major order.  The results you are expecting are correct for row-major matrices (and note what @pQB said about the error in your setup code.)
In addition, you can pass row-major ordered data directly to cublas and get sensible results, if you modify the calling setup.
Comment: Hi, I forgot to mention that I tried to initialize my array using IDX2F and IDX2C, but it didn't seem to work either. Is there anyway I could declare my matrices in column-major order?
Comment: Actually I missed the error that @pQB pointed out.  That is actually the source of your confusion, I believe.  16,18,23,26 are the correct values for the matrix multiply.  The only other factor is the order they are presented in, which may vary between row-major and column major.


Set carousel custom button to active when slide is active

Question: I have a classic bootstrap carousel but with some modifications. Basically as you can see by the image below, I have a carousel of chart images. On top of the carousel there is another row with the custom select buttons(sales and tickets).

The problem is that I want to add the active class to the button connected to that slide. Below I provide images of both html and jquery.
HTML

Jquery

Code for HTML

$('#carousel-example-generic').on('slid.bs.carousel', function (event) {
            var nextactiveslide = $(event.relatedTarget).index();
            var $btns = $('.custom-carousel-btns');
            var $active = $btns.find("[data-slide-to='" + nextactiveslide + "']");
            // alert( nextactiveslide );
            $btns.find('.car-ind').removeClass('active');
            $active.find('.car-ind').addClass('active');
        });
/* Charts Carousel */
.carousel-inner > .item > img{
  margin: 0 auto;
}

.car-ind{
  color: grey;
}

.custom-carousel-btns .active{
  color: black;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

 Reports

        Sales
        Tickets

Thank you in advance
Comment: Please share code so that we can run it. Screenshots of the code is not helping much
Comment: I just did, so you can have a look if you want, thanks in advance, very much appreciated.
Answer: Try this :-
$('#carousel-example-generic').on('slid.bs.carousel', function (event) {
        var nextactiveslide = $(event.relatedTarget).index();
        var $btns = $('.car-ind');
        $btns.removeClass('active');
        var $activeBtn = $("[data-slide-to='" + nextactiveslide + "']").addClass('active');
    });

$('#carousel-example-generic').on('slid.bs.carousel', function (event) {
        var nextactiveslide = $(event.relatedTarget).index();
        var $btns = $('.car-ind');
        //var $active = $btns.find("[data-slide-to='" + nextactiveslide + "']");
        // alert( nextactiveslide );
        $btns.removeClass('active');
        var $activeBtn = $("[data-slide-to='" + nextactiveslide + "']").addClass('active');
        // console.log($(".active", event.target).index());
        // $btns.find('.car-ind').removeClass('active');
        // $active.find('.car-ind').addClass('active');
    });
/* Charts Carousel */
.carousel-inner > .item > img{
  margin: 0 auto;
}

.car-ind{
  color: grey;
}

.custom-carousel-btns .active{
  color: black;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

 Reports

        Sales
        Tickets

Comment: Yes it worked! I see what you did there.. Thank you, I appreciate it!


KeepMyFamilySecureLSP64.dll is crashing my GTA 5

Question: If I try to delete it, it comes up with this error:
Action cannot be completed because the file is opened in services.exe.
But when I open services it says it's off.
Comment: How'd you install the game?
Comment: Do you have Kaspersky antivirus? It seems that .dll is related to it somehow.
Comment: @Frank I used rockstar installler
Comment: @TimmyJim Nope i dont have it
Comment: CMON SOMEBODY HELP ME!!
Comment: @Dr.Sheldon-Memer The error you're getting is due to that file being in use elsewhere on the PC. (Which in turn means that it's very likely not GTA 5 related) What information do you have that's telling you that file needs to be deleted to "fix" GTA 5?
Comment: @NBN-Alex I saw it in Event Viewer
Answer: KeepMyFamilySecureLSP64.dll is a part of a parental control software called, unsurprisingly, "Keep my family secure".
Ask whoever controls the PC to disable said parental control software.
Comment: Asked my dad does he control it he said no and my mom doesnt know how to even do it... I trust my dad when he says no because he aint an expert either at it. And i have no parental controls over my PC ;p


Will I get banned by using region restricted games on Steam?

Question: After receiving a game gift which was country restricted, I had to change my Steam store and activate that game by changing my IP. what are the chances of getting banned or anything similar for this action?
I have high level Steam so it's important for me. I know some games are region restricted only for activation but some others are also required to play in that country to, I.e keep having that IP address. but this one is only activation locked. there are many speculations around this so please only answer if you're sure.
Comment: There could be something on ToS @Frank , then again, maybe not
Comment: We have no way of knowing this.  Without Steam having said something, this is totally unanswerable.
Comment: @Oak Could.  Doesn't really mean anything, even if there is.  Either way, it still requires Steam to have said something in order to answer this.
Comment: I once was banned for doing this. They lifted the ban after I contacted steam support and supplied some information about me (ie. last payment via paypal, my ID of who I am etc.) Since then I dont do this anymore.
Answer: From the Steam Subscriber Agreement:

3. BILLING, PAYMENT AND OTHER SUBSCRIPTIONS
A. Payment Authorization
...
  You agree that you will not use IP proxying or other methods to disguise the place of your residence, whether to circumvent geographical restrictions on game content, to purchase at pricing not applicable to your geography, or for any other purpose. If you do this, Valve may terminate your access to your Account.

Emphasis mine. I would highly recommend not spoofing or using proxies to disguise your IP in order to circumvent blocks (on game activation or play). Doing so will run the risk of having your account suspended or terminated.

Further to this: by default, Steam will always try to show you the Storefront from your 'home' region, even when traveling:

What if I am traveling and the product I am trying to purchase has a note about region restrictions?
If you are currently traveling, please ensure that your store region is correctly set to the country where you permanently reside as shown below. You may view and change your store region from your Account Details page. Learn how to change your store country.

And Steam clearly labels any Steam Gifts as being region locked:

Are Steam gifts region restricted?
Gifts purchased in certain regions can be redeemed only in those regions. When you purchase a gift you will be notified at checkout of any restrictions that will be placed on the gift. An example of a gift purchase in Russia and the countries that the gift can be redeemed in is shown below:

I received a Steam gift. How will I know if it has a region restriction?
Each gift will clearly note in the gift's description which countries it can be redeemed in. You can view the description from your Steam gift inventory.
Steam Support cannot modify region restricted gifts. You should contact the friend who gave you the gift to return it or have them ask for a refund.

You can read more about Steam's Region Restrictions on their Support Page


How do I get a hole-in-one?

Question: In Lara Croft: Guardian of Light, in the Spider Tomb level you come across a ball swinging around a post and a challenge is given to achieve a hole-in-one.
I'm probably missing something very obvious, but how is this done? I'm assuming you need to get the ball into the fire pit, but I'm unsure how to detach it from the pole to start with.
Comment: Drop a bomb in its path and detonate it when the ball's close. Not making this an answer because I'm not sure how to get it into the hole consistently.
Answer: To detach the ball, use a bomb. Place the bomb in the path of the ball, towards the back wall. Wait until the ball is above the fire jet 5 jets down and 4 jets in (well, 3 and a half, since the door is between two jets) from the entry door and detonate it. The ball should just roll into the fire pit.
See this video for a better idea.
This is a problem mostly of timing. If you miss on your first attempt you will have to replay the level to try again. If you have previously got the relic when you replay the level, you can lure the golem to the edge of the room, and destroy it without accidentally knocking the ball off in the process.

How do I get a hole-in-one?


CoreBluetooth and Wifi interference

Question: I'm really stuck with a problem, thus, needless to say, I need your help.
I'm using CoreBluetooth to communicate between two iDevices, it is the same app, running as a central on one device and as a peripheral on the other device. In some cases the central loses connection to the peripheral with the following error:
Error Domain=CBErrorDomain Code=10 "The connection has failed unexpectedly." UserInfo=0x14ee8fe0 {NSLocalizedDescription=The connection has failed unexpectedly.}

In this particular case, the peripheral was an iPad 4 and the central was an iPad mini.
I tracked down the problem and it turns out, that once I encounter this issue, the problem will persist every time I connect, regardless of restarting the app or even the bluetooth on both sides, HOWEVER, the interesting part is, if I turn off Wifi on the central device, the connection doesn't time out anymore.
Do you have any suggestions, workarounds? Both devices are running iOS 7.1.1
Answer: This is a well known issue, and it has a solution that is confirmed to work for the Mac side.
sudo defaults write /Library/Preferences/com.apple.airport.bt.plist bluetoothCoexMgmt Hybrid

After you run this script, the issue will go away and BT connections will remain stable.
And here is the explanation:

Background: after a lot of snooping and head scratching, here's what I found: the issue here seems to be that the system isn't using the same Bluetooth/Airport coexistance mode for BLE as it uses for BT Classic. One tell tale sign: if you have any BT Classic devices connected and active, the bug won't repro (neither for the Classic device nor any connected BLE device). The moment the Classic device disconnects, the bug repros (ie all the BLE connections are also dropped).
Further, I was able to find reference in the symbol table of an airport configd agent to an override setting for the coexistance mode. If you set the mode manually as above to 'hybrid' (the same mode that is usually invoked when a classic device is connected), the bug no longer repros.

All credits go to William Henderson from Knock for this trick.
There were cases when the same effect was perceived on iOS devices as well. This some times happens when the Core Bluetooth connections are not stable. Sometimes this can lead to the WiFi connection being unusable. But it's hard to reproduce, at least I wasn't able to, and your question does not concern it either.
Comment: Thanks for the great comment! Indeed, I haven't figured out yet how this issue can be reproduced, it happens mostly after some heavy communication over Bluetooth, but it varies.
Comment: On the Mac this happens if you have a BLE connection and you start using the WiFi at the same time. Without the patch this will most possibly cause an immediate connection break. Just try downloading some file, start a Skype video call or anything that loads the WiFi connection. (torrent is the best for testing :) )
Comment: I was able to consistently reproduce this when using my phone as a wifi hotspot with my computer connected. When that was in place, bluetooth connections would fail 50-60% of the time.

CoreBluetooth and Wifi interference


Device Handling in usb4java

Question: I'm using libusb for communicating with usb device in java. My operating system is linux. But I have problem about open device.
<code>    DeviceHandle handle = LibUsb.openDeviceWithVidPid(null, VENDOR_ID, PRODUCT_ID_1);

    if(handle == null){

        System.out.println("Device Not Opened");
    }else{

        System.out.println("Device Opened");
    }
</code>
I'm getting the error that "handle must not be null".
How can I solve this problem. Thanks for your reply from now.
Answer: I came across your question while searching for another problem. I don't usually program in Java, so there might be some slight differences in the names of the function.
I think the first step you have to do is obtain a Session Handle, which describes the entire operation you are trying to do. Then pass that session handle instead of the NULL to the function you used above.
Here's a reference to MonoUsbSessionHandler:
http://libusbdotnet.sourceforge.net/V2/html/b35376bb-ab07-ee75-8c90-b9f9b12ce067.htm

Device Handling in usb4java


Go modules cannot be updated on GoLand IDE

Question: I'm a beginner on golang. Every time I remove the go 1.13, it suddenly goes back again. I'm not sure why. It has something to do with GoLand?
module github.com/Projec/test

require (
    cloud.google.com/go v0.44.3
    github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect
    github.com/gobuffalo/envy v1.7.1 // indirect
    github.com/helloeave/json v1.11.0
    github.com/labstack/echo v3.3.10+incompatible
    github.com/labstack/gommon v0.2.8 // indirect
    github.com/mailgun/mailgun-go/v3 v3.6.0
    github.com/mattn/go-colorable v0.1.4 // indirect
    github.com/mattn/go-isatty v0.0.9 // indirect
    github.com/metakeule/fmtdate v1.1.2
    github.com/mileusna/useragent v0.0.0-20190129205925-3e331f0949a5
    github.com/murooka/go-diff-image v0.0.0-20171228143924-8c413ad9b24c
    github.com/pkg/errors v0.8.1
    github.com/sergi/go-diff v1.1.0 // indirect
    github.com/valyala/fasttemplate v1.0.1 // indirect
    golang.org/x/crypto v0.0.0-20190829043050-9756ffdc2472
    golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297
    golang.org/x/text v0.3.2
    google.golang.org/api v0.9.0
    google.golang.org/appengine v1.6.2
)

go 1.13

Comment: Do not post images of text.
Comment: And no. This will reapear on every build and you cannot do anything against it and it   is fine.
Answer: You are probably using Go 1.13 to develop your application.
In this case, whenever you run a Go command, like go build, go list, go test, go mod tidy and others, the go.mod file will be modified to have some formatting included, and add missing directives, like the Go version that's compatible with that module.
So, go 1.13 is added to the file automatically, not by the IDE. You can reproduce this by running any of the commands that I listed above.
Comment: I see. So how I can down grade? I think I accidently updated the version from 1.11 to 1.13.
Comment: I'm not sure what you mean in this context. If you want to mark the minimal version for Go that's compatible with the module, then you can change the version from `go 1.13` to `go 1.11`. But that doesn't mean you can't use Go 1.15 to compile it (it should be 100% safe).
Comment: Oh i see. I'm a little confused since when I run the `go version` on my terminal, it says `go 1.11` but on my go.mod file its `go 1.13`. And when I try to remove the `go 1.13` on the go.mod file, it suddenly goes back again. I just want the `go 1.13` to be removed on the go.mod file.
Comment: What's the Go version you are using in the IDE? You can see it under Settings / Preferences | Go | GOROOT. If that's Go 1.13, then that's probably where the difference comes from. Replace `go 1.13` to `go 1.11`, and it should be ok.
Comment: I think that's what I'm trying to find. Thank you so much man!


Why aren't certain indicators showing in Unity?

Question: I've upgraded to Raring a couple of days ago, and noticed that certain indicators are not appearing in my Unity panel, while all other do.
Essentially I'm referring to: pyAlienFX (from http://code.google.com/p/pyalienfx/), Thunderbird (with Firetray extension, https://github.com/foudfou/FireTray.git) and pidgin.
Obviously they all did work with previous 12.10.
Answer: The older system tray has been retired since 10.04 and has now been totally removed in 13.04. pyalienfx needs to use the appindicator, you can file a bug on the program and point to this page:

https://wiki.ubuntu.com/DesktopExperienceTeam/ApplicationIndicators

So that app authors can port their application. This includes a fallback option so the software will still work in older Ubuntus and other distros.
As far as pidgin and thunderbird, those are integrated into the messaging menu (The little envelope).
Here are some other pointers:

How do I migrate from systray to AppIndicators?
Answer: Here's my solution:
How to re-enable the systray whitelist in Ubuntu 13.04 (Raring Ringtail)
If you use such an application and want the systray whitelist back in Ubuntu 13.04, you can use a PPA that comes with Unity patched to re-enable the systray whitelist. To do this, open a terminal and run the following commands:
sudo add-apt-repository ppa:timekiller/unity-systrayfix
sudo apt-get update
sudo apt-get upgrade

Then, restart Unity by pressing ALT + F2 and entering "unity" or by logging out. Then open Dconf Editor, navigate to com > canonical > unity > panel and the "systray-whitelist" should be displayed there so you can enable some apps to be able to use the systray.
After adding an application to the systray whitelist, remember to restart Unity or else it won't work.
source: http://www.webupd8.org/2013/05/how-to-get-systray-whitelist-back-in.html
Comment: You should realise this installs a custom version of Unity.  You are now dependent upon the PPA owner for updates & fixes.
Comment: What alternatives if you NEED one or more indicators?


Calling a C# method from JavaScript

Question: I want to to call a method GetAccount from my controller AccountController.cs, in my JavaScript factory LoginFactory.js. Something like this:
AccountController.cs:
public Account GetAccount(string userName)
    { ... }

LoginFactory.js:
if(x>y) {
   var account = <%AccountController.GetAccount(someParam);%>
}

I've tried using [WebMethod] and Ajax, but I can't get it to work: I get a 404 response.
Comment: Could you please post the code of your Ajax request? And did you check [this](http://stackoverflow.com/questions/18610042/call-c-sharp-method-from-javascript-with-parameter) post?
Comment: If you're getting a 404, almost certainly, your webservice is not deployed onto the server you're hitting or you're hitting the wrong server. I'd look at a Fiddler/Firebug trace to see that it's going to the correct path for your IIS server.
Comment: You cannot call a method directly from client side to server side. Instead, use a service or `WebMethod`. You are claiming that this doesn't work, so please post the code that is failing, both javascript and C# otherwise it will be hard to determine whats wrong.
Answer: Assuming your GetAccount method can be reached at /Account/GetAccount when your application runs, you could use the following:
$.ajax({
  type: 'GET',
  url: '/Account/GetAccount',
  data: { 'username' : 'a-username' },
  dataType: 'json',
  success: function(jsonData) {
    alert(jsonData);
  },
  error: function() {
    alert('error');
  }
});

Note - this is dependant on jQuery.
This causes the browser to make a request to /Account/GetAccount as if you  had done so by entering the URL in the URL bar, but of course, captures the returned json for use in your client side (javascript) script.
If this returns a 404, it would be worth checking your routing.

Calling a C# method from JavaScript


Use the "Starts with" selector in less

Question: Lets say i have a div like

some content

I want to select the div. Normaly no problem... My problem is, there is more css that acts on this div. So I dont want to use !important. I try to use more than one selector to keep this one "important". Now i know there will be a col-m- but i dont know the value.... even if its 1, 2, 3 or what ever...
Actually in CSS i would use
.col-d-1 [class^='col-m-'] {
    background: red;
}

something like this to select my col-d-1 having some col-m-
But how to convert this to less ?
I thought
.col-d-1 {
    &.col-m-* {
        background: red;
    }
}

But nothing i tried works ^^
Any suggestions ?
Or is this less allready ?
Comment: Of course it doesn't work if you change the selector type ... the attribute selector is still the attribute selector, even when you use LESS ... you can not just substitute the class selector for it.
Answer: This should work for you:
.col-d-1 {
    &[class*='col-m-'] {
        background: red;
    }
}

codepen example
Comment: This is preferred to the `caret` option as it selects *regardless* of class order.
Answer: Well, LESS does recognise CSS, so keep it unchanged should work.
The other option is just combine it using the raw selector:
.col-d-1 {
    &[class*='col-m-'] {
        background: red;
    }
}

Because you are pattern-matching on the class attribute, not checking if a class within it starts with col-m-, you need to use the contains selector *=, no the starts-with selector.

Use the "Starts with" selector in less


Is Windows %ERRORLEVEL% == $? in Linux

Question: Trying my hands on windows batch files, in the below code that I found by searching in www.
@ECHO OFF
REM Call this with two arguments, and it will add them.
SET a=%1+%2
IF %ERRORLEVEL%==0 (goto errors-0) ELSE (goto errors-1)
REM Instead of using goto with the variable, this uses an IF-ELSE structure
:errors-0
REM This is if it was successful
ECHO %a%
goto exit
:errors-1
REM this is if it had an error:
ECHO Errors occurred.
goto exit
REM GUESS WHAT, THIS REM WILL NEVER EVER BE READ!  IT WILL BE SKIPPED OVER BY THE GOTOS
:exit
ECHO.
ECHO press any key to exit.
PAUSE>nul

The code is suppose to take 2 arguments, add them and echo the result.
But this won't execute with success on my Windows 8.1 machine. Below is what I get:
C:\ProjectDoc>add3.bat
Errors occurred.

press any key to exit.

So, U added an echo for the ERRORLEVEL to see its value after executing the command SET. Below is the output:
C:\ProjectDoc>add3.bat 2 3
9009
Errors occurred.

press any key to exit.
C:\ProjectDoc>

So, is this errorlevel in Windows equal to the $? of Linux. Should it be returning 0 for every successful execution of a command or is it different? Reading some docs relates it to the Linux $? but it isn't clearly working as $? in Linux.
Comment: Read the help for the `SET` command. Also the dos tag is not valid for this question.
Comment: In general yes, `ErrorLevel` is the return code that indicates success by being `0`; however, the problem is that commands use it differently: some set it in case of errors but do not reset it in case of success (e. g., `set`); some do reset it (e. g., `copy`); some use even non-zero numbers for success, to indicate a result (`choice`)...
Comment: Whether it's "equivalent to $? in unix/linux" depends on which shell you are using in unix/linux.
Comment: Turn `Echo on` on first line and you'll see what is happening.
Comment: The question was "is the errorlevel equivalent to $? For unix/linux"? If u understanding what i am asking
Answer: Yes, to be precise, %errorlevel% is analogous to $? in Bash shell.
In your batch file, SET a=%1+%2 is not doing what you expect it to do. It just sets the value of the variable a to the string "2+3" assuming you ran the file with arguments 2 3. If you want to do arithmetic you need to use the /A option: set /a a=%1+%2.
The SET command (and many other built-in commands) only set the ERRORLEVEL if there has actually been an error. If it was successful, the ERRORLEVEL will retain its previous value. I think this is what you're witnessing in your question.
By contrast, when a command runs an executable file, when the process completes it always sets the ERRORLEVEL.
As well as checking the ERRORLEVEL variable for specific values, it is idiomatic (for historical reasons) to check the errorlevel using the following expression
IF ERRORLEVEL 1 ECHO Hello
This will run the given command if ERRORLEVEL is 1 or above - in other words, if any error has occurred.
Comment: Agreed that the command with the syntax: `SET a=%1+%2` is not performing the arithmetic as desired due to the lack of the option `/a`. But the command as such (without the `/a` switch) is not wrong. It set the value to a string `"2+3"`. So in a Linux environment, the `$?` will return 0 for this. But the windows batch sets/retains a value 9009. why is this so?  Although i think, this is what you are trying to say in the 3rd para of your answer? `"The SET command (and many other built-in commands) only set the ERRORLEVEL if there......................"`
Comment: @OK9999 exactly. The error value 9009 must have been left over from some previous operation, and because the SET command succeeded, it didn't change this error value. cmd.exe is full of quirks.

Is Windows %ERRORLEVEL% == $? in Linux


Align text vertically in a span

Question: I want "text 2" to be aligned vertically center to a text before it (i.e. "text 1" here).
HTML code:
text 1text 2

CSS code:
.two{
    color:red;
    font-size: 12px;
}

I thought vertical-align:middle for the .two class but it doesn't seem to work..
Here is the fiddle
Answer: Create a container for your text content, a span perhaps, and do the following:
span {
    display:inline-block;
    vertical-align:middle;
}

Comment: @JoshC: Yes, I agree. But just one thing to note is that when the font-size is less (say 20px for the first) the vertical-align wouldn't look too obvious. (Atleast in Opera it doesn't). I think adding a `line-height` to the spans in addition to the already suggested would be better.
Answer: You might need to apply vertical-align to both .
span { vertical-align: middle }

http://jsfiddle.net/BBh4e/2/

Align text vertically in a span


Where can user inform Ubuntu Snap Store to update snap from third-party?

Question: Where can user inform Ubuntu Snap Store to update snap from third-party?
Example: Oracle provide VirtualBox latest statble version for Ubuntu.
But Ubuntu SnapStore provide old version.
So Where can user inform Ubuntu Snap Store to update such snaps or such software?
Answer: Via the CLI
If an application is a snap, you can find the contact info of the third-party publisher by running snap info snap-name.
$ snap info foliate
name:      foliate
summary:   A simple and modern eBook viewer
publisher: John Factotum (johnfactotum)
store-url: https://snapcraft.io/foliate
contact:   https://github.com/johnfactotum/foliate/issues
license:   GPL-3.0+
description: |
...

The contact field shows you how to contact the publisher.
Via the Snap Store website.

Go to https://snapcraft.io/store
Search for the snap
Go to the listing page of the snap and click on the "Contact" link below the description.

Snap Not found?
If you can't find the snap in the online snap store, that means it comes from the regular Ubuntu APT repositories. These can only be updated together with Ubuntu itself, so either you upgrade to a newer Ubuntu release, or you contact the developer of the application and ask them to create a Snap.
VirtualBox, for example, is not available as a Snap yet.
Contact info not found?
Some publishers have not filled in the contact info for the Snap. In that case, you will have to use Google to find who is responsible for the Snap.


Read Input of different data types in one line C++

Question: The program I'm working on requires a user to input something like i v or r v, where i means insert, r means remove, and v would be an integer to be inserted or removed.
How can I read the input and separate it into two variables, one for the operator (as in i or d) and another for the value?
Example:
cout << "Enter decision";
cin >> decision;

// somehow split the decision into the two variables below.

int value;
char operation;

Comment: Have you tried: `char operator; int number; std::cin >> operation >> number;`?
Answer: If you want to read something into a std::string (which I assume is what decision is), you should use std::getline. Formatted input, like cin >> decision;, will only read one word by default. Any whitespace character will make it stop reading.
if(std::getline(std::cin, decision)) {
    // successfully read a line
}

You then need to split the decision into the two variables. One simple solution is to use a std::istringstream. You copy the std::string into a std::istringstream and extract the values from it:
#include <sstream>

// ...

    std::istringstream is(decision);
    if(is >> operation >> value) {
        // success
    }

Depending on the rest of the program, another option is to read directly from std::cin into the two variables and skip reading into decision:
if(std::cin >> operation >> value) {
    // success
}

Comment: This is perfect, thank you
Comment: @FayZ Glad to hear it! You're welcome!


Get text preceding image in PDF

Question: What I'm trying to do is extract the image associated with some text in a PDF file. For instance, a PDF would have a photo of the front of a house. Just above the photo, there would be a caption which reads "Front View". I want the program to search the PDF for the text "Front View" and extract the photo that follows it.
I've looked iTextSharp, PDFsharp, and other utilities, but all of them treat the text in a PDF and the images separately. There doesn't seem to be any way to figure out that this line of text comes before that image.
We use iTextSharp for manipulating PDFs. I've written a method in C# that will extract an image given a page number, the number of the image on the page, and the image type. For instance, I can extract the 2nd jpeg on page 3. Here is the code for that. What I would like is to be able to search for a line of text in the file and then extract the image that follows that line of text.
public class ImageExtractor : IRenderListener
{
    int _currentPage = 1;
    int _imageCount = 0;
    int _index = 0;
    int _count = 0;
    readonly string _outputFilePrefix;
    readonly string _outputFolder;
    readonly bool _overwriteExistingFiles;
    string[] _fileTypes;

    public ImageExtractor(string outputFilePrefix, string outputFolder, bool overwriteExistingFiles, string[] fileTypes, int index)
    {
        _outputFilePrefix = outputFilePrefix;
        _outputFolder = outputFolder;
        _overwriteExistingFiles = overwriteExistingFiles;
        _fileTypes = fileTypes;
        _index = index;
    }

    public static int ExtractImageByIndex(string pdfPath, string outputFilePrefix, string outputFolder, bool overwriteExistingFiles, int pageNumber, int index, string[] fileTypes = null)
    {
        // Handle setting of any default values
        outputFilePrefix = outputFilePrefix ?? System.IO.Path.GetFileNameWithoutExtension(pdfPath);
        outputFolder = String.IsNullOrEmpty(outputFolder) ? System.IO.Path.GetDirectoryName(pdfPath) : outputFolder;

        var instance = new ImageExtractor(outputFilePrefix, outputFolder, overwriteExistingFiles, fileTypes, index);
        instance._currentPage = pageNumber;

        using (var pdfReader = new PdfReader(pdfPath))
        {
            if (pdfReader.NumberOfPages == 0)
                return 0;

            if (pdfReader.IsEncrypted())
                throw new ApplicationException(pdfPath + " is encrypted.");

            var pdfParser = new PdfReaderContentParser(pdfReader);

            pdfParser.ProcessContent(instance._currentPage, instance);
        }

        return instance._imageCount;
    }

    public void BeginTextBlock() { }
    public void EndTextBlock() { }
    public void RenderText(TextRenderInfo renderInfo) { }

    public void RenderImage(ImageRenderInfo renderInfo)
    {
        // If _index is greater than 0, we're looking for a specific image. If _count is
        // equal to _index, we've already found it, so don't go any farther.
        if (_index > 0 && _count == _index)
            return;

        var imageObject = renderInfo.GetImage();

        var imageFileName = "";

        if (_fileTypes != null)
        {
            var type = imageObject.GetFileType().ToLower();
            var flag = false;
            foreach (var t in _fileTypes)
            {
                if (t.ToLower() == type)
                {
                    flag = true;
                    break;
                }
            }
            if (flag)
                imageFileName = String.Format("{0}_{1}_{2}.{3}", _outputFilePrefix, _currentPage, _imageCount, imageObject.GetFileType());
        }
        else
        {
            imageFileName = String.Format("{0}_{1}_{2}.{3}", _outputFilePrefix, _currentPage, _imageCount, imageObject.GetFileType());
        }

        if (!string.IsNullOrEmpty(imageFileName))
        {
            // If _index is 0, multiple images may be extracted. If _index is greater than 0,
            // RenderImage will increment count every time it finds an image that matches the
            // file type and will only extract the image if count equals index.
            if (_index > 0)
            {
                _count++;
                if (_count != _index)
                    return;
            }

            var imagePath = System.IO.Path.Combine(_outputFolder, imageFileName);

            if (_overwriteExistingFiles || !File.Exists(imagePath))
            {
                var imageRawBytes = imageObject.GetImageAsBytes();

                File.WriteAllBytes(imagePath, imageRawBytes);

            }

            // Subtle: Always increment even if file is not written. This ensures consistency should only some
            //   of a PDF file's images actually exist.
            _imageCount++;
        }
    }
}

Comment: PDF files may or may not treat images and text "separately", we'd need to see your PDFs to tell. "the line of text that immediately precedes an image" can be interpreted in many ways; you'll have to give a definition of what you mean. Depending on these there are many different approaches, different for each type of software, and you haven't told us what you "looked" at. Hopelessly vague.
Comment: [This answer](https://stackoverflow.com/a/28087521/1729265) shows how to extract text and images including tags in the text representing positions of images in the text flow. The solution is for itext in java and, therefore, should be easy to port to itextsharp in c#.
Comment: I've uploaded some code I wrote that extracts an image based on its page number and it's index on the page. That is, you can tell it to get the 2nd image on the 2nd page. I'm not sure how to upload a sample pdf. Do I need a minimum reputation for that or something? Thanks, mkl, for the "This answer" link. I'll take a look at that and see if it helps.
Answer: As already mentioned in a comment, this is very similar to the topic of the question Extraction of images present inside a paragraph with the main difference that in the context of that question iText for Java was used instead of iTextSharp for .Net.
A port of the Java SimpleMixedExtractionStrategy from that question might look like this:
public class SimpleMixedExtractionStrategy : LocationTextExtractionStrategy
{
    FieldInfo field = typeof(LocationTextExtractionStrategy).GetField("locationalResult", BindingFlags.Instance | BindingFlags.NonPublic);
    LineSegment UNIT_LINE = new LineSegment(new Vector(0, 0, 1), new Vector(1, 0, 1));
    String outputPath;
    String name;
    int counter = 0;

    public SimpleMixedExtractionStrategy(String outputPath, String name)
    {
        this.outputPath = outputPath;
        this.name = name;
    }

    public override void RenderImage(ImageRenderInfo renderInfo)
    {
        PdfImageObject image = renderInfo.GetImage();
        if (image == null) return;
        int number = counter++;
        String filename = name + "-" + number + "." + image.GetFileType();
        File.WriteAllBytes(outputPath + filename, image.GetImageAsBytes());

        LineSegment segment = UNIT_LINE.TransformBy(renderInfo.GetImageCTM());
        TextChunk location = new TextChunk("[" + filename + "]", segment.GetStartPoint(), segment.GetEndPoint(), 0f);

        List<TextChunk> locationalResult = (List<TextChunk>)field.GetValue(this);
        locationalResult.Add(location);
    }
}

Just like in the Java implementation, it is necessary to use reflection to access the private List<TextChunk> locationalResult in LocationTextExtractionStrategy. If the use of reflection is not allowed in your project, you can copy the whole source of LocationTextExtractionStrategy to an own class and apply the changes to the copy.
You might use it like this:
String sourceFile = @"SOURCE.pdf";
String imagePath = @"extract\";
String imageBaseName = "SOURCE-";
Directory.CreateDirectory(imagePath);

using (PdfReader pdfReader = new PdfReader(sourceFile))
{
    PdfReaderContentParser parser = new PdfReaderContentParser(pdfReader);
    for (var i = 1; i <= pdfReader.NumberOfPages; i++)
    {
        SimpleMixedExtractionStrategy listener = new SimpleMixedExtractionStrategy(imagePath, imageBaseName + i);
        parser.ProcessContent(i, listener);
        String text = listener.GetResultantText();
        Console.Write("Text of page {0}:\n---\n{1}\n\n", i, text);
    }
}

For the example file from the referred-to question

the output is:
Text of page 1:
---
Getting Started with Vaadin
• A version of Book of Vaadin that you can browse in the Eclipse Help system.
You can install the plugin as follows:
1. Start Eclipse.
2. Select Help   Software Updates....
3. Select the Available Software tab.
4. Add the Vaadin plugin update site by clicking Add Site....
[book-of-vaadin-page14-1-0.png]
Enter the URL of the Vaadin Update Site: http://vaadin.com/eclipse and click OK. The
Vaadin site should now appear in the Software Updates window.
5. Select all the Vaadin plugins in the tree.
[book-of-vaadin-page14-1-1.png]
Finally, click Install.
Detailed and up-to-date installation instructions for the Eclipse plugin can be found at http://vaad-
in.com/eclipse.
Updating the Vaadin Plugin
If you have automatic updates enabled in Eclipse (see Window   Preferences   Install/Update
  Automatic Updates), the Vaadin plugin will be updated automatically along with other plugins.
Otherwise, you can update the Vaadin plugin (there are actually multiple plugins) manually as
follows:
1. Select Help   Software Updates..., the Software Updates and Add-ons window will
open.
2. Select the Installed Software tab.
14 Vaadin Plugin for Eclipse

Thus, for your task

What I would like is to be able to search for a line of text in the file and then extract the image that follows that line of text.

simply search for that line of text in the output string above and look for the next line containing an image file name in square brackets.
(If your PDF also uses square brackets, you can envelop the file name in other delimiters in the SimpleMixedExtractionStrategy, e.g. some characters from a Unicode private use area.)
Comment: Thank you for your help. Before I saw your post, I managed to come up with a solution which seems to work for me. I'll post that solution below.
Answer: Here's the solution I found. The original code contains a lot of stuff that's not directly related to the question, so I simplified it for the post.
public class ImageExtractor : IRenderListener
{
    private string caption;
    private bool _captionFound;
    private string _outputFolder;

    ....
    ....

    public void BeginTextBlock() { }

    public void EndTextBlock() { }

    public void RenderText(TextRenderInfo renderInfo) {
        // If this line of text contains the caption, set _captionFound to true
        if (renderInfo.GetText().Contains(_caption))
            _captionFound = true;
    }

    public void RenderImage(ImageRenderInfo renderInfo)
    {
        // Skip the image if _captionFound is false
        if (!_captionFound)
            return;

        // _captionFound is true, so extract the image

        // Code to extract image

        // Set _captionFound back to false, so that only the first image found is
        // extracted.
        _captionFound = false;

    }

    public static int ExtractImageByCaption(string caption, string pdfPath, string outputFolder, string outputFolder, bool overwriteExistingFiles, string[] fileTypes = null)
    {
        var instance = new ImageExtractor(outputFilePrefix, outputFolder, overwriteExistingFiles, fileTypes, 0);

        instance._caption = caption;
        instance._outputFolder = outputFolder;

        using (var pdfReader = new PdfReader(pdfPath))
        {
            if (pdfReader.IsEncrypted())
                throw new ApplicationException(pdfPath + " is encrypted.");

            var pdfParser = new PdfReaderContentParser(pdfReader);

            while (instance._currentPage <= pdfReader.NumberOfPages)
            {
                pdfParser.ProcessContent(instance._currentPage, instance);

                instance._currentPage++;
            }
        }
    }
}

Comment: This solution relies on two conditions: **a** the content stream must be drawn in reading order, in particular the image captions right before the images, and **b** the captions must be drawn in a single instruction. Neither of these conditions are automatically true, the pdf format allows content to be drawn in arbitrary order and text lines might be drawn piece-wise. Thus, there may be a number of pdfs this approach works with, but there also are numerous pdfs it won't work with.
Comment: *"The image captions don't have to be right before the image."* - ok, to be more exact, first the caption, then the image must be drawn; and between caption and associated image no other images must be drawn. (There are PDF producers that draw all images at the beginning or at the end, so even those conditions cannot be taken for sure.)
Comment: The image captions don't have to be right before the image. The code extracts the first image it finds after it finds the caption. Otherwise, I agree with you. The pdfs we are using this on come in a standard format, so it should work for them. I'm not claiming this will work for every type of pdf.

Get text preceding image in PDF


My breaker panel is full but I need to add at least 3 double pole 30 amp breakers. Will I exceed my service line rating?

Question: My breaker panel is full, but I need to add at least 3 double pole 30 amp breakers.
I believe after I do the math on the room size and what would be needed for space heating baseboards I'm assuming I need 3 30 amp double pole breakers.
I'm not sure if I have to subpanel off of it or run a new panel altogether. It's a challenger 100 amp panel.. no it's not a Stab-Lok.
I know I would need to know if the service line is big enough first to handle the load. I am also not sure how they rate panels and loads and such. I assume that it is under full threshold load capacity before breaking the main, but what confuses me is I've seen so many panels overloaded when going to customers homes and wondered if I add up all the numbers they exceed the main breaker size how is that?
Should I sub or replace with 150 or possibly 200 amp for future addition to the newly added addition the owner decided to do for an extra apt in the attic to extend the second floor apt.. once I know what to look for in the existing service line.
If it's not rated high enough to handle the full load then it's a no-go, right?
Then my other option is to have a licensed electrician install a new line, weather-head and socket, I can do the rest from there. It wouldn't be my first time installing a new panel.
Comment: Get cold-climate mini-split heatpumps (~300% efficiency based on electrical input) instead of baseboard resistance heat (100%) and you'll need about 1/3 the power supply, and lower power bills to match.
Comment: We would need to know the other loads but adding ~75 amp load to your service load is fairly large (note 30 amp breakers are 24 amp each by code this is where the 75 comes from)
Comment: There are probably easier ways to get heat.  Most breakers in a home panel are only using a few amps and nowhere near the number of amps listed on them.  A 15 amp breaker for lights might only use maybe 5 amps with all the lights on.  Most of the larger breakers only use their power of part of the time, a 40 amp stove breaker maybe a couple hours a day.  Electric heat has probably the most full time use of your breakers.
Answer:
It's a challenger 100 amp panel.. no it's not a Stab-Lok.

There's nothing wrong with Challenger panels.  But Challenger breakers were caught in a VW-like cheating scandal; they don't trip when they're supposed to.  Only Type C and Type A breakers will fit in a Challenger panel, fortunately Eaton BR breakers are cross-listed Type C, and BR tandems are cross-listed Type A.  So all the Challenger breakers need to go and be replaced by Eaton BR/C/A.  BR is the most popular breaker type in North America.

what confuses me is I've seen so many panels overloaded when going to customers homes and wondered if I add up all the numbers they exceed the main breaker size how is that?

Oversubscribing panels is allowed because nobody maxes out all their circuits at the same time. Also, USA panels are actually 240V, and so we have two banks of 120V at full amperage.
There's an old joke... someone says to their banker "Overdrawn? How can my account be overdrawn?  I still have checks left in my checkbook!"  Number of spaces available in your panel is a lot like that.  It has nothing to do with the actual electrical load.
Both these issues are resolved by a procedure called a Load Calculation.  There is the official, NEC-approved way to do that.  Some of the math gets tricky especially with ranges, but the good news is you don't need to tally up lighting or any of your plug-in 120V loads, as those are accounted for in "catch-all" figures.

When you say "Common" do you mean "common" off the timer labeling.... or do you mean "Neutral"?  They are not the same thing.  Neutral is not "common", common is a hot line actually.

I presume the house was heated previously, so it sounds like you are converting from another heating technology to electric resistive heating. This is a huge electrical load change, and absolutely requires a new Load Calculation. Really any new large appliance requires a new Load Calculation, but this most particularly.
Fully expect to find your electric service is inadequate and that a "heavy-up" would be called for.  This would be a great time to address the full panel - a new main panel can be added, and the existing Challenger panel can be re-configured as a subpanel so you don't have to rewire.
Make sure you have a full understanding of your power company's local rate tariffs before installing electric resistance heating as a heat source. This is cheap to install but incredibly expensive to operate, unless you really know what you're doing re: power company tariffs. Resistive heating is cheap to install but prohibitive to operate. Better off with modern heat pump tech.
If your plan is to have the tenant pay the electric bill, then you can't DIY this work - all electrical work on rental units must be done by a pro electrician (who will do the permits, Load Calculation and possible heavy-up as part of the job). HVAC contractors have been known to do "light" electrical work related to their installation, but we see a lot of work that is just terrible.

Should I sub or replace with 150 or possibly 200 amp for future addition to the newly added addition the owner decided to do for an extra apt in the attic to extend the second floor apt.. once I know what to look for in the existing service line.

Nope, you doing electrical work for a third party is out of the question.  To DIY electrical work, you must a) own the property, b) be the planned occupant of the unit in which you are working (and NO homeowner is going to install baseboard heat unless they have a favorable tariff), and c) pull permits and get inspections.
It sounds like a) this is for your customer and b) they are a landlord renting to tenants, which explains the cheap-to-build, expensive-to-run electric heating.   Of course that particular slice of slumlord bastardry only works if there are individual electric meters to each unit! Which precludes the method you are proposing.

Then my other option is to have a licensed electrician install a new line, weather-head and socket, I can do the rest from there.
It wouldn't be my first time installing a new panel.. I'm very meticulous or anal about safety... something I have to be when it comes to stuff like this..

And yet, you are involved in this dubious scheme.

I've been running a micro business for years with plumbing, heating, electrical and now large kitchen and bath appliances with a very good success rate at not failing stuff I knew nothing about, but with reading here and elsewhere and by the grace of God things turned out well, all homes are intact years later..

Animals collect safety data only by what they witness for themselves.  We have very bold pigeons in our local park. Catching one is easy, but if you do, only the pigeons who saw that happen become afraid of people.  Whereas human beings are able to share experiences so all humans learn from the experience of others far away from them.  So when you say "none of my buildings exploded (that I know of)", that is the animal way of analyzing data.  The human way is what the Electrical Code is.
Professionals do real analysis of thousands of accidents.  The result of that analysis is the Electrical Code. It's not New York lawyers dreaming up stupid requirements to inconvenience you or cost you money. Every rule is written in blood and ash.
Answer: You've got three separate issues here:

Panel space

Sometimes that can be resolved by merging circuits and/or putting half-size breakers in place of full-size breakers. If that isn't enough (or isn't allowed - there are many constraints depending on panel type, circuit types, etc.) then you either have to replace the panel with a larger panel or install a subpanel.

Panel capacity

You currently have a 100A main breaker. In some cases (especially with newer panels, not as likely with an old Challenger) you can install a larger main breaker because the rest of the panel is designed to handle more current. But with a 100A main breaker on an older panel, it is quite likely to have a true maximum of either 100A or 125A. To be honest, adding 90A of load (which may all be used at once since the heaters are likely to all run at the same time on cold days) plus other loads (lighting, receptacles, appliances) is likely to get you way over 125A.

Service capacity

The service from the utility is out of your control. But your main breaker has to be matched (equal or less than) to the service capacity. If your utility is providing 100A service, you can't switch to a new panel with a 200A main breaker. On the other hand, if your utility is already providing 200A service then you can make that upgrade. The only people who can give you a definitive answer on that are at the utility company. My hunch is you have older service that was 100A maximum at the time, in which case (as in my house) the upgrade requires more than just a new panel but also a new meter and service entrance cable. But you need to find out before you add 90A of load.
In addition, you really should do a load calculation. This factors in heating, air conditioning (which, if different devices, don't run at the same time), cooking appliances (which have special rules), size of the house, type of appliances, etc. Once you have done that, with the new heating system included, you can determine what you need to do about your panel and your utility service.
As others have mentioned, electric resistance heat is cheap to install but expensive to run. Installing a heat pump will cost a lot more to install, but it might use just enough less power to avoid having to put in a new panel and upgrade the utility service - which might well be a significant net savings.


flatten nested dictionary in list

Question: I have a data from Facebook Insights API and some columns in the data look like this:
"[{'action_type': 'link_click', 'value': '812'}, {'action_type':'page_engagement','value':'823'}, {'action_type': 'post_engagement', 'value': '823'}, {'action_type':'post', 'value': '1'}, {'action_type': 'post_reaction', 'value': '10'}, {'action_type':'landing_page_view', 'value': '143'}]"]

I'm trying to put the data here in a dataframe, but there is a different campaign in each row and I need to add more than one row for a campaign here, so for campaign a, link click: 812 is also post_engag for campaign a. 823 and these need to be in separate columns for that campaign, so the data needs to be separated as follows:
link_click    page_engagement   post_engagement  post   post_reaction   landing_page_view
   812              823              823          1         10               143

I have a method but I get an error:
def function2(df, col_name, filter="action_type",
                        which_fields=''):
    xx = df[xcol].apply(pd.Series).merge(df["index"], right_index=True, left_index=True).melt
    xx2 = xx[col_name].apply(pd.Series).merge(xx["index"], right_index=True, left_index=True)
    xx2 = xx2.loc[xx2[filter] == which_fields, ["value", "index"]]
    xx2.rename(columns={"value": col_name + '_' + which_fields.replace('.','_')},inplace=True)

    return xx2

The error I get is:
    raise KeyError(key) from err
KeyError: 'action_type'

How can I do that with Python ?
Answer: You can use ast.literal_eval and the DataFrame constructor:
from ast import literal_eval

out = pd.DataFrame(literal_eval(s)).set_index('action_type').T

output:
action_type link_click page_engagement post_engagement post post_reaction landing_page_view
value              812             823             823    1            10               143

used input:
s = "[{'action_type': 'link_click', 'value': '812'}, {'action_type':'page_engagement','value':'823'}, {'action_type': 'post_engagement', 'value': '823'}, {'action_type':'post', 'value': '1'}, {'action_type': 'post_reaction', 'value': '10'}, {'action_type':'landing_page_view', 'value': '143'}]"

Answer: Try:
lst = [
    {"action_type": "link_click", "value": "812"},
    {"action_type": "page_engagement", "value": "823"},
    {"action_type": "post_engagement", "value": "823"},
    {"action_type": "post", "value": "1"},
    {"action_type": "post_reaction", "value": "10"},
    {"action_type": "landing_page_view", "value": "143"},
]

df = pd.DataFrame([{d.get("action_type"): d.get("value") for d in lst}])
print(df)

Prints:
  link_click page_engagement post_engagement post post_reaction landing_page_view
0        812             823             823    1            10               143

flatten nested dictionary in list


Bat error set was unexpected this time

Question: Hello i need help with my .bat program it fails here for some
Comment: You should include your code in the question, not in an image though.
Comment: Wrong syntax. Should be `if exist "....." (set "loginpass=true") else (set "loginpass=false")` Also you can directly go to labels in the first comparison.
Comment: When testing if the variable is equal to true or false you should also have quotes around true and false.
Answer: Let's disassemble your line
if else set "loginpass=false

Syntax is: if <string1> <condition> <string2> <command>
so, your <string1> would be else, your <condition> would be set - wait - that is not a valid condition, is it? So it tells you "sorry, I don't know what to do with set in this place"
wOxxOm gave you a better Syntax in his comment:
if exist "....." (set "loginpass=true") else (set "loginpass=false")

He also suggested to use goto in this place:
 if exist "....." (goto :loginpass) else (goto :errornum3)

Comment: Yeah i think im going with that

Bat error set was unexpected this time


How do you load a season in MLB 2K6?

Question: We just got an Xbox 360 for the kids and I bought an old cheap game: MLB 2K6.  My son was able to figure out how to start and save a season under VIP1, and we can go under Manage Seasons.  But he and I can not figure out how to load the seasons up so it continues playing. Do I need to have an Xbox Live account setup to do that?
What are the steps to load the seasons?  When he hits play it gives him the choices to pick two new teams to start a game, but those are not for the season.
Answer: The 2K6 games are set up differently from EA's sports games (not that it matters now, as EA's pushed 2K out of most sports), and the menu system is not easy to figure out. To load a season that you've created,

From the Main Menu, select My 2K6. A menu will appear on the right side of the screen.
Select Save/Load. The menu on the right side will change.
Select Load. You'll get a prompt from the 360 to select a device - this is the standard dialog box across all games that the 360 uses. Select the device on which the games are stored; it's most likely your hard drive. The 360 menu will close and the Load menu will appear.
Every type of file that has been saved will appear on this screen. Look in the Type column for Season; this is the season file (probably called Season1) that your son saved. Select the saved season.
A dialog box will appear that says "Caution: Loading now will lose any of your previously unsaved changes. Continue?" Select Yes.

You should get a message that the season is loading and then a dialog box telling you that it was successfully loaded.

How do you load a season in MLB 2K6?


Patches on my california basement wall

Question: I'm seeing large patches on my California basement wall.
It is a tiny basement that is common in Los Angeles area. The basement is in the middle of the house, so it is quite far from the perimeter. The patch seems a little moist and the wall material seems to have dissolved a little as can be seen by the white powder and the texture of the wall
What is causing it? What can be done to prevent it from getting worse? Is it a big concern?

Thank you!
Comment: Is this common? Would the wall crumble eventually? It is quite far from the perimeter of the house and rain water is redirected away. Although there are some cracks between the driveway and the exterior of the house. I wonder if it sips in from there.
Comment: I'm going to post my response as an answer. You should [take our tour](https://diy.stackexchange.com/tour) so you know how our site works with upvotes for helpful answers and checks for accepted answers.
Answer: What your seeing is called efflorescence which are mineral deposits from moisture which sometimes seeps through exterior walls. Even though the basement walls may be inset from  the main level water will migrate through soil layers. It appears that the other side of that wall is in contact with compacted soil. Even if it was water-proofed during construction moisture can sometimes seep through.
I don't think it looks serious. It would be different if water was obvious or pooling on the interior. At this point you can treat the interior walls with water-proofing material such as Drylok or Flex Seal. Although it might solve the efflorescence issue it won't keep moisture from seeping into the wall from the soil. The other option is to excavate the exterior of the wall and treat it with water-proofing which would be labor-intensive or prohibitively expensive.
As I indicated I would try to keep exterior groundwater away from the foundation and if the efflorescence is a major concern for you can treat the wall with an interior water-proofing product.

Patches on my california basement wall


Last printf statement is being skipped

Question: After insertting all my values I was expecting to have the final printf statement give the final results of the equations
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char *carModel;
    float tankRange;
    float gasCost;
    float costTank;
    float gallonsTank; //gallons in full tank
    float mpg; //miles per gallon
    float costMile;

    carModel = malloc(256);

    printf("What is the model of car? " );
    scanf("%255s", &carModel);  // Don't read more than 255 chars
    printf("How many miles can be driven on a full tank? " );
    scanf("%f", &tankRange);
    printf("What is the gas cost per gallon? " );
    scanf("%f", &gasCost);
    printf("How much does it cost to fill the tank? " );
    scanf("%f", &costTank);
    gallonsTank = costTank / gasCost;
    mpg = tankRange / gallonsTank;
    costMile = mpg / gasCost;
    printf("Amazing! %255s has an mpg of %.3f per gallon! You spent $%.2f to drive one mile!\n",  carModel, mpg, costMile);

return 0;

}

All of it prints and runs well except for the last printf statement, it shows that the code is finished running
Comment: Hint: where does `carModel` point to?
Comment: You're better using a constant like in my answer to the last version of this question than hard-coding the magic values 256 and 255.  Heap allocated memory carries with it a liability to explicitly free() it again.  It doesn't matter here but you want to make that a habit.
Comment: Prefer double to float.
Comment: Prefer initialized variables.  `char *carModel = malloc(...);`, `double gallonsTank = costTAnk / gasCost;`.  This also reduces scope as variables which makes your code easier to read and reason about.
Comment: If you operate on such small arrays and don't need longer lifetime than the function body you usually are better off with a local array: `char carModel[256];` Still be aware that these arrays decay to pointers implicitly, so again `scanf(..., &carModel);` would have been wrong (undefined behaviour for mismatching pointer types) even though, due to the equality of the addresses of `&carModel` and `&carModel[0]`, it would have been pretty likely that you would have experienced the desired result – so indeed the more natural way would in this case have hidden the error away, unfortunately :(
Comment: *'Prefer double to float'* – even better: avoid floating point entirely! You need to be aware that even many of such simple numbers like 0.1 (this one included) cannot be represented exactly as they are periodic in binary. Usually you are far better off with fixed comma arithmetic (i.e. doing calculations in sub-units like milliseconds instead of seconds, in cents instead of euros/dollars/... or 10th of, ...). Admitted, IO, if presented in whole units, gets more complicated, but in most cases you'll profit everywhere else from.
Answer: This call of scanf is incorrect
printf("What is the model of car? " );
scanf("%255s", &carModel);  // Don't read more than 255 chars
               ^^^^^^^^^

instead you have to write
printf("What is the model of car? " );
scanf("%255s", carModel);  // Don't read more than 255 chars

Otherwise the call of scanf overwrites the memory occupied by the local variables.
The conversion specifier s expects an argument of the type char * while you are passing an argument of the type char **.
If you want to input a string that contains more than one word then you can write for example
printf("What is the model of car? " );
scanf("%255[^\n]", carModel);  // Don't read more than 255 chars

Pay attention to that you should free the allocated memory at the end of the program
free( carModel );

Last printf statement is being skipped