Programs & Examples On #Column types

Add Auto-Increment ID to existing table?

Proceed like that :

Make a dump of your database first

Remove the primary key like that

ALTER TABLE yourtable DROP PRIMARY KEY

Add the new column like that

ALTER TABLE yourtable add column Id INT NOT NULL AUTO_INCREMENT FIRST, ADD primary KEY Id(Id)

The table will be looked and the AutoInc updated.

Add another class to a div

If the element has no class, give it one. Otherwise, append a space followed by the new className:

  var el = document.getElementById('hello');
  if(el) {
    el.className += el.className ? ' someClass' : 'someClass';
  }

How can I disable ARC for a single file in a project?

Note: if you want to disable ARC for many files, you have to:

  1. open "Build phases" -> "Compile sources"
  2. select files with "left_mouse" + "cmd" (for separated files) or + "shift" (for grouped files - select first and last)
  3. press "enter"
  4. paste -fno-objc-arc
  5. press "enter" again
  6. profit!

How do you search an amazon s3 bucket?

This is little bit old thread - but maybe help someone who still search - I'm the one who search for that a year.

Solution may be "AWS Athena" where you can search over data like this

'SELECT user_name FROM S3Object WHERE cast(age as int) > 20'

https://aws.amazon.com/blogs/developer/introducing-support-for-amazon-s3-select-in-the-aws-sdk-for-javascript/

Currently pricing is $5 for 1TB data - so for example, if your query search over one 1TB file 3times your cost is $15 - but for example if there is only 1column in "converted columnar format" what you want read, you'll pay 1/3 of price means $1.67/TB.

Cast Int to enum in Java

You can try like this.
Create Class with element id.

      public Enum MyEnum {
        THIS(5),
        THAT(16),
        THE_OTHER(35);

        private int id; // Could be other data type besides int
        private MyEnum(int id) {
            this.id = id;
        }

        public static MyEnum fromId(int id) {
                for (MyEnum type : values()) {
                    if (type.getId() == id) {
                        return type;
                    }
                }
                return null;
            }
      }

Now Fetch this Enum using id as int.

MyEnum myEnum = MyEnum.fromId(5);

Quickly reading very large tables as dataframes

I am reading data very quickly using the new arrow package. It appears to be in a fairly early stage.

Specifically, I am using the parquet columnar format. This converts back to a data.frame in R, but you can get even deeper speedups if you do not. This format is convenient as it can be used from Python as well.

My main use case for this is on a fairly restrained RShiny server. For these reasons, I prefer to keep data attached to the Apps (i.e., out of SQL), and therefore require small file size as well as speed.

This linked article provides benchmarking and a good overview. I have quoted some interesting points below.

https://ursalabs.org/blog/2019-10-columnar-perf/

File Size

That is, the Parquet file is half as big as even the gzipped CSV. One of the reasons that the Parquet file is so small is because of dictionary-encoding (also called “dictionary compression”). Dictionary compression can yield substantially better compression than using a general purpose bytes compressor like LZ4 or ZSTD (which are used in the FST format). Parquet was designed to produce very small files that are fast to read.

Read Speed

When controlling by output type (e.g. comparing all R data.frame outputs with each other) we see the the performance of Parquet, Feather, and FST falls within a relatively small margin of each other. The same is true of the pandas.DataFrame outputs. data.table::fread is impressively competitive with the 1.5 GB file size but lags the others on the 2.5 GB CSV.


Independent Test

I performed some independent benchmarking on a simulated dataset of 1,000,000 rows. Basically I shuffled a bunch of things around to attempt to challenge the compression. Also I added a short text field of random words and two simulated factors.

Data

library(dplyr)
library(tibble)
library(OpenRepGrid)

n <- 1000000

set.seed(1234)
some_levels1 <- sapply(1:10, function(x) paste(LETTERS[sample(1:26, size = sample(3:8, 1), replace = TRUE)], collapse = ""))
some_levels2 <- sapply(1:65, function(x) paste(LETTERS[sample(1:26, size = sample(5:16, 1), replace = TRUE)], collapse = ""))


test_data <- mtcars %>%
  rownames_to_column() %>%
  sample_n(n, replace = TRUE) %>%
  mutate_all(~ sample(., length(.))) %>%
  mutate(factor1 = sample(some_levels1, n, replace = TRUE),
         factor2 = sample(some_levels2, n, replace = TRUE),
         text = randomSentences(n, sample(3:8, n, replace = TRUE))
         )

Read and Write

Writing the data is easy.

library(arrow)

write_parquet(test_data , "test_data.parquet")

# you can also mess with the compression
write_parquet(test_data, "test_data2.parquet", compress = "gzip", compression_level = 9)

Reading the data is also easy.

read_parquet("test_data.parquet")

# this option will result in lightning fast reads, but in a different format.
read_parquet("test_data2.parquet", as_data_frame = FALSE)

I tested reading this data against a few of the competing options, and did get slightly different results than with the article above, which is expected.

benchmarking

This file is nowhere near as large as the benchmark article, so maybe that is the difference.

Tests

  • rds: test_data.rds (20.3 MB)
  • parquet2_native: (14.9 MB with higher compression and as_data_frame = FALSE)
  • parquet2: test_data2.parquet (14.9 MB with higher compression)
  • parquet: test_data.parquet (40.7 MB)
  • fst2: test_data2.fst (27.9 MB with higher compression)
  • fst: test_data.fst (76.8 MB)
  • fread2: test_data.csv.gz (23.6MB)
  • fread: test_data.csv (98.7MB)
  • feather_arrow: test_data.feather (157.2 MB read with arrow)
  • feather: test_data.feather (157.2 MB read with feather)

Observations

For this particular file, fread is actually very fast. I like the small file size from the highly compressed parquet2 test. I may invest the time to work with the native data format rather than a data.frame if I really need the speed up.

Here fst is also a great choice. I would either use the highly compressed fst format or the highly compressed parquet depending on if I needed the speed or file size trade off.

How do I specify the JDK for a GlassFish domain?

Had the same problem in my IntelliJ 17 after adding fresh glassfish 4.1.

I had set my JAVA_HOME environment variable as follow:

echo %JAVA_HOME%
C:\Java\jdk1.8.0_121\

Then opened %GLASSFISH_HOME%\glassfish\config\asenv.bat

And just added and the end of the file:

set AS_JAVA=%JAVA_HOME%

Then Glassfish started without problems.

How do I interpret precision and scale of a number in a database?

Numeric precision refers to the maximum number of digits that are present in the number.

ie 1234567.89 has a precision of 9

Numeric scale refers to the maximum number of decimal places

ie 123456.789 has a scale of 3

Thus the maximum allowed value for decimal(5,2) is 999.99

illegal character in path

You seem to have the quote marks (") embedded in your string at the start and the end. These are not needed and are illegal characters in a path. How are you initializing the string with the path?

This can be seen from the debugger visualizer, as the string starts with "\" and ends with \"", it shows that the quotes are part of the string, when they shouldn't be.

You can do two thing - a regular escaped string (using \) or a verbatim string literal (that starts with a @):

  string str = "C:\\Program Files (x86)\\test software\\myapp\\demo.exe";

Or:

  string verbatim = @"C:\Program Files (x86)\test software\myapp\demo.exe";

Material UI and Grid system

I looked around for an answer to this and the best way I found was to use Flex and inline styling on different components.

For example, to make two paper components divide my full screen in 2 vertical components (in ration of 1:4), the following code works fine.

const styles = {
  div:{
    display: 'flex',
    flexDirection: 'row wrap',
    padding: 20,
    width: '100%'
  },
  paperLeft:{
    flex: 1,
    height: '100%',
    margin: 10,
    textAlign: 'center',
    padding: 10
  },
  paperRight:{
    height: 600,
    flex: 4,
    margin: 10,
    textAlign: 'center',
  }
};

class ExampleComponent extends React.Component {
  render() {
    return (
      <div>
        <div style={styles.div}>
          <Paper zDepth={3} style={styles.paperLeft}>
            <h4>First Vertical component</h4>
          </Paper>
          <Paper zDepth={3} style={styles.paperRight}>
              <h4>Second Vertical component</h4>
          </Paper>
        </div>
      </div>
    )
  }
}

Now, with some more calculations, you can easily divide your components on a page.

Further Reading on flex

No assembly found containing an OwinStartupAttribute Error

Check if you have the Startup class created in your project. This is an example:

using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof({project_name}.Startup))]

namespace AuctionPortal
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

jquery how to get the page's current screen top position?

var top = $('html').offset().top;

should do it.

edit: this is the negative of $(document).scrollTop()

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

<?php

    /**
     * Comparison of two PHP objects                         ==     ===
     * Checks for
     * 1. References                                         yes    yes
     * 2. Instances with matching attributes and its values  yes    no
     * 3. Instances with different attributes                yes    no
     **/

    // There is no need to worry about comparing visibility of property or
    // method, because it will be the same whenever an object instance is
    // created, however visibility of an object can be modified during run
    // time using ReflectionClass()
    // http://php.net/manual/en/reflectionproperty.setaccessible.php
    //
    class Foo
    {
        public $foobar = 1;

        public function createNewProperty($name, $value)
        {
            $this->{$name} = $value;
        }
    }

    class Bar
    {
    }
    // 1. Object handles or references
    // Is an object a reference to itself or a clone or totally a different object?
    //
    //   ==  true   Name of two objects are same, for example, Foo() and Foo()
    //   ==  false  Name of two objects are different, for example, Foo() and Bar()
    //   === true   ID of two objects are same, for example, 1 and 1
    //   === false  ID of two objects are different, for example, 1 and 2

    echo "1. Object handles or references (both == and    ===) <br />";

    $bar = new Foo();    // New object Foo() created
    $bar2 = new Foo();   // New object Foo() created
    $baz = clone $bar;   // Object Foo() cloned
    $qux = $bar;         // Object Foo() referenced
    $norf = new Bar();   // New object Bar() created
    echo "bar";
    var_dump($bar);
    echo "baz";
    var_dump($baz);
    echo "qux";
    var_dump($qux);
    echo "bar2";
    var_dump($bar2);
    echo "norf";
    var_dump($norf);

    // Clone: == true and === false
    echo '$bar == $bar2';
    var_dump($bar == $bar2); // true

    echo '$bar === $bar2';
    var_dump($bar === $bar2); // false

    echo '$bar == $baz';
    var_dump($bar == $baz); // true

    echo '$bar === $baz';
    var_dump($bar === $baz); // false

    // Object reference: == true and === true
    echo '$bar == $qux';
    var_dump($bar == $qux); // true

    echo '$bar === $qux';
    var_dump($bar === $qux); // true

    // Two different objects: == false and === false
    echo '$bar == $norf';
    var_dump($bar == $norf); // false

    echo '$bar === $norf';
    var_dump($bar === $norf); // false

    // 2. Instances with matching attributes and its values (only ==).
    //    What happens when objects (even in cloned object) have same
    //    attributes but varying values?

    // $foobar value is different
    echo "2. Instances with matching attributes  and its values (only ==) <br />";

    $baz->foobar = 2;
    echo '$foobar' . " value is different <br />";
    echo '$bar->foobar = ' . $bar->foobar . "<br />";
    echo '$baz->foobar = ' . $baz->foobar . "<br />";
    echo '$bar == $baz';
    var_dump($bar == $baz); // false

    // $foobar's value is the same again
    $baz->foobar = 1;
    echo '$foobar' . " value is the same again <br />";
    echo '$bar->foobar is ' . $bar->foobar . "<br />";
    echo '$baz->foobar is ' . $baz->foobar . "<br />";
    echo '$bar == $baz';
    var_dump($bar == $baz); // true

    // Changing values of properties in $qux object will change the property
    // value of $bar and evaluates true always, because $qux = &$bar.
    $qux->foobar = 2;
    echo '$foobar value of both $qux and $bar is 2, because $qux = &$bar' . "<br />";
    echo '$qux->foobar is ' . $qux->foobar . "<br />";
    echo '$bar->foobar is ' . $bar->foobar . "<br />";
    echo '$bar == $qux';
    var_dump($bar == $qux); // true

    // 3. Instances with different attributes (only ==)
    //    What happens when objects have different attributes even though
    //    one of the attributes has same value?
    echo "3. Instances with different attributes (only ==) <br />";

    // Dynamically create a property with the name in $name and value
    // in $value for baz object
    $name = 'newproperty';
    $value = null;
    $baz->createNewProperty($name, $value);
    echo '$baz->newproperty is ' . $baz->{$name};
    var_dump($baz);

    $baz->foobar = 2;
    echo '$foobar' . " value is same again <br />";
    echo '$bar->foobar is ' . $bar->foobar . "<br />";
    echo '$baz->foobar is ' . $baz->foobar . "<br />";
    echo '$bar == $baz';
    var_dump($bar == $baz); // false
    var_dump($bar);
    var_dump($baz);
?>

How to call C++ function from C?

#include <iostream>

//////////////
// C++ code //
//////////////
struct A
{
  int i;
  int j;

  A() {i=1; j=2; std::cout << "class A created\n";}
  void dump() {std::cout << "class A dumped: " << i << ":" << j << std::endl;}
  ~A() {std::cout << "class A destroyed\n";}
};

extern "C" {
  // this is the C code interface to the class A
  static void *createA (void)
  {
    // create a handle to the A class
    return (void *)(new A);
  }
  static void dumpA (void *thisPtr)
  {
    // call A->dump ()
    if (thisPtr != NULL) // I'm an anal retentive programmer
    {
      A *classPtr = static_cast<A *>(thisPtr);
      classPtr->dump ();
    }
  }
  static void *deleteA (void *thisPtr)
  {
    // destroy the A class
    if (thisPtr != NULL)
    {
      delete (static_cast<A *>(thisPtr));
    }
  }
}

////////////////////////////////////
// this can be compiled as C code //
////////////////////////////////////
int main (int argc, char **argv)
{
  void *handle = createA();

  dumpA (handle);
  deleteA (handle);

  return 0;
}

Why can't decimal numbers be represented exactly in binary?

As we have been discussing, in floating point arithmetic, the decimal 0.1 cannot be perfectly represented in binary.

Floating point and integer representations provide grids or lattices for the numbers represented. As arithmetic is done, the results fall off the grid and have to be put back onto the grid by rounding. Example is 1/10 on a binary grid.

If we use binary coded decimal representation as one gentleman suggested, would we be able to keep numbers on the grid?

How to export a Hive table into a CSV file?

This is a much easier way to do it within Hive's SQL:

set hive.execution.engine=tez;
set hive.merge.tezfiles=true;
set hive.exec.compress.output=false;

INSERT OVERWRITE DIRECTORY '/tmp/job/'
ROW FORMAT DELIMITED
FIELDS TERMINATED by ','
NULL DEFINED AS ''
STORED AS TEXTFILE
SELECT * from table;

How can I enable auto complete support in Notepad++?

Autocomplete in Notepad++ is as simple as hitting Ctrl + Enter or Ctrl + Space in the interface.

Ctrl + Enter - as simple as that!

This, for many people, will be better than autocompleting on everything.

Java List.contains(Object with field value equal to x)

Binary Search

You can use Collections.binarySearch to search an element in your list (assuming the list is sorted):

Collections.binarySearch(list, new YourObject("a1", "b",
                "c"), new Comparator<YourObject>() {

            @Override
            public int compare(YourObject o1, YourObject o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });

which will return a negative number if the object is not present in the collection or else it will return the index of the object. With this you can search for objects with different searching strategies.

Turn off display errors using file "php.ini"

In php.ini, comment out:

error_reporting = E_ALL & ~E_NOTICE
error_reporting = E_ALL & ~E_NOTICE | E_STRICT
error_reporting = E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ER… _ERROR
error_reporting = E_ALL & ~E_NOTICE

By placing a ; ahead of it (i.e., like ;error_reporting = E_ALL & ~E_NOTICE)

For disabling in a single file, place error_reporting(0); after opening a php tag.

Difference between View and ViewGroup in Android

A View object is a component of the user interface (UI) like a button or a text box, and it's also called widget.

A ViewGroup object is a layout, that is, a container of other ViewGroup objects (layouts) and View objects (widgets). It's possible to have a layout inside another layout. It's called nested layout but it can increase the time needed to draw the user interface.

The user interface for an app is built using a hierarchy of ViewGroup and View objects. In Android Studio it is possible to use the Component Tree window to visualise this hierarchy.

The Layout Editor in Android Studio can be used to drag and drop View objects (widgets) in the layout. It simplifies the creation of a layout.

setAttribute('display','none') not working

display is not an attribute - it's a CSS property. You need to access the style object for this:

document.getElementById('classRight').style.display = 'none';

OR is not supported with CASE Statement in SQL Server

CASE
  WHEN ebv.db_no = 22978 OR 
       ebv.db_no = 23218 OR
       ebv.db_no = 23219
  THEN 'WECS 9500' 
  ELSE 'WECS 9520' 
END as wecs_system 

await is only valid in async function

I had the same problem and the following block of code was giving the same error message:

repositories.forEach( repo => {
        const commits = await getCommits(repo);
        displayCommit(commits);
});

The problem is that the method getCommits() was async but I was passing it the argument repo which was also produced by a Promise. So, I had to add the word async to it like this: async(repo) and it started working:

repositories.forEach( async(repo) => {
        const commits = await getCommits(repo);
        displayCommit(commits);
});

Filter spark DataFrame on string contains

You can use contains (this works with an arbitrary sequence):

df.filter($"foo".contains("bar"))

like (SQL like with SQL simple regular expression whith _ matching an arbitrary character and % matching an arbitrary sequence):

df.filter($"foo".like("bar"))

or rlike (like with Java regular expressions):

df.filter($"foo".rlike("bar"))

depending on your requirements. LIKE and RLIKE should work with SQL expressions as well.

Android ListView not refreshing after notifyDataSetChanged

Try this

@Override
public void onResume() {
super.onResume();
items.clear();
items = dbHelper.getItems(); //reload the items from database
adapter = new ItemAdapter(getActivity(), items);//reload the items from database
adapter.notifyDataSetChanged();
}

Java - get pixel array from image

Here is another FastRGB implementation found here:

public class FastRGB {
    public int width;
    public int height;
    private boolean hasAlphaChannel;
    private int pixelLength;
    private byte[] pixels;

    FastRGB(BufferedImage image) {
        pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
        width = image.getWidth();
        height = image.getHeight();
        hasAlphaChannel = image.getAlphaRaster() != null;
        pixelLength = 3;
        if (hasAlphaChannel)
            pixelLength = 4;
    }

    short[] getRGB(int x, int y) {
        int pos = (y * pixelLength * width) + (x * pixelLength);
        short rgb[] = new short[4];
        if (hasAlphaChannel)
            rgb[3] = (short) (pixels[pos++] & 0xFF); // Alpha
        rgb[2] = (short) (pixels[pos++] & 0xFF); // Blue
        rgb[1] = (short) (pixels[pos++] & 0xFF); // Green
        rgb[0] = (short) (pixels[pos++] & 0xFF); // Red
        return rgb;
    }
}

What is this?

Reading an image pixel by pixel through BufferedImage's getRGB method is quite slow, this class is the solution for this.

The idea is that you construct the object by feeding it a BufferedImage instance, and it reads all the data at once and stores them in an array. Once you want to get pixels, you call getRGB

Dependencies

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;

Considerations

Although FastRGB makes reading pixels much faster, it could lead to high memory usage, as it simply stores a copy of the image. So if you have a 4MB BufferedImage in the memory, once you create the FastRGB instance, the memory usage would become 8MB. You can however, recycle the BufferedImage instance after you create the FastRGB.

Be careful to not fall into OutOfMemoryException when using it on devices such as Android phones, where RAM is a bottleneck

Javascript - Get Image height

I was searching a solution to get height and width of an image using JavaScript. I found many, but all those solutions only worked when the image was present in browser cache.

Finally I found a solution to get the image height and width even if the image does not exist in the browser cache:

<script type="text/javascript">

  var imgHeight;
  var imgWidth;

  function findHHandWW() {
    imgHeight = this.height;
    imgWidth = this.width;
    return true;
  }

  function showImage(imgPath) {
    var myImage = new Image();
    myImage.name = imgPath;
    myImage.onload = findHHandWW;
    myImage.src = imgPath;
  }
</script>

Thanks,

Binod Suman

http://binodsuman.blogspot.com/2009/06/how-to-get-height-and-widht-of-image.html

automating telnet session using bash scripts

Telnet is often used when you learn HTTP protocol. I used to use that script as a part of my web-scraper:

echo "open www.example.com 80" 
sleep 2 
echo "GET /index.html HTTP/1.1" 
echo "Host: www.example.com" 
echo 
echo 
sleep 2

let's say the name of the script is get-page.sh then:

get-page.sh | telnet

will give you a html document.

Hope it will be helpful to someone ;)

Load and execution sequence of a web page?

1) HTML is downloaded.

2) HTML is parsed progressively. When a request for an asset is reached the browser will attempt to download the asset. A default configuration for most HTTP servers and most browsers is to process only two requests in parallel. IE can be reconfigured to downloaded an unlimited number of assets in parallel. Steve Souders has been able to download over 100 requests in parallel on IE. The exception is that script requests block parallel asset requests in IE. This is why it is highly suggested to put all JavaScript in external JavaScript files and put the request just prior to the closing body tag in the HTML.

3) Once the HTML is parsed the DOM is rendered. CSS is rendered in parallel to the rendering of the DOM in nearly all user agents. As a result it is strongly recommended to put all CSS code into external CSS files that are requested as high as possible in the <head></head> section of the document. Otherwise the page is rendered up to the occurance of the CSS request position in the DOM and then rendering starts over from the top.

4) Only after the DOM is completely rendered and requests for all assets in the page are either resolved or time out does JavaScript execute from the onload event. IE7, and I am not sure about IE8, does not time out assets quickly if an HTTP response is not received from the asset request. This means an asset requested by JavaScript inline to the page, that is JavaScript written into HTML tags that is not contained in a function, can prevent the execution of the onload event for hours. This problem can be triggered if such inline code exists in the page and fails to execute due to a namespace collision that causes a code crash.

Of the above steps the one that is most CPU intensive is the parsing of the DOM/CSS. If you want your page to be processed faster then write efficient CSS by eliminating redundent instructions and consolidating CSS instructions into the fewest possible element referrences. Reducing the number of nodes in your DOM tree will also produce faster rendering.

Keep in mind that each asset you request from your HTML or even from your CSS/JavaScript assets is requested with a separate HTTP header. This consumes bandwidth and requires processing per request. If you want to make your page load as fast as possible then reduce the number of HTTP requests and reduce the size of your HTML. You are not doing your user experience any favors by averaging page weight at 180k from HTML alone. Many developers subscribe to some fallacy that a user makes up their mind about the quality of content on the page in 6 nanoseconds and then purges the DNS query from his server and burns his computer if displeased, so instead they provide the most beautiful possible page at 250k of HTML. Keep your HTML short and sweet so that a user can load your pages faster. Nothing improves the user experience like a fast and responsive web page.

How can I tell where mongoDB is storing data? (its not in the default /data/db!)

From my experience the default location is /var/lib/mongodb after I do

sudo apt-get install -y mongodb-org

Increasing the maximum post size

Try

LimitRequestBody 1024000000

MVC ajax json post to controller action method

Below is how I got this working.

The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.

[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]

[HttpPost]  
  public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)  
  {            
     var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
     return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
  }

The JQuery script used to call this action method:

var requestData = {
         InvoiceNumber: $.trim(this.value),
         SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
      };


      $.ajax({
         url: '/en/myController/GetDataForInvoiceNumber',
         type: 'POST',
         data: JSON.stringify(requestData),
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         error: function (xhr) {
            alert('Error: ' + xhr.statusText);
         },
         success: function (result) {
            CheckIfInvoiceFound(result);
         },
         async: true,
         processData: false
      });

Google Play Services Missing in Emulator (Android 4.4.2)

If you're using Xamarin, I found a guide on their official forum explaining how to do this:

  1. Download the package from the internet. There are many sources for this, one possible source is the CyanogenMod web site.
  2. Start up the Android Player and unlock it.
  3. Drag and drop the zip file that you downloaded onto the Android Player.
  4. Restart the Android Player.

Hereafter, you might also need to update the Google Play Services from the Google Play Store.

Hope this helps for anyone else who has troubles finding the documentation.

Send multipart/form-data files with angular using $http

In Angular 6, you can do this:

In your service file:

 function_name(data) {
    const url = `the_URL`;
    let input = new FormData();
    input.append('url', data);   // "url" as the key and "data" as value
    return this.http.post(url, input).pipe(map((resp: any) => resp));
  }

In component.ts file: in any function say xyz,

xyz(){
this.Your_service_alias.function_name(data).subscribe(d => {   // "data" can be your file or image in base64 or other encoding
      console.log(d);
    });
}

Using an array from Observable Object with ngFor and Async Pipe Angular 2

Here's an example

// in the service
getVehicles(){
    return Observable.interval(2200).map(i=> [{name: 'car 1'},{name: 'car 2'}])
}

// in the controller
vehicles: Observable<Array<any>>
ngOnInit() {
    this.vehicles = this._vehicleService.getVehicles();
}

// in template
<div *ngFor='let vehicle of vehicles | async'>
    {{vehicle.name}}
</div>

Order by in Inner Join

Avoid SELECT * in your main query.

Avoid duplicate columns: the JOIN condition ensures One.One_Name and two.One_Name will be equal therefore you don't need to return both in the SELECT clause.

Avoid duplicate column names: rename One.ID and Two.ID using 'aliases'.

Add an ORDER BY clause using the column names ('alises' where applicable) from the SELECT clause.

Suggested re-write:

SELECT T1.ID AS One_ID, T1.One_Name, 
       T2.ID AS Two_ID, T2.Two_name
  FROM One AS T1
       INNER JOIN two AS T2
          ON T1.One_Name = T2.One_Name
 ORDER 
    BY One_ID;

What is the difference between Double.parseDouble(String) and Double.valueOf(String)?

They both convert a String to a double value but wherease the parseDouble() method returns the primitive double value, the valueOf() method further converts the primitive double to a Double wrapper class object which contains the primitive double value.

The conversion from String to primitive double may throw NFE(NumberFormatException) if the value in String is not convertible into a primitive double.

Standard deviation of a list

Using python, here are few methods:

import statistics as st

n = int(input())
data = list(map(int, input().split()))

Approach1 - using a function

stdev = st.pstdev(data)

Approach2: calculate variance and take square root of it

variance = st.pvariance(data)
devia = math.sqrt(variance)

Approach3: using basic math

mean = sum(data)/n
variance = sum([((x - mean) ** 2) for x in X]) / n
stddev = variance ** 0.5

print("{0:0.1f}".format(stddev))

Note:

  • variance calculates variance of sample population
  • pvariance calculates variance of entire population
  • similar differences between stdev and pstdev

Fastest JSON reader/writer for C++

rapidjson is a C++ JSON parser/generator designed to be fast and small memory footprint.

There is a performance comparison with YAJL and JsonCPP.


Update:

I created an open source project Native JSON benchmark, which evaluates 29 (and increasing) C/C++ JSON libraries, in terms of conformance and performance. This should be an useful reference.

Setting the JVM via the command line on Windows

yes I often need to have 3 or more JVM's installed. For example, I've noticed that sometimes the JRE is slightly different to the JDK version of the JRE.

My go to solution on Windows for a bit of 'packaging' is something like this:

@echo off
setlocal
@rem  _________________________
@rem
@set  JAVA_HOME=b:\lang\java\jdk\v1.6\u45\x64\jre
@rem
@set  JAVA_EXE=%JAVA_HOME%\bin\java
@set  VER=test
@set  WRK=%~d0%~p0%VER%
@rem
@pushd %WRK%
cd 
@echo.
@echo  %JAVA_EXE%  -jar %WRK%\openmrs-standalone.jar
       %JAVA_EXE%  -jar %WRK%\openmrs-standalone.jar 
@rem
@rem  _________________________
popd
endlocal
@exit /b

I think it is straightforward. The main thing is the setlocal and endlocal give your app a "personal environment" for what ever it does -- even if there's other programs to run.

Oracle date format picture ends before converting entire input string

Perhaps you should check NLS_DATE_FORMAT and use the date string conforming the format. Or you can use to_date function within the INSERT statement, like the following:

insert into visit
values(123456, 
       to_date('19-JUN-13', 'dd-mon-yy'),
       to_date('13-AUG-13 12:56 A.M.', 'dd-mon-yyyy hh:mi A.M.'));

Additionally, Oracle DATE stores date and time information together.

1 = false and 0 = true?

There's no good reason for 1 to be true and 0 to be false; that's just the way things have always been notated. So from a logical perspective, the function in your API isn't "wrong", per se.

That said, it's normally not advisable to work against the idioms of whatever language or framework you're using without a damn good reason to do so, so whoever wrote this function was probably pretty bone-headed, assuming it's not simply a bug.

Maximum Length of Command Line String

From the Microsoft documentation: Command prompt (Cmd. exe) command-line string limitation

On computers running Microsoft Windows XP or later, the maximum length of the string that you can use at the command prompt is 8191 characters.

Open Source Javascript PDF viewer

There is an open source HTML5/javascript reader available called Trapeze though its still in its early stages.

Demo site: https://brendandahl.github.io/trapeze-reader/demos/

Github page: https://github.com/brendandahl/trapeze-reader

Disclaimer: I'm the author.

Virtual Memory Usage from Java under Linux, too much memory used

The Sun JVM requires a lot of memory for HotSpot and it maps in the runtime libraries in shared memory.

If memory is an issue consider using another JVM suitable for embedding. IBM has j9, and there is the Open Source "jamvm" which uses GNU classpath libraries. Also Sun has the Squeak JVM running on the SunSPOTS so there are alternatives.

How to import module when module name has a '-' dash or hyphen in it?

you can't. foo-bar is not an identifier. rename the file to foo_bar.py

Edit: If import is not your goal (as in: you don't care what happens with sys.modules, you don't need it to import itself), just getting all of the file's globals into your own scope, you can use execfile

# contents of foo-bar.py
baz = 'quux'
>>> execfile('foo-bar.py')
>>> baz
'quux'
>>> 

How do I install PyCrypto on Windows?

If you are on Windows and struggling with installing Pycrypcto just use the: pip install pycryptodome. It works like a miracle and it will make your life much easier than trying to do a lot of configurations and tweaks.

Set a button background image iPhone programmatically

Complete code:

+ (UIButton *)buttonWithTitle:(NSString *)title
                       target:(id)target
                     selector:(SEL)selector
                        frame:(CGRect)frame
                        image:(UIImage *)image
                 imagePressed:(UIImage *)imagePressed
                darkTextColor:(BOOL)darkTextColor
{
    UIButton *button = [[UIButton alloc] initWithFrame:frame];

    button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];


    UIImage *newImage = [image stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
    [button setBackgroundImage:newImage forState:UIControlStateNormal];

    UIImage *newPressedImage = [imagePressed stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
    [button setBackgroundImage:newPressedImage forState:UIControlStateHighlighted];

    [button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];

    // in case the parent view draws with a custom color or gradient, use a transparent color
    button.backgroundColor = [UIColor clearColor];

    return button;
}

UIImage *buttonBackground = UIImage imageNamed:@"whiteButton.png";
UIImage *buttonBackgroundPressed = UIImage imageNamed:@"blueButton.png";

CGRect frame = CGRectMake(0.0, 0.0, kStdButtonWidth, kStdButtonHeight);

UIButton *button = [FinishedStatsView buttonWithTitle:title
                                               target:target
                                             selector:action
                                                frame:frame
                                                image:buttonBackground
                                         imagePressed:buttonBackgroundPressed
                                        darkTextColor:YES];

[self addSubview:button]; 

To set an image:

UIImage *buttonImage = [UIImage imageNamed:@"Home.png"];
[myButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:myButton];

To remove an image:

[button setBackgroundImage:nil forState:UIControlStateNormal];

How can I enable Assembly binding logging?

Just create a new DWORD(32) under the Fusion key. Name the DWORD to EnableLog, and set it to value 1. Then restart IIS, refresh the page giving errors, and the assembly bind logs will show in the error message.

jQuery see if any or no checkboxes are selected

This is what I used for checking if any checkboxes in a list of checkboxes had changed:

$('input[type="checkbox"]').change(function(){ 

        var itemName = $('select option:selected').text();  

         //Do something.

});     

HTTP response header content disposition for attachments

neither use inline; nor attachment; just use

response.setContentType("text/xml");
response.setHeader( "Content-Disposition", "filename=" + filename );

or

response.setHeader( "Content-Disposition", "filename=\"" + filename + "\"" );

or

response.setHeader( "Content-Disposition", "filename=\"" + 
  filename.substring(0, filename.lastIndexOf('.')) + "\"");

How to terminate a thread when main program ends?

If you make your worker threads daemon threads, they will die when all your non-daemon threads (e.g. the main thread) have exited.

http://docs.python.org/library/threading.html#threading.Thread.daemon

AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?

The issue is that you have to set the ng-model to the parent element to where you want to set the ng-value/value . As mentioned by Angular:

It is mainly used on input[radio] and option elements, so that when the element is selected, the ngModel of that element (or its select parent element) is set to the bound value.

Eg:This is an executed code :

<div class="col-xs-12 select-checkbox" >
<label style="width: 18em;" ng-model="vm.settingsObj.MarketPeers">
  <input name="radioClick" type="radio"  ng-click="vm.setPeerGrp('market');" 
         ng-value="vm.settingsObj.MarketPeers" 
         style="position:absolute;margin-left: 9px;">
  <div style="margin-left: 35px;color: #717171e8;border-bottom: 0.5px solid #e2e2e2;padding-bottom: 2%;">Hello World</div>
</label>
</div>

Note: In this above case I alreday had the JSON response to the ng-model and the value, I am just adding another property to the JS object as "MarketPeers". So the model and value may depend according to the need, but I think this process will help, to have both ng-model and value but not having them on the same element.

Generate random int value from 3 to 6

In general:

select rand()*(@upper-@lower)+@lower;

For your question:

select rand()*(6-3)+3;

<=>

select rand()*3+3;

Check if cookies are enabled

Cookies are Client-side and cannot be tested properly using PHP. That's the baseline and every solution is a wrap-around for this problem.

Meaning if you are looking a solution for your cookie problem, you are on the wrong way. Don'y use PHP, use a client language like Javascript.

Can you use cookies using PHP? Yes, but you have to reload to make the settings to PHP 'visible'.

For instance: Is a test possible to see if the browser can set Cookies with plain PHP'. The only correct answer is 'NO'.

Can you read an already set Cookie: 'YES' use the predefined $_COOKIE (A copy of the settings before you started PHP-App).

Stopping a CSS3 Animation on last frame

Nobody actualy brought it so, the way it was made to work is animation-play-state set to paused.

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

import re
pattern = re.compile("<(\d{4,5})>")

for i, line in enumerate(open('test.txt')):
    for match in re.finditer(pattern, line):
        print 'Found on line %s: %s' % (i+1, match.group())

A couple of notes about the regex:

  • You don't need the ? at the end and the outer (...) if you don't want to match the number with the angle brackets, but only want the number itself
  • It matches either 4 or 5 digits between the angle brackets

Update: It's important to understand that the match and capture in a regex can be quite different. The regex in my snippet above matches the pattern with angle brackets, but I ask to capture only the internal number, without the angle brackets.

More about regex in python can be found here : Regular Expression HOWTO

Calling functions in a DLL from C++

There are many ways to do this but I think one of the easiest options is to link the application to the DLL at link time and then use a definition file to define the symbols to be exported from the DLL.

CAVEAT: The definition file approach works bests for undecorated symbol names. If you want to export decorated symbols then it is probably better to NOT USE the definition file approach.

Here is an simple example on how this is done.

Step 1: Define the function in the export.h file.

int WINAPI IsolatedFunction(const char *title, const char *test);

Step 2: Define the function in the export.cpp file.

#include <windows.h>

int WINAPI IsolatedFunction(const char *title, const char *test)
{
    MessageBox(0, title, test, MB_OK);
    return 1;
}

Step 3: Define the function as an export in the export.def defintion file.

EXPORTS    IsolatedFunction          @1

Step 4: Create a DLL project and add the export.cpp and export.def files to this project. Building this project will create an export.dll and an export.lib file.

The following two steps link to the DLL at link time. If you don't want to define the entry points at link time, ignore the next two steps and use the LoadLibrary and GetProcAddress to load the function entry point at runtime.

Step 5: Create a Test application project to use the dll by adding the export.lib file to the project. Copy the export.dll file to ths same location as the Test console executable.

Step 6: Call the IsolatedFunction function from within the Test application as shown below.

#include "stdafx.h"

// get the function prototype of the imported function
#include "../export/export.h"

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
    // call the imported function found in the dll
    int result = IsolatedFunction("hello", "world");

    return 0;
}

How to convert a boolean array to an int array

Using numpy, you can do:

y = x.astype(int)

If you were using a non-numpy array, you could use a list comprehension:

y = [int(val) for val in x]

Getting Index of an item in an arraylist;

.indexOf() works well. If you want an example here is one:

  ArrayList<String> example = new ArrayList<String>();
  example.add("AB");
  example.add("CD");
  example.add("EF");
  example.add("GH");
  example.add("IJ");
  example.add("KL");
  example.add("MN");

  System.out.println("Index of 'AB': "+example.indexOf("AB"));
  System.out.println("Index of 'KL': "+example.indexOf("KL"));
  System.out.println("Index of 'AA': "+example.indexOf("AA"));
  System.out.println("Index of 'EF': "+example.indexOf("EF"));

will give you an output of

Index of 'AB': 0
Index of 'KL': 5
Index of 'AA': -1
Index of 'EF': 2

Note: This method returns -1 if the specified element is not present in the list.

How do I add a newline using printf?

To write a newline use \n not /n the latter is just a slash and a n

fatal: early EOF fatal: index-pack failed

In my case this was quite helpful:

git clone --depth 1 --branch $BRANCH $URL

This will limit the checkout to mentioned branch only, hence will speed up the process.

Hope this will help.

How do I display images from Google Drive on a website?

I don't know of a better way but you can datamine the page with php. For instance if you go to google and share a folder then go to that folder it will look something like

https://drive.google.com/folderview?id=0B8TT0olkjsdkfji9jekbFF4LWc&usp=sharing

^^^ not a real link

What you are looking for is the individual images inside the source code of this page

then using php get the source code with

<? $f = fopen ("http://www.example.com/f", r);
echo $f;
?>

now $f has the source and you can use other php commands to seperate only the URLS with the images you want. It will take a bit of work but highly doable.

once you have these image links showing the way you want just build them into a div or table structure to display on a gallery maybe even add a greybox element for effect

Access index of last element in data frame

Pandas supports NumPy syntax which allows:

df[len(df) -1:].index[0]

Dump a mysql database to a plaintext (CSV) backup from the command line

Two line PowerShell answer:

# Store in variable
$Global:csv = (mysql -uroot -p -hlocalhost -Ddatabase_name -B -e "SELECT * FROM some_table") `
| ConvertFrom-Csv -Delimiter "`t"

# Out to csv
$Global:csv | Export-Csv "C:\temp\file.csv" -NoTypeInformation

Boom-bata-boom

-D = the name of your database

-e = query

-B = tab-delimited

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

There's a library for conversion:

npm install dateformat

Then write your requirement:

var dateFormat = require('dateformat');

Then bind the value:

var day=dateFormat(new Date(), "yyyy-mm-dd h:MM:ss");

see dateformat

How can I check what version/edition of Visual Studio is installed programmatically?

All the information in this thread is now out of date with the recent release of vswhere. Download that and use it.

How to capture no file for fs.readFileSync()?

You have to catch the error and then check what type of error it is.

try {
  var data = fs.readFileSync(...)
} catch (err) {
  // If the type is not what you want, then just throw the error again.
  if (err.code !== 'ENOENT') throw err;

  // Handle a file-not-found error
}

How do I append to a table in Lua

foo = {}
foo[#foo+1]="bar"
foo[#foo+1]="baz"

This works because the # operator computes the length of the list. The empty list has length 0, etc.

If you're using Lua 5.3+, then you can do almost exactly what you wanted:

foo = {}
setmetatable(foo, { __shl = function (t,v) t[#t+1]=v end })
_= foo << "bar"
_= foo << "baz"

Expressions are not statements in Lua and they need to be used somehow.

MySQL - UPDATE query based on SELECT Query

You can actually do this one of two ways:

MySQL update join syntax:

UPDATE tableA a
INNER JOIN tableB b ON a.name_a = b.name_b
SET validation_check = if(start_dts > end_dts, 'VALID', '')
-- where clause can go here

ANSI SQL syntax:

UPDATE tableA SET validation_check = 
    (SELECT if(start_DTS > end_DTS, 'VALID', '') AS validation_check
        FROM tableA
        INNER JOIN tableB ON name_A = name_B
        WHERE id_A = tableA.id_A)

Pick whichever one seems most natural to you.

How to get file creation & modification date/times in Python?

It may worth taking a look at the crtime library which implements cross-platform access to the file creation time.

from crtime import get_crtimes_in_dir

for fname, date in get_crtimes_in_dir(".", raise_on_error=True, as_epoch=False):
    print(fname, date)
    # file_a.py Mon Mar 18 20:51:18 CET 2019

How can I generate a unique ID in Python?

unique and random are mutually exclusive. perhaps you want this?

import random
def uniqueid():
    seed = random.getrandbits(32)
    while True:
       yield seed
       seed += 1

Usage:

unique_sequence = uniqueid()
id1 = next(unique_sequence)
id2 = next(unique_sequence)
id3 = next(unique_sequence)
ids = list(itertools.islice(unique_sequence, 1000))

no two returned id is the same (Unique) and this is based on a randomized seed value

Resize HTML5 canvas to fit window

CSS

body { margin: 0; } 
canvas { display: block; } 

JavaScript

window.addEventListener("load", function()
{
    var canvas = document.createElement('canvas'); document.body.appendChild(canvas);
    var context = canvas.getContext('2d');

    function draw()
    {
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.beginPath();
        context.moveTo(0, 0); context.lineTo(canvas.width, canvas.height); 
        context.moveTo(canvas.width, 0); context.lineTo(0, canvas.height); 
        context.stroke();
    }
    function resize()
    {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        draw();
    }
    window.addEventListener("resize", resize);
    resize();
});

Android: findviewbyid: finding view by id when view is not on the same layout invoked by setContentView

It's impossible. You can only find and access views that are currently running. If you want to check the value of ex. TextView used in previus activity you must save the value is SharedPreferences, database, file or pass by Intent.

Simple way to encode a string according to a password?

So, as nothing mission critical is being encoded, and you just want to encrypt for obsfuscation.

Let me present caeser's cipher

enter image description here

Caesar's cipher or Caesar shift, is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on.

Sample code for your reference :

def encrypt(text,s): 
        result = "" 

        # traverse text 
        for i in range(len(text)): 
            char = text[i] 

            # Encrypt uppercase characters 
            if (char.isupper()): 
                result += chr((ord(char) + s-65) % 26 + 65) 

            # Encrypt lowercase characters 
            else: 
                result += chr((ord(char) + s - 97) % 26 + 97) 

        return result 

    def decrypt(text,s): 
        result = "" 

        # traverse text 
        for i in range(len(text)): 
            char = text[i] 

            # Encrypt uppercase characters 
            if (char.isupper()): 
                result += chr((ord(char) - s-65) % 26 + 65) 

            # Encrypt lowercase characters 
            else: 
                result += chr((ord(char) - s - 97) % 26 + 97) 

        return result 

    #check the above function 
    text = "ATTACKATONCE"
    s = 4
    print("Text  : " + text) 
    print("Shift : " + str(s)) 
    print("Cipher: " + encrypt(text,s))
    print("Original text: " + decrypt(encrypt(text,s),s))

Advantages : it meets your requirements and is simple and does the encoding thing'y'.

Disadvantage : can be cracked by simple brute force algorithms (highly unlikely anyone would attempt to go through all extra results).

Can I assume (bool)true == (int)1 for any C++ compiler?

According to the standard, you should be safe with that assumption. The C++ bool type has two values - true and false with corresponding values 1 and 0.

The thing to watch about for is mixing bool expressions and variables with BOOL expression and variables. The latter is defined as FALSE = 0 and TRUE != FALSE, which quite often in practice means that any value different from 0 is considered TRUE.

A lot of modern compilers will actually issue a warning for any code that implicitly tries to cast from BOOL to bool if the BOOL value is different than 0 or 1.

IOS: verify if a point is inside a rect

Swift 4

let view = ...
let point = ...
view.bounds.contains(point)

Objective-C

Use CGRectContainsPoint():

bool CGRectContainsPoint(CGRect rect, CGPoint point);

Parameters

  • rect The rectangle to examine.
  • point The point to examine. Return Value true if the rectangle is not null or empty and the point is located within the rectangle; otherwise, false.

A point is considered inside the rectangle if its coordinates lie inside the rectangle or on the minimum X or minimum Y edge.

Lock down Microsoft Excel macro

Generate a protected application for Mac or Windows from your Excel spreadsheet using OfficeProtect with either AppProtect or QuickLicense/AddLicense. There is a demonstation video called "Protect Excel Spreedsheet" at www.excelsoftware.com/videos.

What is the opposite of evt.preventDefault();

I have used the following code. It works fine for me.

$('a').bind('click', function(e) {
  e.stopPropagation();
});

PHP 7 RC3: How to install missing MySQL PDO

Since eggyal didn't provided his comment as answer after he gave right advice in a comment - i am posting it here: In my case I had to install module php-mysql. See comments under the question for details.

How to loop over grouped Pandas dataframe?

You can iterate over the index values if your dataframe has already been created.

df = df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))
for name in df.index:
    print name
    print df.loc[name]

<SELECT multiple> - how to allow only one item selected?

Late to answer but might help someone else, here is how to do it without removing the 'multiple' attribute.

$('.myDropdown').chosen({
    //Here you can change the value of the maximum allowed options
    max_selected_options: 1
});

Unable to connect PostgreSQL to remote database using pgAdmin

In linux terminal try this:

  • sudo service postgresql start : to start the server
  • sudo service postgresql stop : to stop thee server
  • sudo service postgresql status : to check server status

EXCEL VBA, inserting blank row and shifting cells

Sub Addrisk()

Dim rActive As Range
Dim Count_Id_Column as long

Set rActive = ActiveCell

Application.ScreenUpdating = False

with thisworkbook.sheets(1) 'change to "sheetname" or sheetindex
    for i = 1 to .range("A1045783").end(xlup).row
        if 'something'  = 'something' then
            .range("A" & i).EntireRow.Copy 'add thisworkbook.sheets(index_of_sheet) if you copy from another sheet
            .range("A" & i).entirerow.insert shift:= xldown 'insert and shift down, can also use xlup
            .range("A" & i + 1).EntireRow.paste 'paste is all, all other defs are less.
            'change I to move on to next row (will get + 1 end of iteration)
            i = i + 1
        end if

            On Error Resume Next
                .SpecialCells(xlCellTypeConstants).ClearContents
            On Error GoTo 0

        End With
    next i
End With

Application.CutCopyMode = False
Application.ScreenUpdating = True 're-enable screen updates

End Sub

How to restart remote MySQL server running on Ubuntu linux?

  • To restart mysql use this command

sudo service mysql restart

Or

sudo restart mysql

Reference

Do I commit the package-lock.json file created by npm 5?

Yes, the best practice is to check-in (YES, CHECK-IN)

I agree that it will cause a lot of noise or conflict when seeing the diff. But the benefits are:

  1. guarantee exact same version of every package. This part is the most important when building in different environments at different times. You may use ^1.2.3 in your package.json, but how can u ensure each time npm install will pick up the same version in your dev machine and in the build server, especially those indirect dependency packages? Well, package-lock.json will ensure that. (With the help of npm ci which installs packages based on lock file)
  2. it improves the installation process.
  3. it helps with new audit feature npm audit fix (I think the audit feature is from npm version 6).

Decreasing for loops in Python impossible?

This is very late, but I just wanted to add that there is a more elegant way: using reversed

for i in reversed(range(10)):
    print i

gives:

4
3
2
1
0

Use <Image> with a local file

It works exactly as you expect it to work. There's a bug https://github.com/facebook/react-native/issues/282 that prevents it from working correctly.

If you have node_modules (with react_native) in the same folder as the xcode project, you can edit node_modules/react-native/packager/packager.js and make this change: https://github.com/facebook/react-native/pull/286/files . It'll work magically :)

If your react_native is installed somewhere else and the patch doesn't work, comment on https://github.com/facebook/react-native/issues/282 to let them know about your setup.

Cannot drop database because it is currently in use

Just wanted to give a vb.net (as with c language if want to convert..) I was having similar problem for uninstal of one of my programs, dropping the DB was bit tricky, yes could get users to go into server drop it using Express, but thats not clean, after few looks around got a perfect little bit of code together...

    Sub DropMyDatabase()
    Dim Your_DB_To_Drop_Name As String = "YourDB"
    Dim Your_Connection_String_Here As String = "SERVER=MyServer;Integrated Security=True"
    Dim Conn As SqlConnection = New SqlConnection(Your_Connection_String_Here)

    Dim AlterStr As String = "ALTER DATABASE " & Your_DB_To_Drop_Name & " SET OFFLINE WITH ROLLBACK IMMEDIATE"
    Dim AlterCmd = New SqlCommand(AlterStr, Conn)

    Dim DropStr As String = "DROP DATABASE " & Your_DB_To_Drop_Name
    Dim DropCmd = New SqlCommand(DropStr, Conn)

    Try
        Conn.Open()
        AlterCmd.ExecuteNonQuery()
        DropCmd.ExecuteNonQuery()
        Conn.Close()

    Catch ex As Exception
        If (Conn.State = ConnectionState.Open) Then
            Conn.Close()
        End If
        MsgBox("Failed... Sorry!" & vbCrLf & vbCrLf & ex.Message)
    End Try
End Sub

Hope this helps anyone looking xChickenx

UPDATE Using this converter here is the C# version :

public void DropMyDatabase()
    {
        var Your_DB_To_Drop_Name = "YourDB";
        var Your_Connection_String_Here = "SERVER=MyServer;Integrated Security=True";
        var Conn = new SqlConnection(Your_Connection_String_Here);

        var AlterStr = "ALTER DATABASE " + Your_DB_To_Drop_Name + " SET OFFLINE WITH ROLLBACK IMMEDIATE";
        var AlterCmd = new SqlCommand(AlterStr, Conn);

        var DropStr = "DROP DATABASE " + Your_DB_To_Drop_Name;
        var DropCmd = new SqlCommand(DropStr, Conn);

        try
        {
            Conn.Open();
            AlterCmd.ExecuteNonQuery();
            DropCmd.ExecuteNonQuery();
            Conn.Close();

        }
        catch(Exception ex)
        {
            if((Conn.State == ConnectionState.Open))
            {
                Conn.Close();
            }
            Trace.WriteLine("Failed... Sorry!" + Environment.NewLine + ex.Message);
        }
    }

bower automatically update bower.json

from bower help, save option has a capital S

-S, --save  Save installed packages into the project's bower.json dependencies

Redirecting to a relative URL in JavaScript

You can do a relative redirect:

window.location.href = '../'; //one level up

or

window.location.href = '/path'; //relative to domain

How to insert text in a td with id, using JavaScript

append a text node as follows

var td1 = document.getElementById('td1');
var text = document.createTextNode("some text");
td1.appendChild(text);

How to parse unix timestamp to time.Time

You can directly use time.Unix function of time which converts the unix time stamp to UTC

package main

import (
  "fmt"
  "time"
)


func main() {
    unixTimeUTC:=time.Unix(1405544146, 0) //gives unix time stamp in utc 

    unitTimeInRFC3339 :=unixTimeUTC.Format(time.RFC3339) // converts utc time to RFC3339 format

    fmt.Println("unix time stamp in UTC :--->",unixTimeUTC)
    fmt.Println("unix time stamp in unitTimeInRFC3339 format :->",unitTimeInRFC3339)
}

Output

unix time stamp in UTC :---> 2014-07-16 20:55:46 +0000 UTC
unix time stamp in unitTimeInRFC3339 format :----> 2014-07-16T20:55:46Z

Check in Go Playground: https://play.golang.org/p/5FtRdnkxAd

Please add a @Pipe/@Directive/@Component annotation. Error

You get this error when you wrongly add shared service to "declaration" in your appmodules instead of adding it to "provider".

Android Studio: Unable to start the daemon process

Sometimes You just open too much applications in Windows and make the gradle have no enough memory to start the daemon process.So when you come across with this situation,you can just close some applications such as Chrome and so on. Then restart your android studio.

Create stacked barplot where each stack is scaled to sum to 100%

You just need to divide each element by the sum of the values in its column.

Doing this should suffice:

data.perc <- apply(data, 2, function(x){x/sum(x)})

Note that the second parameter tells apply to apply the provided function to columns (using 1 you would apply it to rows). The anonymous function, then, gets passed each data column, one at a time.

Creating a system overlay window (always on top)

by using service you can achieve this :

public class PopupService extends Service{

    private static final String TAG = PopupService.class.getSimpleName();
    WindowManager mWindowManager;
    View mView;
    String type ;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
//        registerOverlayReceiver();
        type = intent.getStringExtra("type");
        Utils.printLog("type = "+type);
        showDialog(intent.getStringExtra("msg"));
        return super.onStartCommand(intent, flags, startId);
    }

    private void showDialog(String aTitle)
    {
        if(type.equals("when screen is off") | type.equals("always"))
        {
            Utils.printLog("type = "+type);
            PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
            WakeLock mWakeLock = pm.newWakeLock((PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "YourServie");
            mWakeLock.acquire();
            mWakeLock.release();
        }

        mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        mView = View.inflate(getApplicationContext(), R.layout.dialog_popup_notification_received, null);
        mView.setTag(TAG);

        int top = getApplicationContext().getResources().getDisplayMetrics().heightPixels / 2;

        LinearLayout dialog = (LinearLayout) mView.findViewById(R.id.pop_exit);
//        android.widget.LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) dialog.getLayoutParams();
//        lp.topMargin = top;
//        lp.bottomMargin = top;
//        mView.setLayoutParams(lp);

        final EditText etMassage = (EditText) mView.findViewById(R.id.editTextInPopupMessageReceived);

        ImageButton imageButtonSend = (ImageButton) mView.findViewById(R.id.imageButtonSendInPopupMessageReceived);
//        lp = (LayoutParams) imageButton.getLayoutParams();
//        lp.topMargin = top - 58;
//        imageButton.setLayoutParams(lp);
        imageButtonSend.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.printLog("clicked");
//                mView.setVisibility(View.INVISIBLE);
                if(!etMassage.getText().toString().equals(""))
                {
                    Utils.printLog("sent");
                    etMassage.setText("");
                }
            }
        });

        TextView close = (TextView) mView.findViewById(R.id.TextViewCloseInPopupMessageReceived);
        close.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                hideDialog();   
            }
        });

        TextView view = (TextView) mView.findViewById(R.id.textviewViewInPopupMessageReceived);
        view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                hideDialog();   
            }
        });

        TextView message = (TextView) mView.findViewById(R.id.TextViewMessageInPopupMessageReceived);
        message.setText(aTitle);

        final WindowManager.LayoutParams mLayoutParams = new WindowManager.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.MATCH_PARENT, 0, 0,
        WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
        WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
//                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON ,
        PixelFormat.RGBA_8888);

        mView.setVisibility(View.VISIBLE);
        mWindowManager.addView(mView, mLayoutParams);
        mWindowManager.updateViewLayout(mView, mLayoutParams);

    }

    private void hideDialog(){
        if(mView != null && mWindowManager != null){
            mWindowManager.removeView(mView);
            mView = null;
        }
    }
}

Div vertical scrollbar show

Have you tried overflow-y:auto ? It is not exactly what you want, as the scrollbar will appear only when needed.

How do I create a Java string from the contents of a file?

I cannot comment other entries yet, so I'll just leave it here.

One of best answers here (https://stackoverflow.com/a/326448/1521167):

private String readFile(String pathname) throws IOException {

File file = new File(pathname);
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner = new Scanner(file);
String lineSeparator = System.getProperty("line.separator");

try {
    while(scanner.hasNextLine()) {        
        fileContents.append(scanner.nextLine() + lineSeparator);
    }
    return fileContents.toString();
} finally {
    scanner.close();
}
}

still has one flaw. It always puts new line char in the end of string, which may cause some weirds bugs. My suggestion is to change it to:

    private String readFile(String pathname) throws IOException {
    File file = new File(pathname);
    StringBuilder fileContents = new StringBuilder((int) file.length());
    Scanner scanner = new Scanner(new BufferedReader(new FileReader(file)));
    String lineSeparator = System.getProperty("line.separator");

    try {
        if (scanner.hasNextLine()) {
            fileContents.append(scanner.nextLine());
        }
        while (scanner.hasNextLine()) {
            fileContents.append(lineSeparator + scanner.nextLine());
        }
        return fileContents.toString();
    } finally {
        scanner.close();
    }
}

How can I select all children of an element except the last child?

Make it simple:

You can apply your style to all the div and re-initialize the last one with :last-child:

for example in CSS:

.yourclass{
    border: 1px solid blue;
}
.yourclass:last-child{
    border: 0;
}

or in SCSS:

.yourclass{
    border: 1px solid rgba(255, 255, 255, 1);
    &:last-child{
        border: 0;
    }
}
  • easy to read/remember
  • fast to execute
  • browser compatible (IE9+ since it's still CSS3)

How can I get useful error messages in PHP?

This answer is brought to you by the department of redundancy department.

  1. ini_set() / php.ini / .htaccess / .user.ini

    The settings display_errors and error_reporting have been covered sufficiently now. But just to recap when to use which option:

    • ini_set() and error_reporting() apply for runtime errors only.
    • php.ini should primarily be edited for development setups. (Webserver and CLI version often have different php.ini's)
    • .htaccess flags only work for dated setups (Find a new hoster! Well managed servers are cheaper.)
    • .user.ini are partial php.ini's for modern setups (FCGI/FPM)

    And as crude alternative for runtime errors you can often use:

    set_error_handler("var_dump");   // ignores error_reporting and `@` suppression
    
  2. error_get_last()

    Can be used to retrieve the last runtime notice/warning/error, when error_display is disabled.

  3. $php_errormsg

    Is a superlocal variable, which also contains the last PHP runtime message.

  4. isset() begone!

    I know this will displease a lot of folks, but isset and empty should not be used by newcomers. You can add the notice suppression after you verified your code is working. But never before.

    A lot of the "something doesn't work" questions we get lately are the result of typos like:

    if(isset($_POST['sumbit']))
    #                  ??
    

    You won't get any useful notices if your code is littered with isset/empty/array_keys_exists. It's sometimes more sensible to use @, so notices and warnings go to the logs at least.

  5. assert_options(ASSERT_ACTIVE|ASSERT_WARNING);

    To get warnings for assert() sections. (Pretty uncommon, but more proficient code might contain some.)

    PHP7 requires zend.assertions=1 in the php.ini as well.

  6. declare(strict_types=1);

    Bending PHP into a strictly typed language is not going to fix a whole lot of logic errors, but it's definitely an option for debugging purposes.

  7. PDO / MySQLi

    And @Phil already mentioned PDO/MySQLi error reporting options. Similar options exist for other database APIs of course.

  8. json_last_error() + json_last_error_msg

    For JSON parsing.

  9. preg_last_error()

    For regexen.

  10. CURLOPT_VERBOSE

    To debug curl requests, you need CURLOPT_VERBOSE at the very least.

  11. shell/exec()

    Likewise will shell command execution not yield errors on its own. You always need 2>&1 and peek at the $errno.

CSS styling in Django forms

Taken from my answer to: How to markup form fields with <div class='field_type'> in Django

class MyForm(forms.Form):
    myfield = forms.CharField(widget=forms.TextInput(attrs={'class' : 'myfieldclass'}))

or

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['myfield'].widget.attrs.update({'class' : 'myfieldclass'})

or

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        widgets = {
            'myfield': forms.TextInput(attrs={'class': 'myfieldclass'}),
        }

--- EDIT ---
The above is the easiest change to make to original question's code that accomplishes what was asked. It also keeps you from repeating yourself if you reuse the form in other places; your classes or other attributes just work if you use the Django's as_table/as_ul/as_p form methods. If you need full control for a completely custom rendering, this is clearly documented

-- EDIT 2 ---
Added a newer way to specify widget and attrs for a ModelForm.

how to save DOMPDF generated content to file?

I did test your code and the only problem I could see was the lack of permission given to the directory you try to write the file in to.

Give "write" permission to the directory you need to put the file. In your case it is the current directory.

Use "chmod" in linux.

Add "Everyone" with "write" enabled to the security tab of the directory if you are in Windows.

How to get the absolute coordinates of a view

You can get a View's coordinates using getLocationOnScreen() or getLocationInWindow()

Afterwards, x and y should be the top-left corner of the view. If your root layout is smaller than the screen (like in a Dialog), using getLocationInWindow will be relative to its container, not the entire screen.

Java Solution

int[] point = new int[2];
view.getLocationOnScreen(point); // or getLocationInWindow(point)
int x = point[0];
int y = point[1];

NOTE: If value is always 0, you are likely changing the view immediately before requesting location.

To ensure view has had a chance to update, run your location request after the View's new layout has been calculated by using view.post:

view.post(() -> {
    // Values should no longer be 0
    int[] point = new int[2];
    view.getLocationOnScreen(point); // or getLocationInWindow(point)
    int x = point[0];
    int y = point[1];
});

~~

Kotlin Solution

val point = IntArray(2)
view.getLocationOnScreen(point) // or getLocationInWindow(point)
val (x, y) = point

NOTE: If value is always 0, you are likely changing the view immediately before requesting location.

To ensure view has had a chance to update, run your location request after the View's new layout has been calculated by using view.post:

view.post {
    // Values should no longer be 0
    val point = IntArray(2)
    view.getLocationOnScreen(point) // or getLocationInWindow(point)
    val (x, y) = point
}

I recommend creating an extension function for handling this:

// To use, call:
val (x, y) = view.screenLocation

val View.screenLocation get(): IntArray {
    val point = IntArray(2)
    getLocationOnScreen(point)
    return point
}

And if you require reliability, also add:

view.screenLocationSafe { x, y -> Log.d("", "Use $x and $y here") }

fun View.screenLocationSafe(callback: (Int, Int) -> Unit) {
    post {
        val (x, y) = screenLocation
        callback(x, y)
    }
}

Conversion failed when converting the varchar value 'simple, ' to data type int

Given that you're only converting to ints to then perform a comparison, I'd just switch the table definition around to using varchar also:

Create table #myTempTable
(
num varchar(12)
)
insert into #myTempTable (num) values (1),(2),(3),(4),(5)

and remove all of the attempted CONVERTs from the rest of the query.

 SELECT a.name, a.value AS value, COUNT(*) AS pocet   
 FROM 
 (SELECT item.name, value.value 
  FROM mdl_feedback AS feedback 
  INNER JOIN mdl_feedback_item AS item 
       ON feedback.id = item.feedback
  INNER JOIN mdl_feedback_value AS value 
       ON item.id = value.item 
   WHERE item.typ = 'multichoicerated' AND item.feedback IN (43)
 ) AS a 
 INNER JOIN #myTempTable 
     on a.value = #myTempTable.num
 GROUP BY a.name, a.value ORDER BY a.name

How to get the number of threads in a Java process

Useful tool for debugging java programs, it gives the number of threads and other relevant info on them:

jconsole <process-id>

Duplicate and rename Xcode project & associated folders

One more thing to try!

When I copied all of my files, opened the project, and renamed it, everything changed to my new project name except for the test target! I got a linker error that said I was missing a file called "myOldProjectname.app". Here's what fixed it:

  1. Click on your project settings and select your test target enter image description here

  2. Click on build settings and search for "test host" enter image description here

  3. Check those 2 file paths. Chances are that those 2 paths are still pointing at your old project name. enter image description here

Hope that helps!

jQuery load more data on scroll

You question specifically is about loading data when a div falls into view, and not when the user reaches the end of the page.

Here's the best answer to your question: https://stackoverflow.com/a/33979503/3024226

$_POST Array from html form

You should get the array like in $_POST['id']. So you should be able to do this:

foreach ($_POST['id'] as $key => $value) {
    echo $value . "<br />";
}

Input names should be same:

<input name='id[]' type='checkbox' value='1'>
<input name='id[]' type='checkbox' value='2'>
...

Measuring elapsed time with the Time module

time.time() will do the job.

import time

start = time.time()
# run your code
end = time.time()

elapsed = end - start

You may want to look at this question, but I don't think it will be necessary.

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

Renaming Columns in an SQL SELECT Statement

select column1 as xyz,
      column2 as pqr,
.....

from TableName;

Click toggle with jQuery

jQuery: Best Way, delegate the actions to jQuery (jQuery = jQuery).

$( "input[type='checkbox']" ).prop( "checked", function( i, val ) {
    return !val;
});

How do I use TensorFlow GPU?

Strangely, even though the tensorflow website 1 mentions that CUDA 10.1 is compatible with tensorflow-gpu-1.13.1, it doesn't work so far. tensorflow-gpu gets installed properly though but it throws out weird errors when running.

So far, the best configuration to run tensorflow with GPU is CUDA 9.0 with tensorflow_gpu-1.12.0 under python3.6.

Following this configuration with the steps mentioned in https://stackoverflow.com/a/51307381/2562870 (the answer above), worked for me :)

Excel VBA, How to select rows based on data in a column?

The easiest way to do it is to use the End method, which is gives you the cell that you reach by pressing the end key and then a direction when you're on a cell (in this case B6). This won't give you what you expect if B6 or B7 is empty, though.

Dim start_cell As Range
Set start_cell = Range("[Workbook1.xlsx]Sheet1!B6")
Range(start_cell, start_cell.End(xlDown)).Copy Range("[Workbook2.xlsx]Sheet1!A2")

If you can't use End, then you would have to use a loop.

Dim start_cell As Range, end_cell As Range

Set start_cell = Range("[Workbook1.xlsx]Sheet1!B6")
Set end_cell = start_cell

Do Until IsEmpty(end_cell.Offset(1, 0))
    Set end_cell = end_cell.Offset(1, 0)
Loop

Range(start_cell, end_cell).Copy Range("[Workbook2.xlsx]Sheet1!A2")

How can I use goto in Javascript?

Absolutely! There is a project called Summer of Goto that allows you use JavaScript at its fullest potential and will revolutionize the way you can write your code.

This JavaScript preprocessing tool allows you to create a label and then goto it using this syntax:

[lbl] <label-name>
goto <label-name>

For example, the example in the question can be written as follows:

[lbl] start:
alert("LATHER");
alert("RINSE");
[lbl] repeat: goto start;

Note that you are not just limited to simple trivial programs like an endless LATHER RINSE repeat cycle—the possibilities afforded by goto are endless and you can even make a Hello, world! message to the JavaScript console 538 times, like this:

var i = 0;
[lbl] start:
console.log("Hello, world!");
i++;
if(i < 538) goto start;

You can read more about how goto is implemented, but basically, it does some JavaScript preprocessing that takes advantage of the fact that you can simulate a goto with a labelled while loop. So, when you write the "Hello, world!" program above, it gets translated to something like this:

var i = 0;
start: while(true) {
  console.log("Hello, world!");
  i++;
  if(i < 538) continue start;
  break;
}

There are some limitations to this preprocessing process, because while loops cannot stretch across multiple functions or blocks. That's not a big deal, though—I'm sure the benefits of being able to take advantage of goto in JavaScript will absolutely overwhelm you.

All above link that lead to goto.js library is ALL DEAD, here is links needed:

goto.js (uncompressed) --- parseScripts.js (uncompressed)

From Goto.js:

P.S. For anyone who is wondering (so far a total of zero people), Summer of Goto is a term that was popularized by Paul Irish, while discussing this script and PHP’s decision to add goto into their language.

And for those who do not immediately recognize that this entire thing is a joke, please forgive me. <—(insurance).

Android Min SDK Version vs. Target SDK Version

When you set targetSdkVersion="xx", you are certifying that your app works properly (e.g., has been thoroughly and successfully tested) at API level xx.

A version of Android running at an API level above xx will apply compatibility code automatically to support any features you might be relying upon that were available at or prior to API level xx, but which are now obsolete at that Android version's higher level.

Conversely, if you are using any features that became obsolete at or prior to level xx, compatibility code will not be automatically applied by OS versions at higher API levels (that no longer include those features) to support those uses. In that situation, your own code must have special case clauses that test the API level and, if the OS level detected is a higher one that no longer has the given API feature, your code must use alternate features that are available at the running OS's API level.

If it fails to do this, then some interface features may simply not appear that would normally trigger events within your code, and you may be missing a critical interface feature that the user needs to trigger those events and to access their functionality (as in the example below).

As stated in other answers, you might set targetSdkVersion higher than minSdkVersion if you wanted to use some API features initially defined at higher API levels than your minSdkVersion, and had taken steps to ensure that your code could detect and handle the absence of those features at lower levels than targetSdkVersion.

In order to warn developers to specifically test for the minimum API level required to use a feature, the compiler will issue an error (not just a warning) if code contains a call to any method that was defined at a later API level than minSdkVersion, even if targetSdkVersion is greater than or equal to the API level at which that method was first made available. To remove this error, the compiler directive

@TargetApi(nn)

tells the compiler that the code within the scope of that directive (which will precede either a method or a class) has been written to test for an API level of at least nn prior to calling any method that depends upon having at least that API level. For example, the following code defines a method that can be called from code within an app that has a minSdkVersion of less than 11 and a targetSdkVersion of 11 or higher:

@TargetApi(11)
    public void refreshActionBarIfApi11OrHigher() {
      //If the API is 11 or higher, set up the actionBar and display it
      if(Build.VERSION.SDK_INT >= 11) {
        //ActionBar only exists at API level 11 or higher
        ActionBar actionBar = getActionBar();

        //This should cause onPrepareOptionsMenu() to be called.
        // In versions of the API prior to 11, this only occurred when the user pressed 
        // the dedicated menu button, but at level 11 and above, the action bar is 
        // typically displayed continuously and so you will need to call this
        // each time the options on your menu change.
        invalidateOptionsMenu();

        //Show the bar
        actionBar.show();
    }
}

You might also want to declare a higher targetSdkVersion if you had tested at that higher level and everything worked, even if you were not using any features from an API level higher than your minSdkVersion. This would be just to avoid the overhead of accessing compatibility code intended to adapt from the target level down to the min level, since you would have confirmed (through testing) that no such adaptation was required.

An example of a UI feature that depends upon the declared targetSdkVersion would be the three-vertical-dot menu button that appears on the status bar of apps having a targetSdkVersion less than 11, when those apps are running under API 11 and higher. If your app has a targetSdkVersion of 10 or below, it is assumed that your app's interface depends upon the existence of a dedicated menu button, and so the three-dot button appears to take the place of the earlier dedicated hardware and/or onscreen versions of that button (e.g., as seen in Gingerbread) when the OS has a higher API level for which a dedicated menu button on the device is no longer assumed. However, if you set your app's targetSdkVersion to 11 or higher, it is assumed that you have taken advantage of features introduced at that level that replace the dedicated menu button (e.g., the Action Bar), or that you have otherwise circumvented the need to have a system menu button; consequently, the three-vertical-dot menu "compatibility button" disappears. In that case, if the user can't find a menu button, she can't press it, and that, in turn, means that your activity's onCreateOptionsMenu(menu) override might never get invoked, which, again in turn, means that a significant part of your app's functionality could be deprived of its user interface. Unless, of course, you have implemented the Action Bar or some other alternative means for the user to access these features.

minSdkVersion, by contrast, states a requirement that a device's OS version have at least that API level in order to run your app. This affects which devices are able to see and download your app when it is on the Google Play app store (and possibly other app stores, as well). It's a way of stating that your app relies upon OS (API or other) features that were established at that level, and does not have an acceptable way to deal with the absence of those features.

An example of using minSdkVersion to ensure the presence of a feature that is not API-related would be to set minSdkVersion to 8 in order to ensure that your app will run only on a JIT-enabled version of the Dalvik interpreter (since JIT was introduced to the Android interpreter at API level 8). Since performance for a JIT-enabled interpreter can be as much as five times that of one lacking that feature, if your app makes heavy use of the processor then you might want to require API level 8 or above in order to ensure adequate performance.

How to colorize diff on the command line?

Since wdiff accepts args specifying the string at the beginning and end of both insertions and deletions, you can use ANSI color sequences as those strings:

wdiff -n -w $'\033[30;41m' -x $'\033[0m' -y $'\033[30;42m' -z $'\033[0m' file1 file2

For example, this is the output of comparing two CSV files:

diff output of CSV files

Example from https://www.gnu.org/software/wdiff/manual/html_node/wdiff-Examples.html

Class Not Found Exception when running JUnit test

I fixed my issue by running maven update. Right click project your project > Maven > Update Project

Maven not found in Mac OSX mavericks

  1. Download Maven from here.
  2. Extract the tar.gz you just downloaded to the location you want (ex:/Users/admin/Maven).
  3. Open the Terminal.
  4. Type " cd " to go to your home folder.
  5. Type "touch .bash_profile".
  6. Type "open -e .bash_profile" to open .bash_profile in TextEdit.
  7. Type the following in the TextEditor

alias mvn='/[Your file location]/apache-maven-x.x.x/bin/mvn'
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdkx.x.x_xx.jdk/Contents/Home/

(Make sure there are no speech marks or apostrophe's) 8. Make sure you fill the required data (ex your file location and version number).

  1. Save your changes
  2. Type ". .bash_profile" to reload .bash_profile and update any functions you add. (*make sure you separate the dots with a single space).
  3. Type mvn -version

If successful you should see the following:

Apache Maven 3.1.1
Maven home: /Users/admin/Maven/apache-maven-3.1.1
Java version: 1.7.0_51, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.9.1", arch: "x86_64", family: "mac"

Java Map equivalent in C#

class Test
{
    Dictionary<int, string> entities;

    public string GetEntity(int code)
    {
        // java's get method returns null when the key has no mapping
        // so we'll do the same

        string val;
        if (entities.TryGetValue(code, out val))
            return val;
        else
            return null;
    }
}

Best Java obfuscator?

It is true that it is always possible to reverse engineer some code, just like it is impossible to protect a house in order so nobody can ever steal from it. That does not keep me from locking the door, though. Actually, I am not in the java world, I use BitHelmet for .net.

Angular ng-if not true

Just use for True:

<li ng-if="area"></li>

and for False:

<li ng-if="area === false"></li>

How to change the playing speed of videos in HTML5?

Just type

document.querySelector('video').playbackRate = 1.25;

in JS console of your modern browser.

jQuery datepicker, onSelect won't work

<script type="text/javascript">
    $(function() {
        $("#datepicker").datepicker({ 
              onSelect: function(value, date) { 
                 window.location = 'day.jsp' ; 
              } 
        });
    });
 </script>

<div id="datepicker"></div>

I think you can try this .It works fine .

Flask SQLAlchemy query, specify column names

You can use the with_entities() method to restrict which columns you'd like to return in the result. (documentation)

result = SomeModel.query.with_entities(SomeModel.col1, SomeModel.col2)

Depending on your requirements, you may also find deferreds useful. They allow you to return the full object but restrict the columns that come over the wire.

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

Haskell

foldl (+) 0 [1,2,3,4,5]

Python

reduce(lambda a,b: a+b, [1,2,3,4,5], 0)

Obviously, that is a trivial example to illustrate a point. In Python you would just do sum([1,2,3,4,5]) and even Haskell purists would generally prefer sum [1,2,3,4,5].

For non-trivial scenarios when there is no obvious convenience function, the idiomatic pythonic approach is to explicitly write out the for loop and use mutable variable assignment instead of using reduce or a fold.

That is not at all the functional style, but that is the "pythonic" way. Python is not designed for functional purists. See how Python favors exceptions for flow control to see how non-functional idiomatic python is.

How to combine date from one field with time from another field - MS SQL Server

Convert both field into DATETIME :

SELECT CAST(@DateField as DATETIME) + CAST(@TimeField AS DATETIME)

and if you're using Getdate() use this first:

DECLARE @FechaActual DATETIME = CONVERT(DATE, GETDATE());
SELECT CAST(@FechaActual as DATETIME) + CAST(@HoraInicioTurno AS DATETIME)

How do you change the character encoding of a postgres database?

# dump into file
pg_dump myDB > /tmp/myDB.sql

# create an empty db with the right encoding (on older versions the escaped single quotes are needed!)
psql -c 'CREATE DATABASE "tempDB" WITH OWNER = "myself" LC_COLLATE = '\''de_DE.utf8'\'' TEMPLATE template0;'

# import in the new DB
psql -d tempDB -1 -f /tmp/myDB.sql

# rename databases
psql -c 'ALTER DATABASE "myDB" RENAME TO "myDB_wrong_encoding";' 
psql -c 'ALTER DATABASE "tempDB" RENAME TO "myDB";'

# see the result
psql myDB -c "SHOW LC_COLLATE"   

Creating a SOAP call using PHP with an XML body

There are a couple of ways to solve this. The least hackiest and almost what you want:

$client = new SoapClient(
    null,
    array(
        'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
        'uri' => 'http://example.com/wsdl',
        'trace' => 1,
        'use' => SOAP_LITERAL,
    )
);
$params = new \SoapVar("<Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer>", XSD_ANYXML);
$result = $client->Echo($params);

This gets you the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://example.com/wsdl">
    <SOAP-ENV:Body>
        <ns1:Echo>
            <Acquirer>
                <Id>MyId</Id>
                <UserId>MyUserId</UserId>
                <Password>MyPassword</Password>
            </Acquirer>
        </ns1:Echo>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

That is almost exactly what you want, except for the namespace on the method name. I don't know if this is a problem. If so, you can hack it even further. You could put the <Echo> tag in the XML string by hand and have the SoapClient not set the method by adding 'style' => SOAP_DOCUMENT, to the options array like this:

$client = new SoapClient(
    null,
    array(
        'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
        'uri' => 'http://example.com/wsdl',
        'trace' => 1,
        'use' => SOAP_LITERAL,
        'style' => SOAP_DOCUMENT,
    )
);
$params = new \SoapVar("<Echo><Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer></Echo>", XSD_ANYXML);
$result = $client->MethodNameIsIgnored($params);

This results in the following request XML:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Body>
        <Echo>
            <Acquirer>
                <Id>MyId</Id>
                <UserId>MyUserId</UserId>
                <Password>MyPassword</Password>
            </Acquirer>
        </Echo>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Finally, if you want to play around with SoapVar and SoapParam objects, you can find a good reference in this comment in the PHP manual: http://www.php.net/manual/en/soapvar.soapvar.php#104065. If you get that to work, please let me know, I failed miserably.

How can I use std::maps with user-defined types as key?

By default std::map (and std::set) use operator< to determine sorting. Therefore, you need to define operator< on your class.

Two objects are deemed equivalent if !(a < b) && !(b < a).

If, for some reason, you'd like to use a different comparator, the third template argument of the map can be changed, to std::greater, for example.

What good are SQL Server schemas?

If you keep your schema discrete then you can scale an application by deploying a given schema to a new DB server. (This assumes you have an application or system which is big enough to have distinct functionality).

An example, consider a system that performs logging. All logging tables and SPs are in the [logging] schema. Logging is a good example because it is rare (if ever) that other functionality in the system would overlap (that is join to) objects in the logging schema.

A hint for using this technique -- have a different connection string for each schema in your application / system. Then you deploy the schema elements to a new server and change your connection string when you need to scale.

Dropdown select with images

This is using ms-Dropdown : https://github.com/marghoobsuleman/ms-Dropdown

But data resource is json.

Example : http://jsfiddle.net/tcibikci/w3rdhj4s/6

HTML

<div id="byjson"></div>

Script

<script>
        var jsonData = [
            {description:'Choos your payment gateway', value:'', text:'Payment Gateway'},
            {image:'https://via.placeholder.com/50', description:'My life. My card...', value:'amex', text:'Amex'},
            {image:'https://via.placeholder.com/50', description:'It pays to Discover...', value:'Discover', text:'Discover'},
            {image:'https://via.placeholder.com/50', title:'For everything else...', description:'For everything else...', value:'Mastercard', text:'Mastercard'},
            {image:'https://via.placeholder.com/50', description:'Sorry not available...', value:'cash', text:'Cash on devlivery', disabled:true},
            {image:'https://via.placeholder.com/50', description:'All you need...', value:'Visa', text:'Visa'},
            {image:'https://via.placeholder.com/50', description:'Pay and get paid...', value:'Paypal', text:'Paypal'}
        ];
        $("#byjson").msDropDown({byJson:{data:jsonData, name:'payments2'}}).data("dd");
    }
</script>

DateTime2 vs DateTime in SQL Server

Almost all the Answers and Comments have been heavy on the Pros and light on the Cons. Here's a recap of all Pros and Cons so far plus some crucial Cons (in #2 below) I've only seen mentioned once or not at all.

  1. PROS:

1.1. More ISO compliant (ISO 8601) (although I don’t know how this comes into play in practice).

1.2. More range (1/1/0001 to 12/31/9999 vs. 1/1/1753-12/31/9999) (although the extra range, all prior to year 1753, will likely not be used except for ex., in historical, astronomical, geologic, etc. apps).

1.3. Exactly matches the range of .NET’s DateTime Type’s range (although both convert back and forth with no special coding if values are within the target type’s range and precision except for Con # 2.1 below else error / rounding will occur).

1.4. More precision (100 nanosecond aka 0.000,000,1 sec. vs. 3.33 millisecond aka 0.003,33 sec.) (although the extra precision will likely not be used except for ex., in engineering / scientific apps).

1.5. When configured for similar (as in 1 millisec not "same" (as in 3.33 millisec) as Iman Abidi has claimed) precision as DateTime, uses less space (7 vs. 8 bytes), but then of course, you’d be losing the precision benefit which is likely one of the two (the other being range) most touted albeit likely unneeded benefits).

  1. CONS:

2.1. When passing a Parameter to a .NET SqlCommand, you must specify System.Data.SqlDbType.DateTime2 if you may be passing a value outside the SQL Server DateTime’s range and/or precision, because it defaults to System.Data.SqlDbType.DateTime.

2.2. Cannot be implicitly / easily converted to a floating-point numeric (# of days since min date-time) value to do the following to / with it in SQL Server expressions using numeric values and operators:

2.2.1. add or subtract # of days or partial days. Note: Using DateAdd Function as a workaround is not trivial when you're needing to consider multiple if not all parts of the date-time.

2.2.2. take the difference between two date-times for purposes of “age” calculation. Note: You cannot simply use SQL Server’s DateDiff Function instead, because it does not compute age as most people would expect in that if the two date-times happens to cross a calendar / clock date-time boundary of the units specified if even for a tiny fraction of that unit, it’ll return the difference as 1 of that unit vs. 0. For example, the DateDiff in Day’s of two date-times only 1 millisecond apart will return 1 vs. 0 (days) if those date-times are on different calendar days (i.e. “1999-12-31 23:59:59.9999999” and “2000-01-01 00:00:00.0000000”). The same 1 millisecond difference date-times if moved so that they don’t cross a calendar day, will return a “DateDiff” in Day’s of 0 (days).

2.2.3. take the Avg of date-times (in an Aggregate Query) by simply converting to “Float” first and then back again to DateTime.

NOTE: To convert DateTime2 to a numeric, you have to do something like the following formula which still assumes your values are not less than the year 1970 (which means you’re losing all of the extra range plus another 217 years. Note: You may not be able to simply adjust the formula to allow for extra range because you may run into numeric overflow issues.

25567 + (DATEDIFF(SECOND, {d '1970-01-01'}, @Time) + DATEPART(nanosecond, @Time) / 1.0E + 9) / 86400.0 – Source: “ https://siderite.dev/blog/how-to-translate-t-sql-datetime2-to.html

Of course, you could also Cast to DateTime first (and if necessary back again to DateTime2), but you'd lose the precision and range (all prior to year 1753) benefits of DateTime2 vs. DateTime which are prolly the 2 biggest and also at the same time prolly the 2 least likely needed which begs the question why use it when you lose the implicit / easy conversions to floating-point numeric (# of days) for addition / subtraction / "age" (vs. DateDiff) / Avg calcs benefit which is a big one in my experience.

Btw, the Avg of date-times is (or at least should be) an important use case. a) Besides use in getting average duration when date-times (since a common base date-time) are used to represent duration (a common practice), b) it’s also useful to get a dashboard-type statistic on what the average date-time is in the date-time column of a range / group of Rows. c) A standard (or at least should be standard) ad-hoc Query to monitor / troubleshoot values in a Column that may not be valid ever / any longer and / or may need to be deprecated is to list for each value the occurrence count and (if available) the Min, Avg and Max date-time stamps associated with that value.

Difference between ProcessBuilder and Runtime.exec()

The various overloads of Runtime.getRuntime().exec(...) take either an array of strings or a single string. The single-string overloads of exec() will tokenise the string into an array of arguments, before passing the string array onto one of the exec() overloads that takes a string array. The ProcessBuilder constructors, on the other hand, only take a varargs array of strings or a List of strings, where each string in the array or list is assumed to be an individual argument. Either way, the arguments obtained are then joined up into a string that is passed to the OS to execute.

So, for example, on Windows,

Runtime.getRuntime().exec("C:\DoStuff.exe -arg1 -arg2");

will run a DoStuff.exe program with the two given arguments. In this case, the command-line gets tokenised and put back together. However,

ProcessBuilder b = new ProcessBuilder("C:\DoStuff.exe -arg1 -arg2");

will fail, unless there happens to be a program whose name is DoStuff.exe -arg1 -arg2 in C:\. This is because there's no tokenisation: the command to run is assumed to have already been tokenised. Instead, you should use

ProcessBuilder b = new ProcessBuilder("C:\DoStuff.exe", "-arg1", "-arg2");

or alternatively

List<String> params = java.util.Arrays.asList("C:\DoStuff.exe", "-arg1", "-arg2");
ProcessBuilder b = new ProcessBuilder(params);

How do I create sql query for searching partial matches?

This may work as well.

SELECT * 
FROM myTable
WHERE CHARINDEX('mall', name) > 0
  OR CHARINDEX('mall', description) > 0

Change image source in code behind - Wpf

None of the methods worked for me as i needed to pull the image from a folder instead of adding it to the application. The below code worked:

TestImage.Source = GetImage("/Content/Images/test.png")

private static BitmapImage GetImage(string imageUri)
{
    var bitmapImage = new BitmapImage();
    
    bitmapImage.BeginInit();
    bitmapImage.UriSource = new Uri("pack://siteoforigin:,,,/" + imageUri,             UriKind.RelativeOrAbsolute);
    bitmapImage.EndInit();
    
    return bitmapImage;
} 

html select option SELECTED

foreach ($array as $value => $name) {
     echo '<option value="' . htmlentities($value) . '"' . (($_GET['sel'] === $value) ? ' selected="selected"') . '>' . htmlentities($name) . '</option>';
}

This is fairly neat, and, I think, self-explanatory.

Comparing two maps

As long as you override equals() on each key and value contained in the map, then m1.equals(m2) should be reliable to check for maps equality.

The same result can be obtained also by comparing toString() of each map as you suggested, but using equals() is a more intuitive approach.

May not be your specific situation, but if you store arrays in the map, may be a little tricky, because they must be compared value by value, or using Arrays.equals(). More details about this see here.

How to check if Receiver is registered in Android?

I am not sure the API provides directly an API, if you consider this thread:

I was wondering the same thing.
In my case I have a BroadcastReceiver implementation that calls Context#unregisterReceiver(BroadcastReceiver) passing itself as the argument after handling the Intent that it receives.
There is a small chance that the receiver's onReceive(Context, Intent) method is called more than once, since it is registered with multiple IntentFilters, creating the potential for an IllegalArgumentException being thrown from Context#unregisterReceiver(BroadcastReceiver).

In my case, I can store a private synchronized member to check before calling Context#unregisterReceiver(BroadcastReceiver), but it would be much cleaner if the API provided a check method.

Format the date using Ruby on Rails

Since the timestamps are seconds since the UNIX epoch, you can use DateTime.strptime ("string parse time") with the correct specifier:

Date.strptime('1100897479', '%s')
#=> #<Date: 2004-11-19 ((2453329j,0s,0n),+0s,2299161j)>
Date.strptime('1100897479', '%s').to_s
#=> "2004-11-19"
DateTime.strptime('1100897479', '%s')
#=> #<DateTime: 2004-11-19T20:51:19+00:00 ((2453329j,75079s,0n),+0s,2299161j)>
DateTime.strptime('1100897479', '%s').to_s
#=> "2004-11-19T20:51:19+00:00"

Note that you have to require 'date' for that to work, then you can call it either as Date.strptime (if you only care about the date) or DateTime.strptime (if you want date and time). If you need different formatting, you can call DateTime#strftime (look at strftime.net if you have a hard time with the format strings) on it or use one of the built-in methods like rfc822.

How do I iterate through the files in a directory in Java?

To add with @msandiford answer, as most of the times when a file tree is walked u may want to execute a function as a directory or any particular file is visited. If u are reluctant to using streams. The following methods overridden can be implemented

Files.walkFileTree(Paths.get(Krawl.INDEXPATH), EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
    new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                throws IOException {
                // Do someting before directory visit
                return FileVisitResult.CONTINUE;
        }
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                throws IOException {
                // Do something when a file is visited
                return FileVisitResult.CONTINUE;
        }
        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc)
                throws IOException {
                // Do Something after directory visit 
                return FileVisitResult.CONTINUE;
        }
});

How to find whether MySQL is installed in Red Hat?

If you're looking for the RPM.

rpm -qa | grep MySQL

Most of it's data is stored in /var/lib/mysql so that's another good place to look.

If it is installed

which mysql

will give you the location of the binary.

You could also do an

updatedb

and a

locate mysql

to find any mysql files.

vertical-align: middle with Bootstrap 2

Try removing the float attribute from span6:

{ float:none !important; }

Python: tf-idf-cosine: to find document similarity

I know its an old post. but I tried the http://scikit-learn.sourceforge.net/stable/ package. here is my code to find the cosine similarity. The question was how will you calculate the cosine similarity with this package and here is my code for that

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import TfidfVectorizer

f = open("/root/Myfolder/scoringDocuments/doc1")
doc1 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc2")
doc2 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc3")
doc3 = str.decode(f.read(), "UTF-8", "ignore")

train_set = ["president of India",doc1, doc2, doc3]

tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix_train = tfidf_vectorizer.fit_transform(train_set)  #finds the tfidf score with normalization
print "cosine scores ==> ",cosine_similarity(tfidf_matrix_train[0:1], tfidf_matrix_train)  #here the first element of tfidf_matrix_train is matched with other three elements

Here suppose the query is the first element of train_set and doc1,doc2 and doc3 are the documents which I want to rank with the help of cosine similarity. then I can use this code.

Also the tutorials provided in the question was very useful. Here are all the parts for it part-I,part-II,part-III

the output will be as follows :

[[ 1.          0.07102631  0.02731343  0.06348799]]

here 1 represents that query is matched with itself and the other three are the scores for matching the query with the respective documents.

How to read specific lines from a file (by line number)?

Reading from specific line:

n = 4   # for reading from 5th line
with open("write.txt",'r') as t:
     for i,line in enumerate(t):
         if i >= n:             # i == n-1 for nth line
            print(line)

Add back button to action bar

if anyone else need the solution

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == android.R.id.home) {
        onBackPressed();
    }

    return super.onOptionsItemSelected(item);
}

PHP Deprecated: Methods with the same name

As mentioned in the error, the official manual and the comments:

Replace

public function TSStatus($host, $queryPort)

with

public function __construct($host, $queryPort)

How can I grep for a string that begins with a dash/hyphen?

If you're using another utility that passes a single argument to grep, you can use:

'[-]X'

Format / Suppress Scientific Notation from Python Pandas Aggregation Results

Here is another way of doing it, similar to Dan Allan's answer but without the lambda function:

>>> pd.options.display.float_format = '{:.2f}'.format
>>> Series(np.random.randn(3))
0    0.41
1    0.99
2    0.10

or

>>> pd.set_option('display.float_format', '{:.2f}'.format)

Create a shortcut on Desktop

You can use this ShellLink.cs class to create the shortcut.

To get the desktop directory, use:

var dir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

or use Environment.SpecialFolder.CommonDesktopDirectory to create it for all users.

Find nearest value in numpy array

Maybe helpful for ndarrays:

def find_nearest(X, value):
    return X[np.unravel_index(np.argmin(np.abs(X - value)), X.shape)]

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

java.lang.RuntimeException: Uncompilable source code - what can cause this?

I guess you are using an IDE (like Netbeans) which allows you to run the code even if certain classes are not compilable. During the application's runtime, if you access this class it would lead to this exception.

Multiple Python versions on the same machine?

Package Managers - user-level

For a package manager that can install and manage multiple versions of python, these are good choices:

  • pyenv - only able to install and manage versions of python
  • asdf - able to install and manage many different languages

The advantages to these package managers is that it may be easier to set them up and install multiple versions of python with them than it is to install python from source. They also provide commands for easily changing the available python version(s) using shims and setting the python version per-directory.

This disadvantage is that, by default, they are installed at the user-level (inside your home directory) and require a little bit of user-level configuration - you'll need to edit your ~/.profile and ~/.bashrc or similar files. This means that it is not easy to use them to install multiple python versions globally for all users. In order to do this, you can install from source alongside the OS's existing python version.


Installation from source - system-wide

You'll need root privileges for this method.

See the official python documentation for building from source for additional considerations and options.

/usr/local is the designated location for a system administrator to install shared (system-wide) software, so it's subdirectories are a good place to download the python source and install. See section 4.9 of the Linux Foundation's File Hierarchy Standard.

Install any build dependencies. On Debian-based systems, use:

apt update
apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libsqlite3-dev libreadline-dev libffi-dev libbz2-dev

Choose which python version you want to install. See the Python Source Releases page for a listing.

Download and unzip file in /usr/local/src, replacing X.X.X below with the python version (i.e. 3.8.2).

cd /usr/local/src
wget https://www.python.org/ftp/python/X.X.X/Python-X.X.X.tgz
tar vzxf Python-X.X.X.tgz

Before building and installing, set the CFLAGS environment variable with C compiler flags necessary (see GNU's make documentation). This is usually not necessary for general use, but if, for example, you were going to create a uWSGI plugin with this python version, you might want to set the flags, -fPIC, with the following:

export CFLAGS='-fPIC'

Change the working directory to the unzipped python source directory, and configure the build. You'll probably want to use the --enable-optimizations option on the ./configure command for profile guided optimization. Use --prefix=/usr/local to install to the proper subdirectories (/usr/local/bin, /usr/local/lib, etc.).

cd Python-X.X.X
./configure --enable-optimizations --prefix=/usr/local

Build the project with make and install with make altinstall to avoid overriding any files when installing multiple versions. See the warning on this page of the python build documentation.

make -j 4
make altinstall

Then you should be able to run your new python and pip versions with pythonX.X and pipX.X (i.e python3.8 and pip3.8). Note that if the minor version of your new installation is the same as the OS's version (for example if you were installing python3.8.4 and the OS used python3.8.2), then you would need to specify the entire path (/usr/local/bin/pythonX.X) or set an alias to use this version.

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

I am just answering here with the formatted version of the final sql I needed based on Bob Jarvis answer as posted in my comment above:

select n1.name, n1.author_id, cast(count_1 as numeric)/total_count
  from (select id, name, author_id, count(1) as count_1
          from names
          group by id, name, author_id) n1
inner join (select author_id, count(1) as total_count
              from names
              group by author_id) n2
  on (n2.author_id = n1.author_id)

Change Input to Upper Case

This answer has a problem:

style="text-transform: uppercase"

it also converts the place holder word to upper case which is inconvenient

placeholder="first name"

when rendering the input, it writes "first name" placeholder as uppercase

FIRST NAME

so i wrote something better:

onkeypress="this.value = this.value + event.key.toUpperCase(); return false;"

it works good!, but it has some side effects if your javascript code is complex,

hope it helps somebody to give him/her an idea to develop a better solution.

Copy or rsync command

The command as written will create new directories and files with the current date and time stamp, and yourself as the owner. If you are the only user on your system and you are doing this daily it may not matter much. But if preserving those attributes matters to you, you can modify your command with

cp -pur /home/abc/* /mnt/windowsabc/

The -p will preserve ownership, timestamps, and mode of the file. This can be pretty important depending on what you're backing up.

The alternative command with rsync would be

rsync -avh /home/abc/* /mnt/windowsabc

With rsync, -a indicates "archive" which preserves all those attributes mentioned above. -v indicates "verbose" which just lists what it's doing with each file as it runs. -z is left out here for local copies, but is for compression, which will help if you are backing up over a network. Finally, the -h tells rsync to report sizes in human-readable formats like MB,GB,etc.

Out of curiosity, I ran one copy to prime the system and avoid biasing against the first run, then I timed the following on a test run of 1GB of files from an internal SSD drive to a USB-connected HDD. These simply copied to empty target directories.

cp -pur    : 19.5 seconds
rsync -ah  : 19.6 seconds
rsync -azh : 61.5 seconds

Both commands seem to be about the same, although zipping and unzipping obviously tax the system where bandwidth is not a bottleneck.

Finding non-numeric rows in dataframe in pandas?

# Original code
df = pd.DataFrame({'a': [1, 2, 3, 'bad', 5],
                   'b': [0.1, 0.2, 0.3, 0.4, 0.5],
                   'item': ['a', 'b', 'c', 'd', 'e']})
df = df.set_index('item')

Convert to numeric using 'coerce' which fills bad values with 'nan'

a = pd.to_numeric(df.a, errors='coerce')

Use isna to return a boolean index:

idx = a.isna()

Apply that index to the data frame:

df[idx]

output

Returns the row with the bad data in it:

        a    b
item          
d     bad  0.4

jQuery jump or scroll to certain position, div or target on the page from button onclick

I would style a link to look like a button, because that way there is a no-js fallback.


So this is how you could animate the jump using jquery. No-js fallback is a normal jump without animation.

Original example:

jsfiddle

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".jumper").on("click", function( e ) {_x000D_
_x000D_
    e.preventDefault();_x000D_
_x000D_
    $("body, html").animate({ _x000D_
      scrollTop: $( $(this).attr('href') ).offset().top _x000D_
    }, 600);_x000D_
_x000D_
  });_x000D_
});
_x000D_
#long {_x000D_
  height: 500px;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!-- Links that trigger the jumping -->_x000D_
<a class="jumper" href="#pliip">Pliip</a>_x000D_
<a class="jumper" href="#ploop">Ploop</a>_x000D_
<div id="long">...</div>_x000D_
<!-- Landing elements -->_x000D_
<div id="pliip">pliip</div>_x000D_
<div id="ploop">ploop</div>
_x000D_
_x000D_
_x000D_


New example with actual button styles for the links, just to prove a point.

Everything is essentially the same, except that I changed the class .jumper to .button and I added css styling to make the links look like buttons.

Button styles example

OSX -bash: composer: command not found

this wasted me a day or two. like why dont anybody say on tutorials that the command composer is not to be used without actually linking and stuff... I mean everyone is writing composer command like its the next step when we are not all 5 years experienced users to know these details.

cp composer.phar /usr/local/bin/composer

did it for me on ubuntu after getting stuck for 2 days

How to implement "Access-Control-Allow-Origin" header in asp.net

From enable-cors.org:

CORS on ASP.NET

If you don't have access to configure IIS, you can still add the header through ASP.NET by adding the following line to your source pages:

Response.AppendHeader("Access-Control-Allow-Origin", "*");

See also: Configuring IIS6 / IIS7

Superscript in markdown (Github flavored)?

Use the <sup></sup>tag (<sub></sub> is the equivalent for subscripts). See this gist for an example.

Circle-Rectangle collision detection (intersection)

Here is the modfied code 100% working:

public static bool IsIntersected(PointF circle, float radius, RectangleF rectangle)
{
    var rectangleCenter = new PointF((rectangle.X +  rectangle.Width / 2),
                                     (rectangle.Y + rectangle.Height / 2));

    var w = rectangle.Width  / 2;
    var h = rectangle.Height / 2;

    var dx = Math.Abs(circle.X - rectangleCenter.X);
    var dy = Math.Abs(circle.Y - rectangleCenter.Y);

    if (dx > (radius + w) || dy > (radius + h)) return false;

    var circleDistance = new PointF
                             {
                                 X = Math.Abs(circle.X - rectangle.X - w),
                                 Y = Math.Abs(circle.Y - rectangle.Y - h)
                             };

    if (circleDistance.X <= (w))
    {
        return true;
    }

    if (circleDistance.Y <= (h))
    {
        return true;
    }

    var cornerDistanceSq = Math.Pow(circleDistance.X - w, 2) + 
                                    Math.Pow(circleDistance.Y - h, 2);

    return (cornerDistanceSq <= (Math.Pow(radius, 2)));
}

Bassam Alugili

Convert integer to hexadecimal and back again

To Hex:

string hex = intValue.ToString("X");

To int:

int intValue = int.Parse(hex, System.Globalization.NumberStyles.HexNumber)

How to permanently remove few commits from remote branch

This might be too little too late but what helped me is the cool sounding 'nuclear' option. Basically using the command filter-branch you can remove files or change something over a large number of files throughout your entire git history.

It is best explained here.

How can one see the structure of a table in SQLite?

You will get the structure by typing the command:

.schema <tableName>

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

Javascript's String.fromCharCode(code1, code2, ..., codeN) takes an infinite number of arguments and returns a string of letters whose corresponding ASCII values are code1, code2, ... codeN. Since 97 is 'a' in ASCII, we can adjust for your indexing by adding 97 to your index.

function indexToChar(i) {
  return String.fromCharCode(i+97); //97 in ASCII is 'a', so i=0 returns 'a', 
                                    // i=1 returns 'b', etc
}

how to put focus on TextBox when the form load?

I solved my problem with changing "TabIndex" property of TextBox. I set 0 for TextBox that I want to focus it on Form when the program start.

UnsatisfiedDependencyException: Error creating bean with name

Considering that your package scanning is correctly set either through XML configuration or annotation based configuration.

You will need a @Repository on your ClientRepository implementation as well to allow Spring to use it in an @Autowired. Since it's not here we can only suppose that's what's missing.

As a side note, it would be cleaner to put your @Autowired/@Qualifier directly on your member if the setter method is only used for the @Autowired.

@Autowired
@Qualifier("clientRepository")
private ClientRepository clientRepository;

Lastly, you don't need the @Qualifier is there is only one class implementing the bean definition so unless you have several implementation of ClientService and ClientRepository you can remove the @Qualifier

How to open an Excel file in C#?

you should open like this

        Excel.Application xlApp ;
        Excel.Workbook xlWorkBook ;
        Excel.Worksheet xlWorkSheet ;
        object misValue = System.Reflection.Missing.Value;

        xlApp = new Excel.ApplicationClass();
        xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

source : http://csharp.net-informations.com/excel/csharp-open-excel.htm

ruden

How to set a string's color

Console

See the Wikipedia page on ANSI escapes for the full collection of sequences, including the colors.

But for one simple example (Printing in red) in Java (as you tagged this as Java) do:

System.out.println("\u001B31;1mhello world!");

The 3 indicates change color, the first 1 indicates red (green would be 2) and the second 1 indicates do it in "bright" mode.

GUI

However, if you want to print to a GUI the easiest way is to use html:

JEditorPane pane = new new JEditorPane();
pane.setText("<html><font color=\"red\">hello world!</font></html>");

For more details on this sort of thing, see the Swing Tutorial. It is also possible by using styles in a JTextPane. Here is a helpful example of code to do this easily with a JTextPane (added from helpful comment).

JTextArea is a single coloured Text component, as described here. It can only display in one color. You can set the color for the whole JTextArea like this:

JTextArea area = new JTextArea("hello world");
area.setForeground(Color.red)

Enum "Inheritance"

The short answer is no. You can play a bit, if you want:

You can always do something like this:

private enum Base
{
    A,
    B,
    C
}

private enum Consume
{
    A = Base.A,
    B = Base.B,
    C = Base.C,
    D,
    E
}

But, it doesn't work all that great because Base.A != Consume.A

You can always do something like this, though:

public static class Extensions
{
    public static T As<T>(this Consume c) where T : struct
    {
        return (T)System.Enum.Parse(typeof(T), c.ToString(), false);
    }
}

In order to cross between Base and Consume...

You could also cast the values of the enums as ints, and compare them as ints instead of enum, but that kind of sucks too.

The extension method return should type cast it type T.

Specify JDK for Maven to use

I know its an old thread. But I was having some issues with something similar to this in Maven for Java 8 compiler source. I figured this out with a quick fix mentioned in this article thought I can put it here and maybe can help others:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

Insert NULL value into INT column

2 ways to do it

insert tbl (other, col1, intcol) values ('abc', 123, NULL)

or just omit it from the column list

insert tbl (other, col1) values ('abc', 123)

How do I concatenate strings and variables in PowerShell?

These answers all seem very complicated. If you are using this in a PowerShell script you can simply do this:

$name = 'Slim Shady'
Write-Host 'My name is'$name

It will output

My name is Slim Shady

Note how a space is put between the words for you

Deleting an SVN branch

You can delete the features folder just like any other in your checkout then commit the change.

To prevent this in the future I suggest you follow the naming conventions for SVN layout.

Either give each project a trunk, branches, tags folder when they are created.

svn
+ project1
  + trunk
    + src
    + etc...
  + branches
    + features
      + src
      + etc...
  + tags
+ project2
  + trunk
  + branches
  + tags

Setting java locale settings

On linux, create file in /etc/default/locale with the following contents

LANG=en.utf8

and then use the source command to export this variable by running

source /etc/default/locale

The source command sets the variable permanently.

Enum to String C++

Kind of an anonymous lookup table rather than a long switch statement:

return (const char *[]) {
    "bananas & monkeys",
    "Round and orange", 
    "APPLE",
}[enumVal];

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

We have been solving the same problem just today, and all you need to do is to increase the runtime version of .NET

4.5.2 didn't work for us with the above problem, while 4.6.1 was OK

If you need to keep the .NET version, then set

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

TCPDF output without saving file

If You want to open dialogue window in browser to save, not open with PDF browser viewer (I was looking for this solution for a while), You should use 'D':

$pdf->Output('name.pdf', 'D');

How to get the parent dir location

May be join two .. folder, to get parent of the parent folder?

path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),"..",".."))

iOS: Convert UTC NSDate to local Timezone

Please use this code.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"]; 
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSDate *date = [dateFormatter dateFromString:@"2015-04-01T11:42:00"]; // create date from string

[dateFormatter setDateFormat:@"EEE, MMM d, yyyy - h:mm a"];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *timestamp = [dateFormatter stringFromDate:date];

HTML table with 100% width, with vertical scroll inside tbody

For using "overflow: scroll" you must set "display:block" on thead and tbody. And that messes up column widths between them. But then you can clone the thead row with Javascript and paste it in the tbody as a hidden row to keep the exact col widths.

$('.myTable thead > tr').clone().appendTo('.myTable tbody').addClass('hidden-to-set-col-widths');

http://jsfiddle.net/Julesezaar/mup0c5hk/

<table class="myTable">
    <thead>
        <tr>
            <td>Problem</td>
            <td>Solution</td>
            <td>blah</td>
            <td>derp</td>
        </tr>
    </thead>
    <tbody></tbody>
</table>
<p>
  Some text to here
</p>

The css:

table {
  background-color: #aaa;
  width: 100%;
}

thead,
tbody {
  display: block; // Necessary to use overflow: scroll
}

tbody {
  background-color: #ddd;
  height: 150px;
  overflow-y: scroll;
}

tbody tr.hidden-to-set-col-widths,
tbody tr.hidden-to-set-col-widths td {
  visibility: hidden;
  height: 0;
  line-height: 0;
  padding-top: 0;
  padding-bottom: 0;
}

td {
  padding: 3px 10px;
}

Twitter Bootstrap: div in container with 100% height

It is very simple. You can use

.fill .map 
{
  min-height: 100vh;
}

You can change height according to your requirement.

What do "branch", "tag" and "trunk" mean in Subversion repositories?

I found this great tutorial regarding SVN when I was looking up the website of the author of the OpenCV 2 Computer Vision Application Programming Cookbook and I thought I should share.

He has a tutorial on how to use SVN and what the phrases 'trunk', 'tag' and 'branch' mean.

Cited directly from his tutorial:

The current version of your software project, on which your team is currently working is usually located under a directory called trunk. As the project evolves, the developer updates that version fix bugs, add new features) and submit his changes under that directory.

At any given point in time, you may want to freeze a version and capture a snapshot of the software as it is at this stage of the development. This generally corresponds to the official versions of your software, for example, the ones you will deliver to your clients. These snapshots are located under the tags directory of your project.

Finally, it is often useful to create, at some point, a new line of development for your software. This happens, for example, when you wish to test an alternative implementation in which you have to modify your software but you do not want to submit these changes to the main project until you decide if you adopt the new solution. The main team can then continue to work on the project while other developer work on the prototype. You would put these new lines of development of the project under a directory called branches.

why is plotting with Matplotlib so slow?

For the first solution proposed by Joe Kington ( .copy_from_bbox & .draw_artist & canvas.blit), I had to capture the backgrounds after the fig.canvas.draw() line, otherwise the background had no effect and I got the same result as you mentioned. If you put it after the fig.show() it still does not work as proposed by Michael Browne.

So just put the background line after the canvas.draw():

[...]
fig.show()

# We need to draw the canvas before we start animating...
fig.canvas.draw()

# Let's capture the background of the figure
backgrounds = [fig.canvas.copy_from_bbox(ax.bbox) for ax in axes]

127 Return code from $?

It has no special meaning, other than that the last process to exit did so with an exit status of 127.

However, it is also used by bash (assuming you're using bash as a shell) to tell you that the command you tried to execute couldn't be executed (i.e. it couldn't be found). It's unfortunately not immediately deducible though, if the process exited with status 127, or if it couldn't found.

EDIT:
Not immediately deducible, except for the output on the console, but this is stack overflow, so I assume you're doing this in a script.

How to convert R Markdown to PDF?

Only two steps:

  1. Install the latest release "pandoc" from here:

    https://github.com/jgm/pandoc/releases

  2. Call the function pandoc in the library(knitr)

    library(knitr)
    pandoc('input.md', format = 'latex')
    

Thus, you can convert your "input.md" into "input.pdf".

Good examples of python-memcache (memcached) being used in Python?

It's fairly simple. You write values using keys and expiry times. You get values using keys. You can expire keys from the system.

Most clients follow the same rules. You can read the generic instructions and best practices on the memcached homepage.

If you really want to dig into it, I'd look at the source. Here's the header comment:

"""
client module for memcached (memory cache daemon)

Overview
========

See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.

Usage summary
=============

This should give you a feel for how this module operates::

    import memcache
    mc = memcache.Client(['127.0.0.1:11211'], debug=0)

    mc.set("some_key", "Some value")
    value = mc.get("some_key")

    mc.set("another_key", 3)
    mc.delete("another_key")

    mc.set("key", "1")   # note that the key used for incr/decr must be a string.
    mc.incr("key")
    mc.decr("key")

The standard way to use memcache with a database is like this::

    key = derive_key(obj)
    obj = mc.get(key)
    if not obj:
        obj = backend_api.get(...)
        mc.set(key, obj)

    # we now have obj, and future passes through this code
    # will use the object from the cache.

Detailed Documentation
======================

More detailed documentation is available in the L{Client} class.
"""

How to convert a single char into an int

You can make use of atoi() function

#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[]){
    int num ;
    num = atoi(argv[1]);
    printf("\n%d", num);
}