Programs & Examples On #Permgen

In the Java Virtual Machine, the permanent generation (or permgen) is used for class definitions and associated metadata.

How do I properly set the permgen size?

So you are doing the right thing concerning "-XX:MaxPermSize=512m": it is indeed the correct syntax. You could try to set these options directly to the Catalyna server files so they are used on server start.

Maybe this post will help you!

How to make sure that Tomcat6 reads CATALINA_OPTS on Windows?

Increase permgen space

On Debian-like distributions you set that in /etc/default/tomcat[67]

How to clear PermGen space Error in tomcat

If tomcat is running as Windows Service neither CATALINA_OPTS nor JAVA_OPTS seems to have any effect.

You need to set it in Java options in GUI.

The below link explains it well

http://www.12robots.com/index.cfm/2010/10/8/Giving-more-memory-to-the-Tomcat-Service-in-Windows

"java.lang.OutOfMemoryError: PermGen space" in Maven build

When you say you increased MAVEN_OPTS, what values did you increase? Did you increase the MaxPermSize, as in example:

export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=128m"

(or on Windows:)

set MAVEN_OPTS=-Xmx512m -XX:MaxPermSize=128m

You can also specify these JVM options in each maven project separately.

PermGen elimination in JDK 8

Because the PermGen space was removed. Memory management has changed a bit.

java-8-permgen-metaspace

What does PermGen actually stand for?

If I remember correctly, the gen stands for generation, as in a generational garbage collector (that treats younger objects differently than mid-life and "permanent" objects). Principle of locality suggests that recently created objects will be wiped out first.

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

1) Increasing the PermGen Memory Size

The first thing one can do is to make the size of the permanent generation heap space bigger. This cannot be done with the usual –Xms(set initial heap size) and –Xmx(set maximum heap size) JVM arguments, since as mentioned, the permanent generation heap space is entirely separate from the regular Java Heap space, and these arguments set the space for this regular Java heap space. However, there are similar arguments which can be used(at least with the Sun/OpenJDK jvms) to make the size of the permanent generation heap bigger:

 -XX:MaxPermSize=128m

Default is 64m.

2) Enable Sweeping

Another way to take care of that for good is to allow classes to be unloaded so your PermGen never runs out:

-XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled

Stuff like that worked magic for me in the past. One thing though, there’s a significant performance trade off in using those, since permgen sweeps will make like an extra 2 requests for every request you make or something along those lines. You’ll need to balance your use with the tradeoffs.

You can find the details of this error.

http://faisalbhagat.blogspot.com/2014/09/java-outofmemoryerror-permgen.html

-XX:MaxPermSize with or without -XX:PermSize

-XX:PermSize specifies the initial size that will be allocated during startup of the JVM. If necessary, the JVM will allocate up to -XX:MaxPermSize.

How to call external JavaScript function in HTML

In Layman terms, you need to include external js file in your HTML file & thereafter you could directly call your JS method written in an external js file from HTML page. Follow the code snippet for insight:-

caller.html

<script type="text/javascript" src="external.js"></script>
<input type="button" onclick="letMeCallYou()" value="run external javascript">

external.js

function letMeCallYou()
{
    alert("Bazinga!!!  you called letMeCallYou")
}

Result : enter image description here

Groovy - How to compare the string?

This line:

if(str2==${str}){

Should be:

if( str2 == str ) {

The ${ and } will give you a parse error, as they should only be used inside Groovy Strings for templating

Can gcc output C code after preprocessing?

cpp is the preprocessor.

Run cpp filename.c to output the preprocessed code, or better, redirect it to a file with cpp filename.c > filename.preprocessed.

How do you create optional arguments in php?

The default value of the argument must be a constant expression. It can't be a variable or a function call.

If you need this functionality however:

function foo($foo, $bar = false)
{
    if(!$bar)
    {
        $bar = $foo;
    }
}

Assuming $bar isn't expected to be a boolean of course.

Get timezone from users browser using moment(timezone).js

Using Moment library, see their website -> https://momentjs.com/timezone/docs/#/using-timezones/converting-to-zone/

i notice they also user their own library in their website, so you can have a try using the browser console before installing it

moment().tz(String);

The moment#tz mutator will change the time zone and update the offset.

moment("2013-11-18").tz("America/Toronto").format('Z'); // -05:00
moment("2013-11-18").tz("Europe/Berlin").format('Z');   // +01:00

This information is used consistently in other operations, like calculating the start of the day.

var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.format();                     // 2013-11-18T11:55:00-05:00
m.startOf("day").format();      // 2013-11-18T00:00:00-05:00
m.tz("Europe/Berlin").format(); // 2013-11-18T06:00:00+01:00
m.startOf("day").format();      // 2013-11-18T00:00:00+01:00

Without an argument, moment#tz returns:

    the time zone name assigned to the moment instance or
    undefined if a time zone has not been set.

var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.tz();  // America/Toronto
var m = moment.tz("2013-11-18 11:55");
m.tz() === undefined;  // true

How to append text to a text file in C++?

You need to specify the append open mode like

#include <fstream>

int main() {  
  std::ofstream outfile;

  outfile.open("test.txt", std::ios_base::app); // append instead of overwrite
  outfile << "Data"; 
  return 0;
}

PostgreSQL: FOREIGN KEY/ON DELETE CASCADE

A foreign key with a cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete.

You are saying in a opposite way, this is not that when you delete from child table then records will be deleted from parent table.

UPDATE 1:

ON DELETE CASCADE option is to specify whether you want rows deleted in a child table when corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the default behaviour of the database server prevents you from deleting data in a table if other tables reference it.

If you specify this option, later when you delete a row in the parent table, the database server also deletes any rows associated with that row (foreign keys) in a child table. The principal advantage to the cascading-deletes feature is that it allows you to reduce the quantity of SQL statements you need to perform delete actions.

So it's all about what will happen when you delete rows from Parent table not from child table.

So in your case when user removes entries from CATs table then rows will be deleted from books table. :)

Hope this helps you :)

Setting the height of a SELECT in IE

There is a work-around for this (at least for multi-select):

  • set select size attribute to option list size (use JavaScript or set it to any large enough number)
  • set select max-height instead of height attribute to desired height (tested on IE9)

How do you serialize a model instance in Django?

If you're dealing with a list of model instances the best you can do is using serializers.serialize(), it gonna fit your need perfectly.

However, you are to face an issue with trying to serialize a single object, not a list of objects. That way, in order to get rid of different hacks, just use Django's model_to_dict (if I'm not mistaken, serializers.serialize() relies on it, too):

from django.forms.models import model_to_dict

# assuming obj is your model instance
dict_obj = model_to_dict( obj )

You now just need one straight json.dumps call to serialize it to json:

import json
serialized = json.dumps(dict_obj)

That's it! :)

In c, in bool, true == 1 and false == 0?

You neglected to say which version of C you are concerned about. Let's assume it's this one:

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf

As you can see by reading the specification, the standard definitions of true and false are 1 and 0, yes.

If your question is about a different version of C, or about non-standard definitions for true and false, then ask a more specific question.

How do I install the yaml package for Python?

following command will download pyyaml, which also includes yaml

pip install pyYaml

How can I convert a DateTime to the number of seconds since 1970?

That approach will be good if the date-time in question is in UTC, or represents local time in an area that has never observed daylight saving time. The DateTime difference routines do not take into account Daylight Saving Time, and consequently will regard midnight June 1 as being a multiple of 24 hours after midnight January 1. I'm unaware of anything in Windows that reports historical daylight-saving rules for the current locale, so I don't think there's any good way to correctly handle any time prior to the most recent daylight-saving rule change.

How to add hours to current date in SQL Server?

SELECT GETDATE() + (hours / 24.00000000000000000)

Adding to GETDATE() defaults to additional days, but it will also convert down to hours/seconds/milliseconds using decimal.

how to save DOMPDF generated content to file?

I have just used dompdf and the code was a little different but it worked.

Here it is:

require_once("./pdf/dompdf_config.inc.php");
$files = glob("./pdf/include/*.php");
foreach($files as $file) include_once($file);

$html =
      '<html><body>'.
      '<p>Put your html here, or generate it with your favourite '.
      'templating system.</p>'.
      '</body></html>';

    $dompdf = new DOMPDF();
    $dompdf->load_html($html);
    $dompdf->render();
    $output = $dompdf->output();
    file_put_contents('Brochure.pdf', $output);

Only difference here is that all of the files in the include directory are included.

Other than that my only suggestion would be to specify a full directory path for writing the file rather than just the filename.

How to copy data from one HDFS to another HDFS?

DistCp (distributed copy) is a tool used for copying data between clusters. It uses MapReduce to effect its distribution, error handling and recovery, and reporting. It expands a list of files and directories into input to map tasks, each of which will copy a partition of the files specified in the source list.

Usage: $ hadoop distcp <src> <dst>

example: $ hadoop distcp hdfs://nn1:8020/file1 hdfs://nn2:8020/file2

file1 from nn1 is copied to nn2 with filename file2

Distcp is the best tool as of now. Sqoop is used to copy data from relational database to HDFS and vice versa, but not between HDFS to HDFS.

More info:

There are two versions available - runtime performance in distcp2 is more compared to distcp

Detect all Firefox versions in JS

    <script type="text/javascript">
           var isChrome = /Chrome/.test(navigator.userAgent) && /Google 
                           Inc/.test(navigator.vendor);
           var isFirefox = 
                  navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
           if (isChrome) 
           { 
               document.write('<'+'link rel="stylesheet" 
                                  href="css/chrome.css" />');

           }
          else if(isFirefox)
           {
               document.write('<'+'link rel="stylesheet" 
                                  href="css/Firefox.css" />');
           }
           else
           {
                document.write('<'+'link rel="stylesheet" 
                                   href="css/IE.css" />');
            }

     </script>

This works perfect for IE,Firefox and Chrome.

How do I make an HTML text box show a hint when empty?

For jQuery users: naspinski's jQuery link seems broken, but try this one: http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/

You get a free jQuery plugin tutorial as a bonus. :)

FFMPEG mp4 from http live streaming m3u8 file?

Your command is completely incorrect. The output format is not rawvideo and you don't need the bitstream filter h264_mp4toannexb which is used when you want to convert the h264 contained in an mp4 to the Annex B format used by MPEG-TS for example. What you want to use instead is the aac_adtstoasc for the AAC streams.

ffmpeg -i http://.../playlist.m3u8 -c copy -bsf:a aac_adtstoasc output.mp4

How to convert char* to wchar_t*?

You're returning the address of a local variable allocated on the stack. When your function returns, the storage for all local variables (such as wc) is deallocated and is subject to being immediately overwritten by something else.

To fix this, you can pass the size of the buffer to GetWC, but then you've got pretty much the same interface as mbstowcs itself. Or, you could allocate a new buffer inside GetWC and return a pointer to that, leaving it up to the caller to deallocate the buffer.

List of all index & index columns in SQL Server DB

Using SQL Server 2016, this gives a complete list of all indexes, with an included dump of each table so you can see how the tables relate. It also shows columns included in covering indexes:

select t.name TableName, i.name IdxName, c.name ColName
    , ic.index_column_id ColPosition
    , i.type_desc Type
    , case when i.is_primary_key = 1 then 'Yes' else '' end [Primary?]
    , case when i.is_unique = 1 then 'Yes' else '' end [Unique?]
    , case when ic.is_included_column = 0 then '' else 'Yes - Included' end [CoveredColumn?]
    , 'indexes >>>>' [*indexes*], i.*, 'index_columns >>>>' [*index_columns*]
    , ic.*, 'tables >>>>' [*tables*]
    , t.*, 'columns >>>>' [*columns*], c.*
from sys.index_columns ic
join sys.tables t on t.object_id = ic.object_id
join sys.columns c on c.object_id = t.object_id and c.column_id = ic.column_id
join sys.indexes i on i.object_id = t.object_id and i.index_id = ic.index_id
order by TableName, IdxName, ColPosition

HTTP 404 Page Not Found in Web Api hosted in IIS 7.5

I spent lot's of time trying a lot of things to finally realise I was adding my web app not in Sites/Default Web Sites, but in another website binded to another port. Obviously trying localhost on port 80 would give a 404.

How to fix getImageData() error The canvas has been tainted by cross-origin data?

You won't be able to draw images directly from another server into a canvas and then use getImageData. It's a security issue and the canvas will be considered "tainted".

Would it work for you to save a copy of the image to your server using PHP and then just load the new image? For example, you could send the URL to the PHP script and save it to your server, then return the new filename to your javascript like this:

<?php //The name of this file in this example is imgdata.php

  $url=$_GET['url'];

  // prevent hackers from uploading PHP scripts and pwning your system
  if(!@is_array(getimagesize($url))){
    echo "path/to/placeholderImage.png";
    exit("wrong file type.");
  }

  $img = file_get_contents($url);

  $fn = substr(strrchr($url, "/"), 1);
  file_put_contents($fn,$img);
  echo $fn;

?>

You'd use the PHP script with some ajax javascript like this:

xi=new XMLHttpRequest();
xi.open("GET","imgdata.php?url="+yourImageURL,true);
xi.send();

xi.onreadystatechange=function() {
  if(xi.readyState==4 && xi.status==200) {
    img=new Image;
    img.onload=function(){ 
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    }
    img.src=xi.responseText;
  }
}

If you use getImageData on the canvas after that, it will work fine.

Alternatively, if you don't want to save the whole image, you could pass x & y coordinates to your PHP script and calculate the pixel's rgba value on that side. I think there are good libraries for doing that kind of image processing in PHP.

If you want to use this approach, let me know if you need help implementing it.

edit-1: peeps pointed out that the php script is exposed and allows the internet to potentially use it maliciously. there are a million ways to handle this, one of the simplest being some sort of URL obfuscation... i reckon secure php practices deserves a separate google ;P

edit-2: by popular demand, I've added a check to ensure it is an image and not a php script (from: PHP check if file is an image).

Replace text inside td using jQuery having td containing other elements

A bit late to the party, but JQuery change inner text but preserve html has at least one approach not mentioned here:

var $td = $("#demoTable td");
$td.html($td.html().replace('Tap on APN and Enter', 'new text'));

Without fixing the text, you could use (snother)[https://stackoverflow.com/a/37828788/1587329]:

var $a = $('#demoTable td');
var inner = '';
$a.children.html().each(function() {
    inner = inner + this.outerHTML;
});
$a.html('New text' + inner);

Can jQuery get all CSS styles associated with an element?

Two years late, but I have the solution you're looking for. Not intending to take credit form the original author, here's a plugin which I found works exceptionally well for what you need, but gets all possible styles in all browsers, even IE.

Warning: This code generates a lot of output, and should be used sparingly. It not only copies all standard CSS properties, but also all vendor CSS properties for that browser.

jquery.getStyleObject.js:

/*
 * getStyleObject Plugin for jQuery JavaScript Library
 * From: http://upshots.org/?p=112
 */

(function($){
    $.fn.getStyleObject = function(){
        var dom = this.get(0);
        var style;
        var returns = {};
        if(window.getComputedStyle){
            var camelize = function(a,b){
                return b.toUpperCase();
            };
            style = window.getComputedStyle(dom, null);
            for(var i = 0, l = style.length; i < l; i++){
                var prop = style[i];
                var camel = prop.replace(/\-([a-z])/g, camelize);
                var val = style.getPropertyValue(prop);
                returns[camel] = val;
            };
            return returns;
        };
        if(style = dom.currentStyle){
            for(var prop in style){
                returns[prop] = style[prop];
            };
            return returns;
        };
        return this.css();
    }
})(jQuery);

Basic usage is pretty simple, but he's written a function for that as well:

$.fn.copyCSS = function(source){
  var styles = $(source).getStyleObject();
  this.css(styles);
}

Hope that helps.

Format an Excel column (or cell) as Text in C#?

I've recently battled with this problem as well, and I've learned two things about the above suggestions.

  1. Setting the numberFormatting to @ causes Excel to left-align the value, and read it as if it were text, however, it still truncates the leading zero.
  2. Adding an apostrophe at the beginning results in Excel treating it as text and retains the zero, and then applies the default text format, solving both problems.

The misleading aspect of this is that you now have a different value in the cell. Fortuately, when you copy/paste or export to CSV, the apostrophe is not included.

Conclusion: use the apostrophe, not the numberFormatting in order to retain the leading zeros.

Python - Using regex to find multiple matches and print them out

Instead of using re.search use re.findall it will return you all matches in a List. Or you could also use re.finditer (which i like most to use) it will return an Iterator Object and you can just use it to iterate over all found matches.

line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
for match in re.finditer('<form>(.*?)</form>', line, re.S):
    print match.group(1)

Html.HiddenFor value property not getting set

Have you tried using a view model instead of ViewData? Strongly typed helpers that end with For and take a lambda expression cannot work with weakly typed structures such as ViewData.

Personally I don't use ViewData/ViewBag. I define view models and have my controller actions pass those view models to my views.

For example in your case I would define a view model:

public class MyViewModel
{
    [HiddenInput(DisplayValue = false)]
    public string CRN { get; set; }
}

have my controller action populate this view model:

public ActionResult Index()
{
    var model = new MyViewModel
    {
        CRN = "foo bar"
    };
    return View(model);
}

and then have my strongly typed view simply use an EditorFor helper:

@model MyViewModel
@Html.EditorFor(x => x.CRN)

which would generate me:

<input id="CRN" name="CRN" type="hidden" value="foo bar" />

in the resulting HTML.

Dynamically adding HTML form field using jQuery

You can add any type of HTML with methods like append and appendTo (among others):

jQuery manipulation methods

Example:

$('form#someform').append('<input type="text" name="something" id="something" />');

How to call a method after a delay in Android

I created simpler method to call this.

public static void CallWithDelay(long miliseconds, final Activity activity, final String methodName)
    {
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                try {
                    Method method =  activity.getClass().getMethod(methodName);
                    method.invoke(activity);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }, miliseconds);
    }

To use it, just call : .CallWithDelay(5000, this, "DoSomething");

How to use LINQ Distinct() with multiple fields

The Distinct() guarantees that there are no duplicates pair (CategoryId, CategoryName).

- exactly that

Anonymous types 'magically' implement Equals and GetHashcode

I assume another error somewhere. Case sensitivity? Mutable classes? Non-comparable fields?

Parsing command-line arguments in C

AnyOption is a C++ class for easy parsing of complex commandline options. It also parses options from a rsourcefile in option value pair format.

AnyOption implements the traditional POSIX style character options ( -n ) as well as the newer GNU style long options ( --name ). Or you can use a simpler long option version ( -name ) by asking to ignore the POSIX style options.

How to break out from a ruby block?

next and break seem to do the correct thing in this simplified example!

class Bar
  def self.do_things
      Foo.some_method(1..10) do |x|
            next if x == 2
            break if x == 9
            print "#{x} "
      end
  end
end

class Foo
    def self.some_method(targets, &block)
      targets.each do |target|
        begin
          r = yield(target)
        rescue  => x
          puts "rescue #{x}"
        end
     end
   end
end

Bar.do_things

output: 1 3 4 5 6 7 8

How can I link a photo in a Facebook album to a URL

Unfortunately, no. This feature is not available for facebook albums.

How to hide the keyboard when I press return key in a UITextField?

Try this in Swift,

Step 1: Set delegate as self to your textField

textField.delegate = self

Step 2: Add this UITextFieldDelegate below your class declaration,

extension YourClassName: UITextFieldDelegate {
    func textFieldShouldReturn(textField: UITextField) -> Bool {
         textField.resignFirstResponder()
        return true
    }
}

How to know when a web page was last updated?

Take a look at archive.org

You can find almost everything about the past of a website there.

Compiler error: "initializer element is not a compile-time constant"

A global variable has to be initialized to a constant value, like 4 or 0.0 or @"constant string" or nil. A object constructor, such as init, does not return a constant value.

If you want to have a global variable, you should initialize it to nil and then return it using a class method:

NSImage *segment = nil;

+ (NSImage *)imageSegment
{
    if (segment == nil) segment = [[NSImage alloc] initWithContentsOfFile:@"/user/asd.jpg"];
    return segment;
}

Boxplot in R showing the mean

abline(h=mean(x))

for a horizontal line (use v instead of h for vertical if you orient your boxplot horizontally), or

points(mean(x))

for a point. Use the parameter pch to change the symbol. You may want to colour them to improve visibility too.

Note that these are called after you have drawn the boxplot.

If you are using the formula interface, you would have to construct the vector of means. For example, taking the first example from ?boxplot:

boxplot(count ~ spray, data = InsectSprays, col = "lightgray")
means <- tapply(InsectSprays$count,InsectSprays$spray,mean)
points(means,col="red",pch=18)

If your data contains missing values, you might want to replace the last argument of the tapply function with function(x) mean(x,na.rm=T)

Why do I get a warning icon when I add a reference to an MEF plugin project?

Try closing and opening VS.

Seems silly but after 1 hour of following the above and finding everything lined up OK. I restarted VS 2017 and the problems were gone.

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

The window.navigator.platform property is not spoofed when the userAgent string is changed. I tested on my Mac if I change the userAgent to iPhone or Chrome Windows, navigator.platform remains MacIntel.

navigator.platform is not spoofed when the userAgent string is changed

The property is also read-only

navigator.platform is read-only


I could came up with the following table

Mac Computers

Mac68K Macintosh 68K system.
MacPPC Macintosh PowerPC system.
MacIntel Macintosh Intel system.

iOS Devices

iPhone iPhone.
iPod iPod Touch.
iPad iPad.


Modern macs returns navigator.platform == "MacIntel" but to give some "future proof" don't use exact matching, hopefully they will change to something like MacARM or MacQuantum in future.

var isMac = navigator.platform.toUpperCase().indexOf('MAC')>=0;

To include iOS that also use the "left side"

var isMacLike = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);
var isIOS = /(iPhone|iPod|iPad)/i.test(navigator.platform);

_x000D_
_x000D_
var is_OSX = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);_x000D_
var is_iOS = /(iPhone|iPod|iPad)/i.test(navigator.platform);_x000D_
_x000D_
var is_Mac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;_x000D_
var is_iPhone = navigator.platform == "iPhone";_x000D_
var is_iPod = navigator.platform == "iPod";_x000D_
var is_iPad = navigator.platform == "iPad";_x000D_
_x000D_
/* Output */_x000D_
var out = document.getElementById('out');_x000D_
if (!is_OSX) out.innerHTML += "This NOT a Mac or an iOS Device!";_x000D_
if (is_Mac) out.innerHTML += "This is a Mac Computer!\n";_x000D_
if (is_iOS) out.innerHTML += "You're using an iOS Device!\n";_x000D_
if (is_iPhone) out.innerHTML += "This is an iPhone!";_x000D_
if (is_iPod) out.innerHTML += "This is an iPod Touch!";_x000D_
if (is_iPad) out.innerHTML += "This is an iPad!";_x000D_
out.innerHTML += "\nPlatform: " + navigator.platform;
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_


Since most O.S. use the close button on the right, you can just move the close button to the left when the user is on a MacLike O.S., otherwise isn't a problem if you put it on the most common side, the right.

_x000D_
_x000D_
setTimeout(test, 1000); //delay for demonstration_x000D_
_x000D_
function test() {_x000D_
_x000D_
  var mac = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);_x000D_
_x000D_
  if (mac) {_x000D_
    document.getElementById('close').classList.add("left");_x000D_
  }_x000D_
}
_x000D_
#window {_x000D_
  position: absolute;_x000D_
  margin: 1em;_x000D_
  width: 300px;_x000D_
  padding: 10px;_x000D_
  border: 1px solid gray;_x000D_
  background-color: #DDD;_x000D_
  text-align: center;_x000D_
  box-shadow: 0px 1px 3px #000;_x000D_
}_x000D_
#close {_x000D_
  position: absolute;_x000D_
  top: 0px;_x000D_
  right: 0px;_x000D_
  width: 22px;_x000D_
  height: 22px;_x000D_
  margin: -12px;_x000D_
  box-shadow: 0px 1px 3px #000;_x000D_
  background-color: #000;_x000D_
  border: 2px solid #FFF;_x000D_
  border-radius: 22px;_x000D_
  color: #FFF;_x000D_
  text-align: center;_x000D_
  font: 14px"Comic Sans MS", Monaco;_x000D_
}_x000D_
#close.left{_x000D_
  left: 0px;_x000D_
}
_x000D_
<div id="window">_x000D_
  <div id="close">x</div>_x000D_
  <p>Hello!</p>_x000D_
  <p>If the "close button" change to the left side</p>_x000D_
  <p>you're on a Mac like system!</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://www.nczonline.net/blog/2007/12/17/don-t-forget-navigator-platform/

Convert UIImage to NSData and convert back to UIImage in Swift?

Now in Swift 4.2 you can use pngData() new instance method of UIImage to get the data from the image

let profileImage = UIImage(named:"profile")!
let imageData = profileImage.pngData()

How can I know if a process is running?

It depends on how reliable you want this function to be. If you want to know if the particular process instance you have is still running and available with 100% accuracy then you are out of luck. The reason being that from the managed process object there are only 2 ways to identify the process.

The first is the Process Id. Unfortunately, process ids are not unique and can be recycled. Searching the process list for a matching Id will only tell you that there is a process with the same id running, but it's not necessarily your process.

The second item is the Process Handle. It has the same problem though as the Id and it's more awkward to work with.

If you're looking for medium level reliability then checking the current process list for a process of the same ID is sufficient.

How should the ViewModel close the form?

public partial class MyWindow: Window
{
    public ApplicationSelection()
    {
      InitializeComponent();

      MyViewModel viewModel = new MyViewModel();

      DataContext = viewModel;

      viewModel.RequestClose += () => { Close(); };

    }
}

public class MyViewModel
{

  //...Your code...

  public event Action RequestClose;

  public virtual void Close()
  {
    if (RequestClose != null)
    {
      RequestClose();
    }
  }

  public void SomeFunction()
  {
     //...Do something...
     Close();
  }
}

How to allow only a number (digits and decimal point) to be typed in an input?

Expanding from gordy's answer:

Good job btw. But it also allowed + in the front. This will remove it.

    scope.$watch('inputValue', function (newValue, oldValue) {
        var arr = String(newValue).split("");
        if (arr.length === 0) return;
        if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.')) return;
        if (arr.length === 2 && newValue === '-.') return;
        if (isNaN(newValue)) {
            scope.inputValue = oldValue;
        }
        if (arr.length > 0) {
            if (arr[0] === "+") {
                scope.inputValue = oldValue;
            }
        }
    });

Correct Semantic tag for copyright info - html5

Put it inside your <footer> by all means, but the most fitting element is the small element.

The HTML5 spec for this says:

Small print typically features disclaimers, caveats, legal restrictions, or copyrights. Small print is also sometimes used for attribution, or for satisfying licensing requirements.

how to convert integer to string?

If you really want to use String:

NSString *number = [[NSString alloc] initWithFormat:@"%d", 123];

But I would recommend using NSNumber:

NSNumber *number = [[NSNumber alloc] initWithInt:123];

Then just add it to the array.

[array addObject:number];

Don't forget to release it after that, since you created it above.

[number release];

.gitignore exclude folder but include specific subfolder

@Chris Johnsen's answer is great, but with a newer versions of Git (1.8.2 or later), there is a double asterisk pattern you can leverage for a bit more shorthand solution:

# assuming the root folder you want to ignore is 'application'
application/**/*

# the subfolder(s) you want to track:
!application/language/gr/

This way you don't have to "unignore" parent directory of the subfolder you want to track.


With Git 2.17.0 (Not sure how early before this version. Possibly back to 1.8.2), using the ** pattern combined with excludes for each subdirectory leading up to your file(s) works. For example:

# assuming the root folder you want to ignore is 'application'
application/**

# Explicitly track certain content nested in the 'application' folder:
!application/language/
!application/language/gr/
!application/language/gr/** # Example adding all files & folder in the 'gr' folder
!application/language/gr/SomeFile.txt # Example adding specific file in the 'gr' folder

Styling the last td in a table with css

Javascript is the only viable way to do this client side (that is, CSS won't help you). In jQuery:

$("table td:last").css("border", "none");

take(1) vs first()

Here are three Observables A, B, and C with marble diagrams to explore the difference between first, take, and single operators:

first vs take vs single operators comparison

* Legend:
--o-- value
----! error
----| completion

Play with it at https://thinkrx.io/rxjs/first-vs-take-vs-single/ .

Already having all the answers, I wanted to add a more visual explanation

Hope it helps someone

How can you customize the numbers in an ordered list?

HTML5: Use the value attribute (no CSS needed)

Modern browsers will interpret the value attribute and will display it as you expect. See MDN documentation.

_x000D_
_x000D_
<ol>_x000D_
  <li value="3">This is item three.</li>_x000D_
  <li value="50">This is item fifty.</li>_x000D_
  <li value="100">This is item one hundred.</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Also have a look at the <ol> article on MDN, especially the documentation for the start and attribute.

collapse cell in jupyter notebook

You can create a cell and put the following code in it:

%%html
<style>
div.input {
    display:none;
}
</style>

Running this cell will hide all input cells. To show them back, you can use the menu to clear all outputs.

Otherwise you can try notebook extensions like below:

https://github.com/ipython-contrib/IPython-notebook-extensions/wiki/Home_3x

Creating a Zoom Effect on an image on hover using CSS?

Here you go.

Demo

http://jsfiddle.net/27Syr/4/

HTML

<div id="menu">

    <div class="fader">
        <div class="text">
            <p>Yay!</p>
        </div>
        <a href="http://stackoverflow.com/questions/15732643/jquery-masonry-and-css3/">
            <img class ="blog" src="http://s18.postimg.org/il7hbk7i1/image.png" alt="">
        </a>
    </div>

    <div class="fader">
        <div class="text">
            <p>Yay!</p>
        </div>
        <a href="http://stackoverflow.com/questions/15732643/jquery-masonry-and-css3/">
            <img class ="blog" src="http://s18.postimg.org/4st2fxgqh/image.png" alt="">
        </a>
    </div>

    <div class="fader">
        <div class="text">
            <p>Yay!</p>
        </div>
        <a href="http://stackoverflow.com/questions/15732643/jquery-masonry-and-css3/">
            <img class ="projects" src="http://s18.postimg.org/sxtrxn115/image.png" alt="">
        </a>
    </div>

    <div class="fader">
        <div class="text">
            <p>Yay!</p>
        </div>
        <a href="http://stackoverflow.com/questions/15732643/jquery-masonry-and-css3/">
            <img class ="blog" src="http://s18.postimg.org/5xn4lb37d/image.png" alt="">
        </a>
    </div>

</div>

CSS

#menu {
    text-align: center; }


.fader {
    /* Giving equal sizes to each element */
    width:    250px;
    height:   375px;

    /* Positioning elements in lines */
    display:  inline-block;

    /* This is necessary for position:absolute to work as desired */
    position: relative;

    /* Preventing zoomed images to grow outside their elements */
    overflow: hidden; }


    .fader img {
        /* Stretching the images to fill whole elements */
        width:       100%;
        height:      100%;

        /* Preventing blank space below the image */
        line-height: 0;

        /* A one-second transition was to disturbing for me */
        -webkit-transition: all 0.3s ease;
        -moz-transition:    all 0.3s ease;
        -o-transition:      all 0.3s ease;
        -ms-transition:     all 0.3s ease;
        transition:         all 0.3s ease; }

        .fader img:hover {
            /* Making images appear bigger and transparent on mouseover */
            opacity: 0.5;
            width:   120%;
            height:  120%; }

    .fader .text {
        /* Placing text behind images */
        z-index: -10;     

        /* Positioning text top-left conrner in the middle of elements */
        position: absolute;
        top:      50%;
        left:     50%; }

        .fader .text p {
            /* Positioning text contents 50% left and top relative
               to text container's top left corner */
            margin-top:  -50%; 
            margin-left: -50%; }

Suggestion

Instead of .fader { inline-block; } consider using some grid system. Based on your technology of preference, you can go Foundation, Susy, Masonry or their alternatives.

Setting up a cron job in Windows

There's pycron which I really as a Cron implementation for windows, but there's also the built in scheduler which should work just fine for what you need (Control Panel -> Scheduled Tasks -> Add Scheduled Task).

How to remove a class from elements in pure JavaScript?

Find elements:

var elements = document.getElementsByClassName('widget hover');

Since elements is a live array and reflects all dom changes you can remove all hover classes with a simple while loop:

while(elements.length > 0){
    elements[0].classList.remove('hover');
}

Hashmap holding different data types as values for instance Integer, String and Object

Define a class to store your data first

public class YourDataClass {

    private String messageType;
    private Timestamp timestamp;
    private int count;
    private int version;

    // your get/setters
    ...........
}

And then initialize your map:

Map<Integer, YourDataClass> map = new HashMap<Integer, YourDataClass>();

Adjust plot title (main) position

To summarize and explain visually how it works. Code construction is as follows:

par(mar = c(3,2,2,1))
barplot(...all parameters...)
title("Title text", adj = 0.5, line = 0)

explanation:

par(mar = c(low, left, top, right)) - margins of the graph area.

title("text" - title text
      adj  = from left (0) to right (1) with anything in between: 0.1, 0.2, etc...
      line = positive values move title text up, negative - down)

enter image description here

Login failed for user 'DOMAIN\MACHINENAME$'

I also had this error with a SQL Server authenticated user

I tried some of the fixes, but they did not work.

The solution in my case was to configure its "Server Authentication Mode" to allow SQL Server authentication, under Management Studio: Properties/Security.

Count how many rows have the same value

Try this Query

select NUM, count(1) as count 
from tbl 
where num = 1
group by NUM
--having count(1) (You condition)

SQL FIDDLE

Delete rows with blank values in one particular column

An easy approach would be making all the blank cells NA and only keeping complete cases. You might also look for na.omit examples. It is a widely discussed topic.

df[df==""]<-NA
df<-df[complete.cases(df),]

When to use AtomicReference in Java?

I won't talk much. Already my respected fellow friends have given their valuable input. The full fledged running code at the last of this blog should remove any confusion. It's about a movie seat booking small program in multi-threaded scenario.

Some important elementary facts are as follows. 1> Different threads can only contend for instance and static member variables in the heap space. 2> Volatile read or write are completely atomic and serialized/happens before and only done from memory. By saying this I mean that any read will follow the previous write in memory. And any write will follow the previous read from memory. So any thread working with a volatile will always see the most up-to-date value. AtomicReference uses this property of volatile.

Following are some of the source code of AtomicReference. AtomicReference refers to an object reference. This reference is a volatile member variable in the AtomicReference instance as below.

private volatile V value;

get() simply returns the latest value of the variable (as volatiles do in a "happens before" manner).

public final V get()

Following is the most important method of AtomicReference.

public final boolean  compareAndSet(V expect, V update) {
        return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
}

The compareAndSet(expect,update) method calls the compareAndSwapObject() method of the unsafe class of Java. This method call of unsafe invokes the native call, which invokes a single instruction to the processor. "expect" and "update" each reference an object.

If and only if the AtomicReference instance member variable "value" refers to the same object is referred to by "expect", "update" is assigned to this instance variable now, and "true" is returned. Or else, false is returned. The whole thing is done atomically. No other thread can intercept in between. As this is a single processor operation (magic of modern computer architecture), it's often faster than using a synchronized block. But remember that when multiple variables need to be updated atomically, AtomicReference won't help.

I would like to add a full fledged running code, which can be run in eclipse. It would clear many confusion. Here 22 users (MyTh threads) are trying to book 20 seats. Following is the code snippet followed by the full code.

Code snippet where 22 users are trying to book 20 seats.

for (int i = 0; i < 20; i++) {// 20 seats
            seats.add(new AtomicReference<Integer>());
        }
        Thread[] ths = new Thread[22];// 22 users
        for (int i = 0; i < ths.length; i++) {
            ths[i] = new MyTh(seats, i);
            ths[i].start();
        }

Following is the full running code.

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

public class Solution {

    static List<AtomicReference<Integer>> seats;// Movie seats numbered as per
                                                // list index

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        seats = new ArrayList<>();
        for (int i = 0; i < 20; i++) {// 20 seats
            seats.add(new AtomicReference<Integer>());
        }
        Thread[] ths = new Thread[22];// 22 users
        for (int i = 0; i < ths.length; i++) {
            ths[i] = new MyTh(seats, i);
            ths[i].start();
        }
        for (Thread t : ths) {
            t.join();
        }
        for (AtomicReference<Integer> seat : seats) {
            System.out.print(" " + seat.get());
        }
    }

    /**
     * id is the id of the user
     * 
     * @author sankbane
     *
     */
    static class MyTh extends Thread {// each thread is a user
        static AtomicInteger full = new AtomicInteger(0);
        List<AtomicReference<Integer>> l;//seats
        int id;//id of the users
        int seats;

        public MyTh(List<AtomicReference<Integer>> list, int userId) {
            l = list;
            this.id = userId;
            seats = list.size();
        }

        @Override
        public void run() {
            boolean reserved = false;
            try {
                while (!reserved && full.get() < seats) {
                    Thread.sleep(50);
                    int r = ThreadLocalRandom.current().nextInt(0, seats);// excludes
                                                                            // seats
                                                                            //
                    AtomicReference<Integer> el = l.get(r);
                    reserved = el.compareAndSet(null, id);// null means no user
                                                            // has reserved this
                                                            // seat
                    if (reserved)
                        full.getAndIncrement();
                }
                if (!reserved && full.get() == seats)
                    System.out.println("user " + id + " did not get a seat");
            } catch (InterruptedException ie) {
                // log it
            }
        }
    }

}    

How to truncate string using SQL server

If you only want to return a few characters of your long string, you can use:

select 
  left(col, 15) + '...' col
from yourtable

See SQL Fiddle with Demo.

This will return the first 15 characters of the string and then concatenates the ... to the end of it.

If you want to to make sure than strings less than 15 do not get the ... then you can use:

select 
  case 
    when len(col)>=15
    then left(col, 15) + '...' 
    else col end col
from yourtable

See SQL Fiddle with Demo

What is the difference between Numpy's array() and asarray() functions?

The differences are mentioned quite clearly in the documentation of array and asarray. The differences lie in the argument list and hence the action of the function depending on those parameters.

The function definitions are :

numpy.array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0)

and

numpy.asarray(a, dtype=None, order=None)

The following arguments are those that may be passed to array and not asarray as mentioned in the documentation :

copy : bool, optional If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtype, order, etc.).

subok : bool, optional If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default).

ndmin : int, optional Specifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement.

How do I print to the debug output window in a Win32 app?

If you need to see the output of an existing program that extensively used printf w/o changing the code (or with minimal changes) you can redefine printf as follows and add it to the common header (stdafx.h).

int print_log(const char* format, ...)
{
    static char s_printf_buf[1024];
    va_list args;
    va_start(args, format);
    _vsnprintf(s_printf_buf, sizeof(s_printf_buf), format, args);
    va_end(args);
    OutputDebugStringA(s_printf_buf);
    return 0;
}

#define printf(format, ...) \
        print_log(format, __VA_ARGS__)

Difference in days between two dates in Java?

Based on @Mad_Troll's answer, I developed this method.

I've run about 30 test cases against it, is the only method that handles sub day time fragments correctly.

Example: If you pass now & now + 1 millisecond that is still the same day. Doing 1-1-13 23:59:59.098 to 1-1-13 23:59:59.099 returns 0 days, correctly; allot of the other methods posted here will not do this correctly.

Worth noting it does not care about which way you put them in, If your end date is before your start date it will count backwards.

/**
 * This is not quick but if only doing a few days backwards/forwards then it is very accurate.
 *
 * @param startDate from
 * @param endDate   to
 * @return day count between the two dates, this can be negative if startDate is after endDate
 */
public static long daysBetween(@NotNull final Calendar startDate, @NotNull final Calendar endDate) {

    //Forwards or backwards?
    final boolean forward = startDate.before(endDate);
    // Which direction are we going
    final int multiplier = forward ? 1 : -1;

    // The date we are going to move.
    final Calendar date = (Calendar) startDate.clone();

    // Result
    long daysBetween = 0;

    // Start at millis (then bump up until we go back a day)
    int fieldAccuracy = 4;
    int field;
    int dayBefore, dayAfter;
    while (forward && date.before(endDate) || !forward && endDate.before(date)) {
        // We start moving slowly if no change then we decrease accuracy.
        switch (fieldAccuracy) {
            case 4:
                field = Calendar.MILLISECOND;
                break;
            case 3:
                field = Calendar.SECOND;
                break;
            case 2:
                field = Calendar.MINUTE;
                break;
            case 1:
                field = Calendar.HOUR_OF_DAY;
                break;
            default:
            case 0:
                field = Calendar.DAY_OF_MONTH;
                break;
        }
        // Get the day before we move the time, Change, then get the day after.
        dayBefore = date.get(Calendar.DAY_OF_MONTH);
        date.add(field, multiplier);
        dayAfter = date.get(Calendar.DAY_OF_MONTH);

        // This shifts lining up the dates, one field at a time.
        if (dayBefore == dayAfter && date.get(field) == endDate.get(field))
            fieldAccuracy--;
        // If day has changed after moving at any accuracy level we bump the day counter.
        if (dayBefore != dayAfter) {
            daysBetween += multiplier;
        }
    }
    return daysBetween;
}

You can remove the @NotNull annotations, these are used by Intellij to do code analysis on the fly

Identify duplicates in a List

create a Map<Integer,Integer>, iterate the list, if an element is in the map, increase it's value, otherwise add it to the map with key=1
iterate the map, and add to the lists all elements with key>=2

public static void main(String[] args) {
        List<Integer> list = new LinkedList<Integer>();
        list.add(1);
        list.add(1);
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(3);
        Map<Integer,Integer> map = new HashMap<Integer, Integer>();
        for (Integer x : list) { 
            Integer val = map.get(x);
            if (val == null) { 
                map.put(x,1);
            } else {
                map.remove(x);
                map.put(x,val+1);
            }
        }
        List<Integer> result = new LinkedList<Integer>();
        for (Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() > 1) {
                result.add(entry.getKey());
            }
        }
        for (Integer x : result) { 
            System.out.println(x);
        }

    }

Getting min and max Dates from a pandas dataframe

min(df['some_property'])
max(df['some_property'])

The built-in functions work well with Pandas Dataframes.

Need a row count after SELECT statement: what's the optimal SQL approach?

If you're using SQL Server, after your query you can select the @@RowCount function (or if your result set might have more than 2 billion rows use the RowCount_Big() function). This will return the number of rows selected by the previous statement or number of rows affected by an insert/update/delete statement.

SELECT my_table.my_col
  FROM my_table
 WHERE my_table.foo = 'bar'

SELECT @@Rowcount

Or if you want to row count included in the result sent similar to Approach #2, you can use the the OVER clause.

SELECT my_table.my_col,
    count(*) OVER(PARTITION BY my_table.foo) AS 'Count'
  FROM my_table
 WHERE my_table.foo = 'bar'

Using the OVER clause will have much better performance than using a subquery to get the row count. Using the @@RowCount will have the best performance because the there won't be any query cost for the select @@RowCount statement

Update in response to comment: The example I gave would give the # of rows in partition - defined in this case by "PARTITION BY my_table.foo". The value of the column in each row is the # of rows with the same value of my_table.foo. Since your example query had the clause "WHERE my_table.foo = 'bar'", all rows in the resultset will have the same value of my_table.foo and therefore the value in the column will be the same for all rows and equal (in this case) this the # of rows in the query.

Here is a better/simpler example of how to include a column in each row that is the total # of rows in the resultset. Simply remove the optional Partition By clause.

SELECT my_table.my_col, count(*) OVER() AS 'Count'
  FROM my_table
 WHERE my_table.foo = 'bar'

Convert Data URI to File then append to FormData

My preferred way is canvas.toBlob()

But anyhow here is yet another way to convert base64 to a blob using fetch ^^,

_x000D_
_x000D_
var url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="_x000D_
_x000D_
fetch(url)_x000D_
.then(res => res.blob())_x000D_
.then(blob => {_x000D_
  var fd = new FormData()_x000D_
  fd.append('image', blob, 'filename')_x000D_
  _x000D_
  console.log(blob)_x000D_
_x000D_
  // Upload_x000D_
  // fetch('upload', {method: 'POST', body: fd})_x000D_
})
_x000D_
_x000D_
_x000D_

What are .dex files in Android?

dex file is a file that is executed on the Dalvik VM.

Dalvik VM includes several features for performance optimization, verification, and monitoring, one of which is Dalvik Executable (DEX).

Java source code is compiled by the Java compiler into .class files. Then the dx (dexer) tool, part of the Android SDK processes the .class files into a file format called DEX that contains Dalvik byte code. The dx tool eliminates all the redundant information that is present in the classes. In DEX all the classes of the application are packed into one file. The following table provides comparison between code sizes for JVM jar files and the files processed by the dex tool.

The table compares code sizes for system libraries, web browser applications, and a general purpose application (alarm clock app). In all cases dex tool reduced size of the code by more than 50%.

enter image description here

In standard Java environments each class in Java code results in one .class file. That means, if the Java source code file has one public class and two anonymous classes, let’s say for event handling, then the java compiler will create total three .class files.

The compilation step is same on the Android platform, thus resulting in multiple .class files. But after .class files are generated, the “dx” tool is used to convert all .class files into a single .dex, or Dalvik Executable, file. It is the .dex file that is executed on the Dalvik VM. The .dex file has been optimized for memory usage and the design is primarily driven by sharing of data.

Download pdf file using jquery ajax

I am newbie and most of the code is from google search. I got my pdf download working with the code below (trial and error play). Thank you for code tips (xhrFields) above.

$.ajax({
            cache: false,
            type: 'POST',
            url: 'yourURL',
            contentType: false,
            processData: false,
            data: yourdata,
             //xhrFields is what did the trick to read the blob to pdf
            xhrFields: {
                responseType: 'blob'
            },
            success: function (response, status, xhr) {

                var filename = "";                   
                var disposition = xhr.getResponseHeader('Content-Disposition');

                 if (disposition) {
                    var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                    var matches = filenameRegex.exec(disposition);
                    if (matches !== null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                } 
                var linkelem = document.createElement('a');
                try {
                                           var blob = new Blob([response], { type: 'application/octet-stream' });                        

                    if (typeof window.navigator.msSaveBlob !== 'undefined') {
                        //   IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                        window.navigator.msSaveBlob(blob, filename);
                    } else {
                        var URL = window.URL || window.webkitURL;
                        var downloadUrl = URL.createObjectURL(blob);

                        if (filename) { 
                            // use HTML5 a[download] attribute to specify filename
                            var a = document.createElement("a");

                            // safari doesn't support this yet
                            if (typeof a.download === 'undefined') {
                                window.location = downloadUrl;
                            } else {
                                a.href = downloadUrl;
                                a.download = filename;
                                document.body.appendChild(a);
                                a.target = "_blank";
                                a.click();
                            }
                        } else {
                            window.location = downloadUrl;
                        }
                    }   

                } catch (ex) {
                    console.log(ex);
                } 
            }
        });

Returning unique_ptr from functions

I think it's perfectly explained in item 25 of Scott Meyers' Effective Modern C++. Here's an excerpt:

The part of the Standard blessing the RVO goes on to say that if the conditions for the RVO are met, but compilers choose not to perform copy elision, the object being returned must be treated as an rvalue. In effect, the Standard requires that when the RVO is permitted, either copy elision takes place or std::move is implicitly applied to local objects being returned.

Here, RVO refers to return value optimization, and if the conditions for the RVO are met means returning the local object declared inside the function that you would expect to do the RVO, which is also nicely explained in item 25 of his book by referring to the standard (here the local object includes the temporary objects created by the return statement). The biggest take away from the excerpt is either copy elision takes place or std::move is implicitly applied to local objects being returned. Scott mentions in item 25 that std::move is implicitly applied when the compiler choose not to elide the copy and the programmer should not explicitly do so.

In your case, the code is clearly a candidate for RVO as it returns the local object p and the type of p is the same as the return type, which results in copy elision. And if the compiler chooses not to elide the copy, for whatever reason, std::move would've kicked in to line 1.

Pure Javascript listen to input value change

Actually, the ticked answer is exactly right, but the answer can be in ES6 shape:

HTMLInputElementObject.oninput = () => {
  console.log('run'); // Do something
}

Or can be written like below:

HTMLInputElementObject.addEventListener('input', (evt) => {
  console.log('run'); // Do something
});

Should composer.lock be committed to version control?

Yes obviously.

That’s because a locally installed composer will give first preference to composer.lock file over composer.json.

If lock file is not available in vcs the composer will point to composer.json file to install latest dependencies or versions.

The file composer.lock maintains dependency in more depth i.e it points to the actual commit of the version of the package we include in our software, hence this is one of the most important files which handles the dependency more finely.

Create a git patch from the uncommitted changes in the current working directory

I like:

git format-patch HEAD~<N>

where <N> is number of last commits to save as patches.

The details how to use the command are in the DOC

UPD
Here you can find how to apply them then.

UPD For those who did not get the idea of format-patch
Add alias:

git config --global alias.make-patch '!bash -c "cd ${GIT_PREFIX};git add .;git commit -m ''uncommited''; git format-patch HEAD~1; git reset HEAD~1"'

Then at any directory of your project repository run:

git make-patch

This command will create 0001-uncommited.patch at your current directory. Patch will contain all the changes and untracked files that are visible to next command:

git status .

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

After done trying everything that I found on this issue, in eclipse,

I selected my project --> right click --> Run as --> Maven generate-sources

enter image description here

Then I re-ran my TestNG project and it ran perfectly fine without any issues.Hope that helps :)

Basic http file downloading and saving to disk in python?

I use wget.

Simple and good library if you want to example?

import wget

file_url = 'http://johndoe.com/download.zip'

file_name = wget.download(file_url)

wget module support python 2 and python 3 versions

Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell

You can leverage Conditional Formatting as follows.

  1. In cell H8 select Format > Conditional Formatting...
  2. In Condition1, select Formula Is in first drop down menu
  3. In the next textbox type =I8="Elementary"
  4. Select Format... and select the color you want etc.
  5. Select Add>> and repeat steps 1 to 4

Note that you can only have (in excel 2003) three separate conditions so you will only be able to have different formatting for three items in the drop down menu. If the idea is to make them visually distinct then (maybe) having no color for one of the selections is not a problem?

If the cell is never blank, you can use format (not conditional) to get 4 distinct visuals.

Converting Date and Time To Unix Timestamp

You can use Date.getTime() function, or the Date object itself which when divided returns the time in milliseconds.

var d = new Date();

d/1000
> 1510329641.84

d.getTime()/1000
> 1510329641.84

Return a value of '1' a referenced cell is empty

=if(a1="","1","0")

In this formula if the cell is empty then the result would be 1 else it would be 0

Getting result of dynamic SQL into a variable for sql-server

DECLARE @sqlCommand nvarchar(1000)
DECLARE @city varchar(75)
declare @counts int
SET @city = 'New York'
SET @sqlCommand = 'SELECT @cnt=COUNT(*) FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75),@cnt int OUTPUT', @city = @city, @cnt=@counts OUTPUT
select @counts as Counts

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

I had the same problem, and here's how it was fixed:

  1. My .jsp was calling attributes that I had not yet defined in the servlet.
  2. I had two column names that I was passing into an object through ResultSet (getString("columnName")) that didn't match the column names in my database.

I'm not exactly sure which one fixed the problem, but it worked. Also, be sure that you create a new Statement and ResultSet for each table query.

CREATE TABLE LIKE A1 as A2

CREATE TABLE new_table LIKE old_table;

or u can use this

CREATE TABLE new_table as SELECT * FROM old_table WHERE 1 GROUP BY [column to remove duplicates by];

How to plot ROC curve in Python

Here are two ways you may try, assuming your model is an sklearn predictor:

import sklearn.metrics as metrics
# calculate the fpr and tpr for all thresholds of the classification
probs = model.predict_proba(X_test)
preds = probs[:,1]
fpr, tpr, threshold = metrics.roc_curve(y_test, preds)
roc_auc = metrics.auc(fpr, tpr)

# method I: plt
import matplotlib.pyplot as plt
plt.title('Receiver Operating Characteristic')
plt.plot(fpr, tpr, 'b', label = 'AUC = %0.2f' % roc_auc)
plt.legend(loc = 'lower right')
plt.plot([0, 1], [0, 1],'r--')
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.show()

# method II: ggplot
from ggplot import *
df = pd.DataFrame(dict(fpr = fpr, tpr = tpr))
ggplot(df, aes(x = 'fpr', y = 'tpr')) + geom_line() + geom_abline(linetype = 'dashed')

or try

ggplot(df, aes(x = 'fpr', ymin = 0, ymax = 'tpr')) + geom_line(aes(y = 'tpr')) + geom_area(alpha = 0.2) + ggtitle("ROC Curve w/ AUC = %s" % str(roc_auc)) 

What is "entropy and information gain"?

When I was implementing an algorithm to calculate the entropy of an image I found these links, see here and here.

This is the pseudo-code I used, you'll need to adapt it to work with text rather than images but the principles should be the same.

//Loop over image array elements and count occurrences of each possible
//pixel to pixel difference value. Store these values in prob_array
for j = 0, ysize-1 do $
    for i = 0, xsize-2 do begin
       diff = array(i+1,j) - array(i,j)
       if diff lt (array_size+1)/2 and diff gt -(array_size+1)/2 then begin
            prob_array(diff+(array_size-1)/2) = prob_array(diff+(array_size-1)/2) + 1
       endif
     endfor

//Convert values in prob_array to probabilities and compute entropy
n = total(prob_array)

entrop = 0
for i = 0, array_size-1 do begin
    prob_array(i) = prob_array(i)/n

    //Base 2 log of x is Ln(x)/Ln(2). Take Ln of array element
    //here and divide final sum by Ln(2)
    if prob_array(i) ne 0 then begin
        entrop = entrop - prob_array(i)*alog(prob_array(i))
    endif
endfor

entrop = entrop/alog(2)

I got this code from somewhere, but I can't dig out the link.

how to check if object already exists in a list

If it's maintainable to use those 2 properties, you could:

bool alreadyExists = myList.Any(x=> x.Foo=="ooo" && x.Bar == "bat");

Checking network connection

A modern portable solution with requests:

import requests

def internet():
    """Detect an internet connection."""

    connection = None
    try:
        r = requests.get("https://google.com")
        r.raise_for_status()
        print("Internet connection detected.")
        connection = True
    except:
        print("Internet connection not detected.")
        connection = False
    finally:
        return connection

Or, a version that raises an exception:

import requests
from requests.exceptions import ConnectionError

def internet():
    """Detect an internet connection."""

    try:
        r = requests.get("https://google.com")
        r.raise_for_status()
        print("Internet connection detected.")
    except ConnectionError as e:
        print("Internet connection not detected.")
        raise e

How to initialize a list of strings (List<string>) with many string values

Move round brackets like this:

var optionList = new List<string>(){"AdditionalCardPersonAdressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"};

how to make label visible/invisible?

Change visible="false" to style="visibility:hidden" on your tags..


or better use a class to show/hide the labels..

.hidden{
   visibility:hidden;
}

then on your labels add class="hidden"

and with your script remove the class

document.getElementById("endTimeLabel").className = 'hidden'; // to hide

and

document.getElementById("endTimeLabel").className = ''; // to show

How to draw interactive Polyline on route google maps v2 android

You can use this method to draw polyline on googleMap

// Draw polyline on map
public void drawPolyLineOnMap(List<LatLng> list) {
    PolylineOptions polyOptions = new PolylineOptions();
    polyOptions.color(Color.RED);
    polyOptions.width(5);
    polyOptions.addAll(list);

    googleMap.clear();
    googleMap.addPolyline(polyOptions);

    LatLngBounds.Builder builder = new LatLngBounds.Builder();
    for (LatLng latLng : list) {
        builder.include(latLng);
    }

    final LatLngBounds bounds = builder.build();

    //BOUND_PADDING is an int to specify padding of bound.. try 100.
    CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, BOUND_PADDING);
    googleMap.animateCamera(cu);
}

You need to add this line in your gradle in case you haven't.

compile 'com.google.android.gms:play-services-maps:8.4.0'

Using global variables in a function

You can use a global variable within other functions by declaring it as global within each function that assigns a value to it:

globvar = 0

def set_globvar_to_one():
    global globvar    # Needed to modify global copy of globvar
    globvar = 1

def print_globvar():
    print(globvar)     # No need for global declaration to read value of globvar

set_globvar_to_one()
print_globvar()       # Prints 1

I imagine the reason for it is that, since global variables are so dangerous, Python wants to make sure that you really know that's what you're playing with by explicitly requiring the global keyword.

See other answers if you want to share a global variable across modules.

Why is a primary-foreign key relation required when we can join without it?

A primary key is not required. A foreign key is not required either. You can construct a query joining two tables on any column you wish as long as the datatypes either match or are converted to match. No relationship needs to explicitly exist.

To do this you use an outer join:

select tablea.code, tablea.name, tableb.location from tablea left outer join 
tableb on tablea.code = tableb.code

join with out relation

SQL join

Store images in a MongoDB database

http://blog.mongodb.org/post/183689081/storing-large-objects-and-files-in-mongodb

There is a Mongoose plugin available on NPM called mongoose-file. It lets you add a file field to a Mongoose Schema for file upload. I have never used it but it might prove useful. If the images are very small you could Base64 encode them and save the string to the database.

Storing some small (under 1MB) files with MongoDB in NodeJS WITHOUT GridFS

How to control the width and height of the default Alert Dialog in Android?

Ok , I can control the width and height using Builder class. I used

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(layout);
builder.setTitle("Title");
AlertDialog alertDialog = builder.create();
alertDialog.getWindow().setLayout(600, 400); //Controlling width and height.
alertDialog.show();

How to hide form code from view code/inspect element browser?

This code removes the inner html of an element from the dom when the debugger is open (tested in Chrome and IE)

var currentInnerHtml;
var element = new Image();
var elementWithHiddenContent = document.querySelector("#element-to-hide");
var innerHtml = elementWithHiddenContent.innerHTML;

element.__defineGetter__("id", function() {
    currentInnerHtml = "";
});

setInterval(function() {
    currentInnerHtml = innerHtml;
    console.log(element);
    console.clear();
    elementWithHiddenContent.innerHTML = currentInnerHtml;
}, 1000);

Here #element-to-hide is the id of element you want to hide. It is a hack, but I hope it helps you.

How to compile and run C files from within Notepad++ using NppExec plugin?

You can actually compile and run C code even without the use of nppexec plugins. If you use MingW32 C compiler, use g++ for C++ language and gcc for C language.

Paste this code into the notepad++ run section

cmd /k cd $(CURRENT_DIRECTORY) && gcc $(FILE_NAME) -o $(NAME_PART).exe  && $(NAME_PART).exe && pause

It will compile your C code into exe and run it immediately. It's like a build and run feature in CodeBlock. All these are done with some cmd knowledge.

Explanation:

  1. cmd /k is used for testing.
  2. cd $(CURRENT_DIRECTORY)
    • change directory to where file is located
  3. && operators
    • to chain your commands in a single line
  4. gcc $(FILE_NAME)
    • use GCC to compile File with its file extension.
  5. -o $(NAME_PART).exe
    • this flag allow you to choose your output filename. $(NAME_PART) does not include file extension.
  6. $(NAME_PART).exe
    • this alone runs your program
  7. pause
    • this command is used to keep your console open after file has been executed.

For more info on notepad++ commands, go to

http://docs.notepad-plus-plus.org/index.php/External_Programs

Get timezone from DateTime

You could use TimeZoneInfo class

The TimeZone class recognizes local time zone, and can convert times between Coordinated Universal Time (UTC) and local time. A TimeZoneInfo object can represent any time zone, and methods of the TimeZoneInfo class can be used to convert the time in one time zone to the corresponding time in any other time zone. The members of the TimeZoneInfo class support the following operations:

  1. Retrieving a time zone that is already defined by the operating system.

  2. Enumerating the time zones that are available on a system.

  3. Converting times between different time zones.

  4. Creating a new time zone that is not already defined by the operating system.

    Serializing a time zone for later retrieval.

Calculating the position of points in a circle

The angle between each of your points is going to be 2Pi/x so you can say that for points n= 0 to x-1 the angle from a defined 0 point is 2nPi/x.

Assuming your first point is at (r,0) (where r is the distance from the centre point) then the positions relative to the central point will be:

rCos(2nPi/x),rSin(2nPi/x)

Large Numbers in Java

Checkout BigDecimal and BigInteger.

Changing Placeholder Text Color with Swift

In my case, I use Swift 4

I create extension for UITextField

extension UITextField {
    func placeholderColor(color: UIColor) {
        let attributeString = [
            NSAttributedStringKey.foregroundColor: color.withAlphaComponent(0.6),
            NSAttributedStringKey.font: self.font!
            ] as [NSAttributedStringKey : Any]
        self.attributedPlaceholder = NSAttributedString(string: self.placeholder!, attributes: attributeString)
    }
}

yourField.placeholderColor(color: UIColor.white)

Inserting a Python datetime.datetime object into MySQL

You are most likely getting the TypeError because you need quotes around the datecolumn value.

Try:

now = datetime.datetime(2009, 5, 5)

cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s, '%s')",
               ("name", 4, now))

With regards to the format, I had success with the above command (which includes the milliseconds) and with:

now.strftime('%Y-%m-%d %H:%M:%S')

Hope this helps.

JavaScript: Difference between .forEach() and .map()

One thing to point out is that foreach skips uninitialized values while map does not.

var arr = [1, , 3];

arr.forEach(function(element) {
    console.log(element);
});
//Expected output: 1 3

console.log(arr.map(element => element));
//Expected output: [1, undefined, 3];

Getting HTTP code in PHP using curl

Try PHP's "get_headers" function.

Something along the lines of:

<?php
    $url = 'http://www.example.com';
    print_r(get_headers($url));
    print_r(get_headers($url, 1));
?>

Could not determine the dependencies of task ':app:crashlyticsStoreDeobsDebug' if I enable the proguard

In place of 1.+ use the latest version of crashlytics -

 dependencies {
        classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:1.+'
    }

you should use this way -

dependencies {
            classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:2.6.8'
        }

your problem will be resolved for sure. Happy coding !!

How to Lazy Load div background images

I had to deal with this for my responsive website. I have many different backgrounds for the same elements to deal with different screen widths. My solution is very simple, keep all your images scoped to a css selector, like "zoinked".

The logic:

If user scrolls, then load in styles with background images associated with them. Done!

Here's what I wrote in a library I call "zoinked" I dunno why. It just happened ok?

(function(window, document, undefined) {   var Z = function() {
    this.hasScrolled = false;

    if (window.addEventListener) {
      window.addEventListener("scroll", this, false);
    } else {
      this.load();
    }   };
     Z.prototype.handleEvent = function(e) {
    if ($(window).scrollTop() > 2) {
      this.hasScrolled = true;
      window.removeEventListener("scroll", this);
      this.load();
    }   };
     Z.prototype.load = function() {
    $(document.body).addClass("zoinked");   };
     window.Zoink = Z; 
})(window, document);

For the CSS I'll have all my styles like this:

.zoinked #graphic {background-image: url(large.jpg);}

@media(max-width: 480px) {.zoinked #graphic {background-image: url(small.jpg);}}

My technique with this is to load all the images after the top ones as soon as the user starts to scroll. If you wanted more control you could make the "zoinking" more intelligent.

"Couldn't read dependencies" error with npm

I ran into this problem after I cloned a git repository to a directory, renamed the directory, then tried to run npm install. I'm not sure what the problem was, but something was bungled. Deleting everything, re-cloning (this time with the correct directory name), and then running npm install resolved my issue.

How to provide shadow to Button

If you are targeting pre-Lollipop devices, you can use Shadow-Layout, since it easy and you can use it in different kind of layouts.


Add shadow-layout to your Gradle file:

dependencies {
    compile 'com.github.dmytrodanylyk.shadow-layout:library:1.0.1'
}


At the top the xml layout where you have your button, add to the top:

xmlns:app="http://schemas.android.com/apk/res-auto"

it will make available the custom attributes.


Then you put a shadow layout around you Button:

<com.dd.ShadowLayout
        android:layout_marginTop="16dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:sl_shadowRadius="4dp"
        app:sl_shadowColor="#AA000000"
        app:sl_dx="0dp"
        app:sl_dy="0dp"
        app:sl_cornerRadius="56dp"> 

       <YourButton
          .... />

</com.dd.ShadowLayout>

You can then tweak the app: settings to match your required shadow.

Hope it helps.

Linux find file names with given string recursively

use ack its simple. just type ack <string to be searched>

JSON Invalid UTF-8 middle byte

This awnser solved my problem. Below is a copy of it:

Make sure to start you JVM with -Dfile.encoding=UTF-8. You JVM defaults to the operating system charset

This is a JVM argument which could be added, for example, either to JBoss standalone or JBoss running from Eclipse.

In my case, this problem happened isolatelly on only one of my team people's computer. All the others was working without this problem.

How to set default value for column of new created table from select statement in 11g

You can specify the constraints and defaults in a CREATE TABLE AS SELECT, but the syntax is as follows

create table t1 (id number default 1 not null);
insert into t1 (id) values (2);

create table t2 (id default 1 not null)
as select * from t1;

That is, it won't inherit the constraints from the source table/select. Only the data type (length/precision/scale) is determined by the select.

How to round double to nearest whole number and then convert to a float?

Here is a quick example:

public class One {

    /**
     * @param args
     */
    public static void main(String[] args) {

        double a = 4.56777;
        System.out.println( new Float( Math.round(a)) );

    }

}

the result and output will be: 5.0
the closest upper bound Float to the starting value of double a = 4.56777
in this case the use of round is recommended since it takes in double values and provides whole long values

Regards

Can anyone explain IEnumerable and IEnumerator to me?

Explanation via Analogy + Code Walkthrough

First an explanation without code, then I'll add it in later.

Let's say you are running an airline company. And in each plane you want to know information about the passengers flying in the plane. Basically you want to be able to "traverse" the plane. In other words, you want to be able to start at the front seat, and to then work your way towards the back of the plane, asking passengers some information: who they are, where they are from etc. An aeroplane can only do this, if it is:

  1. countable, and
  2. if it has a counter.

Why these requirements? Because that's what the interface requires.

If this is information overload, all you need to know is that you want to be able to ask each passenger in the plane some questions, starting from the first and making your way to the last.

What does countable mean?

If an airline is "countable", this means that there MUST be a flight attendant present on the plane, whose sole job is to count - and this flight attendant MUST count in a very specific manner:

  1. The counter/flight attendant MUST start before the first passenger (at the front of everyone where they demo safety, how to put the life jacket on etc).
  2. He/she (i.e. the flight attendant) MUST "move next" up the aisle to the first seat.
  3. He/she is to then record: (i) who the person is in the seat, and (ii) their current location in the aisle.

Counting Procedures

The captain of the airline wants a report on every passenger as and when they are investigated or counted. So after speaking to the person in the first seat, the flight-attendant/counter then reports to the captain, and when the report is given, the counter remembers his/her exact position in the aisle and continues counting right where he/she left off.

In this manner the captain is always able to have information on the current person being investigated. That way, if he finds out that this individual likes Manchester City, then he can give that passenger preferential treatment etc.

  • The counter keeps going till he reaches the end of the plane.

Let's tie this with the IEnumerables

  • An enumerable is just a collection of passengers on a plane. The Civil Aviation Law - these are basically the rules which all IEnumerables must follow. Everytime the airline attendant goes to the captain with the passeger information, we are basically 'yielding' the passenger to the captain. The captain can basically do whatever he wants with the passenger - except rearranging the passengers on the plane. In this case, they are given preferential treatment if they follow Manchester City (ugh!)

     foreach (Passenger passenger in Plane)
     // the airline hostess is now at the front of the plane
     // and slowly making her way towards the back
     // when she get to a particular passenger she gets some information
     // about the passenger and then immediately heads to the cabin
     // to let the captain decide what to do with it
     { // <---------- Note the curly bracket that is here.
         // we are now cockpit of the plane with the captain.
         // the captain wants to give the passenger free 
         // champaign if they support manchester city
         if (passenger.supports_mancestercity())
         {
             passenger.getFreeChampaign();
         } else
         {
             // you get nothing! GOOD DAY SIR!
         }
     } //  <---- Note the curly bracket that is here!
           the hostess has delivered the information 
           to the captain and goes to the next person
           on the plane (if she has not reached the 
           end of the plane)
    

Summary

In other words, something is countable if it has a counter. And counter must (basically): (i) remember its place (state), (ii) be able to move next, (iii) and know about the current person he is dealing with.

Enumerable is just a fancy word for "countable". In other words, an enumerable allows you to 'enumerate' (i.e. count).

Is there a kind of Firebug or JavaScript console debug for Android?

"USB Web debugging" is one option

"printing it on the screen" another.

But I prefer remote debugging through 'adobe edge inspect' formally known as adobe shadow. It uses weinre internally (=WEb INspect REmote)

You just install it + a small plugin in the browser (Chrome) and a free app you can download in the play-store. Then you have all the tools like the Chrome Development tools.

It has also support for iOS and Kindle Fire

Update

Like Chris noticed, you have to pay a subscription to use edge inspect. A cheap alternative is to use weinre directly, it's the base of edge inspect. Here's an article about how to set it up.

Error converting data types when importing from Excel to SQL Server 2008

There seems to be a really easy solution when dealing with data type issues.

Basically, at the end of Excel connection string, add ;IMEX=1;"

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\YOURSERVER\shared\Client Projects\FOLDER\Data\FILE.xls;Extended Properties="EXCEL 8.0;HDR=YES;IMEX=1";

This will resolve data type issues such as columns where values are mixed with text and numbers.

To get to connection property, right click on Excel connection manager below control flow and hit properties. It'll be to the right under solution explorer. Hope that helps.

How do I import CSV file into a MySQL table?

I see something strange. You are using for ESCAPING the same character you use for ENCLOSING. So the engine does not know what to do when it founds a '"' and I think that is why nothing seems to be in the right place. I think that if you remove the line of ESCAPING, should run great. Like:

LOAD DATA INFILE "/home/paul/clientdata.csv"
INTO TABLE CSVImport
COLUMNS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;

Unless you analyze (manually, visually, ... ) your CSV and find which character uses for escape. Sometimes is '\'. But if you do not have it, do not use it.

file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data.

Source: http://php.net/manual/en/wrappers.php.php.

Querying Datatable with where condition

You can do it with Linq, as mamoo showed, but the oldies are good too:

var filteredDataTable = dt.Select(@"EmpId > 2
    AND (EmpName <> 'abc' OR EmpName <> 'xyz')
    AND EmpName like '%il%'" );

How can I implement a theme from bootswatch or wrapbootstrap in an MVC 5 project?

I do have an article on MSDN - Creating ASP.NET MVC with custom bootstrap theme / layout using VS 2012, VS 2013 and VS 2015, also have a demo code sample attached.. Please refer below link. https://code.msdn.microsoft.com/ASPNET-MVC-application-62ffc106

How to re-enable right click so that I can inspect HTML elements in Chrome?

Hi i have a shorter version. this does same as a best answer. (it works on chrome 74.03)

document.querySelectorAll('*').forEach(e => e.oncontextmenu = null)

How to capitalize the first character of each word in a string

This is just another way of doing it:

private String capitalize(String line)
{
    StringTokenizer token =new StringTokenizer(line);
    String CapLine="";
    while(token.hasMoreTokens())
    {
        String tok = token.nextToken().toString();
        CapLine += Character.toUpperCase(tok.charAt(0))+ tok.substring(1)+" ";        
    }
    return CapLine.substring(0,CapLine.length()-1);
}

how do I loop through a line from a csv file in powershell

$header3 = @("Field_1","Field_2","Field_3","Field_4","Field_5")     

Import-Csv $fileName -Header $header3 -Delimiter "`t" | select -skip 3 | Foreach-Object {

    $record = $indexName 
    foreach ($property in $_.PSObject.Properties){

        #doSomething $property.Name, $property.Value

            if($property.Name -like '*TextWrittenAsNumber*'){

                $record = $record + "," + '"' + $property.Value + '"' 
            }
            else{
                $record = $record + "," + $property.Value 
            }                           
    }               

        $array.add($record) | out-null  
        #write-host $record                         
}

regular expression for Indian mobile numbers

Solutions(^[789]\d{9}$ or ^[789][0-9]{9}$) told by others have a one big flow (If that is used for form validation) It also validates numbers having more than 10 digit. Basically our(Because I was also using this) regex finds a valid number placed anywhere in a string.Like this 123456989796959412345 .

The problem can be solved by additionally checking length of string containing number. Like this if(regex.test(value) && value.length==10)/****do whatever*****/alert("Valid Number");

Note:- According to my tests , the regex.test(value) tests only roman numerals for this expression ^[789]\d{9}$ in both firefox(mozilla) and chrome(webkit)

Formatting "yesterday's" date in python

from datetime import datetime, timedelta

yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%m%d%y')

Convert string to int array using LINQ

You can shorten JSprangs solution a bit by using a method group instead:

string s1 = "1;2;3;4;5;6;7;8;9;10;11;12";
int[] ints = s1.Split(';').Select(int.Parse).ToArray();

AJAX jQuery refresh div every 5 seconds

Try to not use setInterval.
You can resend request to server after successful response with timeout.
jQuery:

sendRequest(); //call function

function sendRequest(){
    $.ajax({
        url: "test.php",
        success: 
        function(result){
            $('#links').text(result); //insert text of test.php into your div
            setTimeout(function(){
                sendRequest(); //this will send request again and again;
            }, 5000);
        }
    });
}

How to capture the "virtual keyboard show/hide" event in Android?

I have sort of a hack to do this. Although there doesn't seem to be a way to detect when the soft keyboard has shown or hidden, you can in fact detect when it is about to be shown or hidden by setting an OnFocusChangeListener on the EditText that you're listening to.

EditText et = (EditText) findViewById(R.id.et);
et.setOnFocusChangeListener(new View.OnFocusChangeListener()
    {
        @Override
        public void onFocusChange(View view, boolean hasFocus)
        {
            //hasFocus tells us whether soft keyboard is about to show
        }
    });

NOTE: One thing to be aware of with this hack is that this callback is fired immediately when the EditText gains or loses focus. This will actually fire right before the soft keyboard shows or hides. The best way I've found to do something after the keyboard shows or hides is to use a Handler and delay something ~ 400ms, like so:

EditText et = (EditText) findViewById(R.id.et);
et.setOnFocusChangeListener(new View.OnFocusChangeListener()
    {
        @Override
        public void onFocusChange(View view, boolean hasFocus)
        {
            new Handler().postDelayed(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        //do work here
                    }
                }, 400);
        }
    });

How to append a jQuery variable value inside the .html tag

HTML :

<div id="myDiv">
    <form id="myForm">
    </form> 
</div>

jQuery :

var chbx='<input type="checkbox" id="Mumbai" name="Mumbai" value="Mumbai" />Mumbai<br /> <input type="checkbox" id=" Delhi" name=" Delhi" value=" Delhi" /> Delhi<br/><input type="checkbox" id=" Bangalore" name=" Bangalore" value=" Bangalore"/>Bangalore<br />';

$("#myDiv form#myForm").html(chbx);

//to insert dynamically created form 
$("#myDiv").html("<form id='dynamicForm'>" +chbx + "'</form>");

Demo

How to install a .ipa file into my iPhone?

You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.

Best Way to read rss feed in .net Using C#

Update: This supports only with UWP - Windows Community Toolkit

There is a much easier way now. You can use the RssParser class. The sample code is given below.

public async void ParseRSS()
{
    string feed = null;

    using (var client = new HttpClient())
    {
        try
        {
            feed = await client.GetStringAsync("https://visualstudiomagazine.com/rss-feeds/news.aspx");
        }
        catch { }
    }

    if (feed != null)
    {
        var parser = new RssParser();
        var rss = parser.Parse(feed);

        foreach (var element in rss)
        {
            Console.WriteLine($"Title: {element.Title}");
            Console.WriteLine($"Summary: {element.Summary}");
        }
    }
}

For non-UWP use the Syndication from the namespace System.ServiceModel.Syndication as others suggested.

public static IEnumerable <FeedItem> GetLatestFivePosts() {
    var reader = XmlReader.Create("https://sibeeshpassion.com/feed/");
    var feed = SyndicationFeed.Load(reader);
    reader.Close();
    return (from itm in feed.Items select new FeedItem {
        Title = itm.Title.Text, Link = itm.Id
    }).ToList().Take(5);
}

public class FeedItem {
    public string Title {
        get;
        set;
    }
    public string Link {
        get;
        set;
    }
}

How to change the sender's name or e-mail address in mutt?

100% Working!

To send HTML contents in the body of the mail on the go with Sender and Recipient mail address in single line, you may try the below,

export EMAIL="[email protected]" && mutt -e "my_hdr Content-Type: text/html" -s "Test Mail" "[email protected]" < body_html.html

File: body_html.html

<HTML>
<HEAD> Test Mail </HEAD>
<BODY>
<p>This is a <strong><span style="color: #ff0000;">test mail!</span></strong></p>
</BODY>
</HTML>

Note: Tested in RHEL, CentOS, Ubuntu.

Creating dummy variables in pandas for python

When I think of dummy variables I think of using them in the context of OLS regression, and I would do something like this:

import numpy as np
import pandas as pd
import statsmodels.api as sm

my_data = np.array([[5, 'a', 1],
                    [3, 'b', 3],
                    [1, 'b', 2],
                    [3, 'a', 1],
                    [4, 'b', 2],
                    [7, 'c', 1],
                    [7, 'c', 1]])                


df = pd.DataFrame(data=my_data, columns=['y', 'dummy', 'x'])
just_dummies = pd.get_dummies(df['dummy'])

step_1 = pd.concat([df, just_dummies], axis=1)      
step_1.drop(['dummy', 'c'], inplace=True, axis=1)
# to run the regression we want to get rid of the strings 'a', 'b', 'c' (obviously)
# and we want to get rid of one dummy variable to avoid the dummy variable trap
# arbitrarily chose "c", coefficients on "a" an "b" would show effect of "a" and "b"
# relative to "c"
step_1 = step_1.applymap(np.int) 

result = sm.OLS(step_1['y'], sm.add_constant(step_1[['x', 'a', 'b']])).fit()
print result.summary()

Why does my 'git branch' have no master?

To checkout a branch which does not exist locally but is in the remote repo you could use this command:

git checkout -t -b master origin/master

How to disable anchor "jump" when loading a page?

Solved my promlem by doing this:

// navbar height 
var navHeigth = $('nav.navbar').height();    

// Scroll to anchor function
var scrollToAnchor = function(hash) {
  // If got a hash
  if (hash) {
    // Scroll to the top (prevention for Chrome)
    window.scrollTo(0, 0);
    // Anchor element
    var term = $(hash);

    // If element with hash id is defined
    if (term) {

      // Get top offset, including header height
      var scrollto = term.offset().top - navHeigth;

      // Capture id value
      var id = term.attr('id');
      // Capture name value
      var name = term.attr('name');

      // Remove attributes for FF scroll prevention
      term.removeAttr('id').removeAttr('name');
      // Scroll to element
      $('html, body').animate({scrollTop:scrollto}, 0);

      // Returning id and name after .5sec for the next scroll
      setTimeout(function() {
        term.attr('id', id).attr('name', name);
      }, 500);
    }
  }
};

// if we are opening the page by url
if (location.hash) {
  scrollToAnchor(location.hash);
}

// preventing default click on links with an anchor
$('a[href*="#"]').click(function(e) {
  e.preventDefault();
  // hash value
  var hash = this.href.substr(this.href.indexOf("#"));
  scrollToAnchor(hash);
});`

Image resizing client-side with JavaScript before upload to the server

The answer to this is yes - in HTML 5 you can resize images client-side using the canvas element. You can also take the new data and send it to a server. See this tutorial:

http://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/

How to call javascript function from asp.net button click event

If you don't need to initiate a post back when you press this button, then making the overhead of a server control isn't necesary.

<input id="addButton" type="button" value="Add" />

<script type="text/javascript" language="javascript">
     $(document).ready(function()
     {
         $('#addButton').click(function() 
         { 
             showDialog('#addPerson'); 
         });
     });
</script>

If you still need to be able to do a post back, you can conditionally stop the rest of the button actions with a little different code:

<asp:Button ID="buttonAdd" runat="server" Text="Add" />

<script type="text/javascript" language="javascript">
     $(document).ready(function()
     {
         $('#<%= buttonAdd.ClientID %>').click(function(e) 
         { 
             showDialog('#addPerson');

             if(/*Some Condition Is Not Met*/) 
                return false;
         });
     });
</script>

Initialising mock objects - MockIto

There is now (as of v1.10.7) a fourth way to instantiate mocks, which is using a JUnit4 rule called MockitoRule.

@RunWith(JUnit4.class)   // or a different runner of your choice
public class YourTest
  @Rule public MockitoRule rule = MockitoJUnit.rule();
  @Mock public YourMock yourMock;

  @Test public void yourTestMethod() { /* ... */ }
}

JUnit looks for subclasses of TestRule annotated with @Rule, and uses them to wrap the test Statements that the Runner provides. The upshot of this is that you can extract @Before methods, @After methods, and even try...catch wrappers into rules. You can even interact with these from within your test, the way that ExpectedException does.

MockitoRule behaves almost exactly like MockitoJUnitRunner, except that you can use any other runner, such as Parameterized (which allows your test constructors to take arguments so your tests can be run multiple times), or Robolectric's test runner (so its classloader can provide Java replacements for Android native classes). This makes it strictly more flexible to use in recent JUnit and Mockito versions.

In summary:

  • Mockito.mock(): Direct invocation with no annotation support or usage validation.
  • MockitoAnnotations.initMocks(this): Annotation support, no usage validation.
  • MockitoJUnitRunner: Annotation support and usage validation, but you must use that runner.
  • MockitoRule: Annotation support and usage validation with any JUnit runner.

See also: How JUnit @Rule works?

How to fix corrupted git repository?

Remove the index and do reset

rm -f .git/index
git reset

How do I check if an object has a specific property in JavaScript?

Performance

Today 2020.12.17 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v83 for chosen solutions.

Results

I compare only solutions A-F because they give valid result for all cased used in snippet in details section. For all browsers

  • solution based on in (A) is fast or fastest
  • solution (E) is fastest for chrome for big objects and fastest for firefox for small arrays if key not exists
  • solution (F) is fastest (~ >10x than other solutions) for small arrays
  • solutions (D,E) are quite fast
  • solution based on losash has (B) is slowest

enter image description here

Details

I perform 4 tests cases:

  • when object has 10 fields and searched key exists - you can run it HERE
  • when object has 10 fields and searched key not exists - you can run it HERE
  • when object has 10000 fields and searched key exists - you can run it HERE
  • when object has 10000 fields and searched key exists - you can run it HERE

Below snippet presents differences between solutions A B C D E F G H I J K

_x000D_
_x000D_
// SO https://stackoverflow.com/q/135448/860099


// src: https://stackoverflow.com/a/14664748/860099
function A(x) {
  return 'key' in x
}

// src: https://stackoverflow.com/a/11315692/860099
function B(x) {
  return _.has(x, 'key')
}

// src: https://stackoverflow.com/a/40266120/860099
function C(x) {
  return Reflect.has( x, 'key')
}

// src: https://stackoverflow.com/q/135448/860099
function D(x) {
  return x.hasOwnProperty('key')
}

// src: https://stackoverflow.com/a/11315692/860099
function E(x) {
  return Object.prototype.hasOwnProperty.call(x, 'key')
}

// src: https://stackoverflow.com/a/136411/860099
function F(x) {
  function hasOwnProperty(obj, prop) {
      var proto = obj.__proto__ || obj.constructor.prototype;
      return (prop in obj) &&
          (!(prop in proto) || proto[prop] !== obj[prop]);
  }
  return hasOwnProperty(x,'key')
}

// src: https://stackoverflow.com/a/135568/860099
function G(x) {
  return typeof(x.key) !== 'undefined'
}

// src: https://stackoverflow.com/a/22740939/860099
function H(x) {
  return x.key !== undefined
}

// src: https://stackoverflow.com/a/38332171/860099
function I(x) {
  return !!x.key
}

// src: https://stackoverflow.com/a/41184688/860099
function J(x) {
  return !!x['key']
}

// src: https://stackoverflow.com/a/54196605/860099
function K(x) {
  return Boolean(x.key)
}


// --------------------
// TEST
// --------------------

let x1 = {'key': 1};
let x2 = {'key': "1"};
let x3 = {'key': true};
let x4 = {'key': []};
let x5 = {'key': {}};
let x6 = {'key': ()=>{}};
let x7 = {'key': ''};
let x8 = {'key': 0};
let x9 = {'key': false};
let x10= {'key': undefined};
let x11= {'nokey': 1};



let b= x=> x ? 1:0;

console.log('  1 2 3 4 5 6 7 8 9 10 11');

[A,B,C,D,E,F,G,H,I,J,K ].map(f=> {  
  console.log(
    `${f.name} ${b(f(x1))} ${b(f(x2))} ${b(f(x3))} ${b(f(x4))} ${b(f(x5))} ${b(f(x6))} ${b(f(x7))} ${b(f(x8))} ${b(f(x9))} ${b(f(x10))}  ${b(f(x11))} `
  )})
  
console.log('\nLegend: Columns (cases)');
console.log('1.  key = 1 ');
console.log('2.  key = "1" ');
console.log('3.  key = true ');
console.log('4.  key = [] ');
console.log('5.  key = {} ');
console.log('6.  key = ()=>{} ');
console.log('7.  key = "" ');
console.log('8.  key = 0 ');
console.log('9.  key = false ');
console.log('10. key = undefined ');
console.log('11. no-key ');
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
  
This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
_x000D_
_x000D_

And here are example results for chrome

enter image description here

For each row in an R dataframe

I use this simple utility function:

rows = function(tab) lapply(
  seq_len(nrow(tab)),
  function(i) unclass(tab[i,,drop=F])
)

Or a faster, less clear form:

rows = function(x) lapply(seq_len(nrow(x)), function(i) lapply(x,"[",i))

This function just splits a data.frame to a list of rows. Then you can make a normal "for" over this list:

tab = data.frame(x = 1:3, y=2:4, z=3:5)
for (A in rows(tab)) {
    print(A$x + A$y * A$z)
}        

Your code from the question will work with a minimal modification:

for (well in rows(dataFrame)) {
  wellName <- well$name    # string like "H1"
  plateName <- well$plate  # string like "plate67"
  wellID <- getWellID(wellName, plateName)
  cat(paste(wellID, well$value1, well$value2, sep=","), file=outputFile)
}

Compare cell contents against string in Excel

If a case-insensitive comparison is acceptable, just use =:

=IF(A1="ENG",1,0)

Where is the Global.asax.cs file?

It don't create normally; you need to add it by yourself.

After adding Global.asax by

  • Right clicking your website -> Add New Item -> Global Application Class -> Add

You need to add a class

  • Right clicking App_Code -> Add New Item -> Class -> name it Global.cs -> Add

Inherit the newly generated by System.Web.HttpApplication and copy all the method created Global.asax to Global.cs and also add an inherit attribute to the Global.asax file.

Your Global.asax will look like this: -

<%@ Application Language="C#" Inherits="Global" %>

Your Global.cs in App_Code will look like this: -

public class Global : System.Web.HttpApplication
{
    public Global()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }
    /// Many other events like begin request...e.t.c, e.t.c
}

Conditional Count on a field

I think you may be after

select 
    jobID, JobName,
    sum(case when Priority = 1 then 1 else 0 end) as priority1,
    sum(case when Priority = 2 then 1 else 0 end) as priority2,
    sum(case when Priority = 3 then 1 else 0 end) as priority3,
    sum(case when Priority = 4 then 1 else 0 end) as priority4,
    sum(case when Priority = 5 then 1 else 0 end) as priority5
from
    Jobs
group by 
    jobID, JobName

However I am uncertain if you need to the jobID and JobName in your results if so remove them and remove the group by,

How to check if a column exists in Pandas

Just to suggest another way without using if statements, you can use the get() method for DataFrames. For performing the sum based on the question:

df['sum'] = df.get('A', df['B']) + df['C']

The DataFrame get method has similar behavior as python dictionaries.

How to reset form body in bootstrap modal box?

In Bootstrap 3 you can reset your form after your modal window has been closed as follows:

$('.modal').on('hidden.bs.modal', function(){
    $(this).find('form')[0].reset();
});

How to Convert JSON object to Custom C# object?

The JSON C# class generator on codeplex generates classes which work well with NewtonSoftJS.

multiprocessing: How do I share a dict among multiple processes?

In addition to @senderle's here, some might also be wondering how to use the functionality of multiprocessing.Pool.

The nice thing is that there is a .Pool() method to the manager instance that mimics all the familiar API of the top-level multiprocessing.

from itertools import repeat
import multiprocessing as mp
import os
import pprint

def f(d: dict) -> None:
    pid = os.getpid()
    d[pid] = "Hi, I was written by process %d" % pid

if __name__ == '__main__':
    with mp.Manager() as manager:
        d = manager.dict()
        with manager.Pool() as pool:
            pool.map(f, repeat(d, 10))
        # `d` is a DictProxy object that can be converted to dict
        pprint.pprint(dict(d))

Output:

$ python3 mul.py 
{22562: 'Hi, I was written by process 22562',
 22563: 'Hi, I was written by process 22563',
 22564: 'Hi, I was written by process 22564',
 22565: 'Hi, I was written by process 22565',
 22566: 'Hi, I was written by process 22566',
 22567: 'Hi, I was written by process 22567',
 22568: 'Hi, I was written by process 22568',
 22569: 'Hi, I was written by process 22569',
 22570: 'Hi, I was written by process 22570',
 22571: 'Hi, I was written by process 22571'}

This is a slightly different example where each process just logs its process ID to the global DictProxy object d.

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

Previous answers point out correctly that you can only do this with the standard JDK tools by converting the JKS file into PKCS #12 format first. If you're interested, I put together a compact utility to import OpenSSL-derived keys into a JKS-formatted keystore without having to convert the keystore to PKCS #12 first: http://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art049

You would use the linked utility like this:

$ openssl req -x509 -newkey rsa:2048 -keyout localhost.key -out localhost.csr -subj "/CN=localhost"

(sign the CSR, get back localhost.cer)

$ openssl rsa -in localhost.key -out localhost.rsa
Enter pass phrase for localhost.key:
writing RSA key
$ java -classpath . KeyImport -keyFile localhost.rsa -alias localhost -certificateFile localhost.cer -keystore localhost.jks -keystorePassword changeit -keystoreType JKS -keyPassword changeit

How do I count occurrence of duplicate items in array

You can also use it with text items array, u will get number of duplicates properly, but PHP shows

Warning: array_count_values(): Can only count STRING and INTEGER values!

$domains = 
array (
  0 => 'i1.wp.com',
  1 => 'i1.wp.com',
  2 => 'i2.wp.com',
  3 => 'i0.wp.com',
  4 => 'i2.wp.com',
  5 => 'i2.wp.com',
  6 => 'i0.wp.com',
  7 => 'i2.wp.com',
  8 => 'i0.wp.com',
  9 => 'i0.wp.com' );

$tmp = array_count_values($domains);
print_r ($tmp);

    array (
      'i1.wp.com' => 2730,
      'i2.wp.com' => 2861,
      'i0.wp.com' => 2807
    )

How do I disable Git Credential Manager for Windows?

Another option I had to use with VSTS:

git config credential.modalprompt false --global

How to force reloading php.ini file?

You also can use graceful restart the apache server with service apache2 reload or apachectl -k graceful. As the apache doc says:

The USR1 or graceful signal causes the parent process to advise the children to exit after their current request (or to exit immediately if they're not serving anything). The parent re-reads its configuration files and re-opens its log files. As each child dies off the parent replaces it with a child from the new generation of the configuration, which begins serving new requests immediately.

How do I turn off PHP Notices?

Use phpinfo() and search for Configuration File (php.ini) Path to see which config file path for php is used. PHP can have multiple config files depending on environment it's running. Usually, for console it's:

/etc/php5/cli/php.ini

and for php run by apache it's:

/etc/php5/apache2/php.ini

And then set error_reporting the way you need it:

http://www.phpknowhow.com/configuration/php-ini-error-settings/ http://www.zootemplate.com/news-updates/how-to-disable-notice-and-warning-in-phpini-file

Psql could not connect to server: No such file or directory, 5432 error?

WARNING: This will remove the database

Within zsh:

rm -rf /usr/local/var/postgres && initdb /usr/local/var/postgres -E utf8

This is the only thing that worked for me after countless hours trouble shooting.

Hide Utility Class Constructor : Utility classes should not have a public or default constructor

I recommend just disabling this rule in Sonar, there is no real benefit of introducing a private constructor, just redundant characters in your codebase other people need to read and computer needs to store and process.

reducing number of plot ticks

Alternatively, if you want to simply set the number of ticks while allowing matplotlib to position them (currently only with MaxNLocator), there is pyplot.locator_params,

pyplot.locator_params(nbins=4)

You can specify specific axis in this method as mentioned below, default is both:

# To specify the number of ticks on both or any single axes
pyplot.locator_params(axis='y', nbins=6)
pyplot.locator_params(axis='x', nbins=10)

How to properly make a http web GET request

Simpliest way for my opinion

  var web = new WebClient();
  var url = $"{hostname}/LoadDataSync?systemID={systemId}";
  var responseString = web.DownloadString(url);

OR

 var bytes = web.DownloadData(url);

startForeground fail after upgrade to Android 8.1

Works properly on Andorid 8.1:

Updated sample (without any deprecated code):

public NotificationBattery(Context context) {
    this.mCtx = context;

    mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
            .setContentTitle(context.getString(R.string.notification_title_battery))
            .setSmallIcon(R.drawable.ic_launcher)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setChannelId(CHANNEL_ID)
            .setOnlyAlertOnce(true)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setWhen(System.currentTimeMillis() + 500)
            .setGroup(GROUP)
            .setOngoing(true);

    mRemoteViews = new RemoteViews(context.getPackageName(), R.layout.notification_view_battery);

    initBatteryNotificationIntent();

    mBuilder.setContent(mRemoteViews);

    mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    if (AesPrefs.getBooleanRes(R.string.SHOW_BATTERY_NOTIFICATION, true)) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, context.getString(R.string.notification_title_battery),
                    NotificationManager.IMPORTANCE_DEFAULT);
            channel.setShowBadge(false);
            channel.setSound(null, null);
            mNotificationManager.createNotificationChannel(channel);
        }
    } else {
        mNotificationManager.cancel(Const.NOTIFICATION_CLIPBOARD);
    }
}

Old snipped (it's a different app - not related to the code above):

@Override
public int onStartCommand(Intent intent, int flags, final int startId) {
    Log.d(TAG, "onStartCommand");

    String CHANNEL_ONE_ID = "com.kjtech.app.N1";
    String CHANNEL_ONE_NAME = "Channel One";
    NotificationChannel notificationChannel = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
                CHANNEL_ONE_NAME, IMPORTANCE_HIGH);
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.setShowBadge(true);
        notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.createNotificationChannel(notificationChannel);
    }

    Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
    Notification notification = new Notification.Builder(getApplicationContext())
            .setChannelId(CHANNEL_ONE_ID)
            .setContentTitle(getString(R.string.obd_service_notification_title))
            .setContentText(getString(R.string.service_notification_content))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(icon)
            .build();

    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    notification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);

    startForeground(START_FOREGROUND_ID, notification);

    return START_STICKY;
}

Dead simple example of using Multiprocessing Queue, Pool and Locking

This might be not 100% related to the question, but on my search for an example of using multiprocessing with a queue this shows up first on google.

This is a basic example class that you can instantiate and put items in a queue and can wait until queue is finished. That's all I needed.

from multiprocessing import JoinableQueue
from multiprocessing.context import Process


class Renderer:
    queue = None

    def __init__(self, nb_workers=2):
        self.queue = JoinableQueue()
        self.processes = [Process(target=self.upload) for i in range(nb_workers)]
        for p in self.processes:
            p.start()

    def render(self, item):
        self.queue.put(item)

    def upload(self):
        while True:
            item = self.queue.get()
            if item is None:
                break

            # process your item here

            self.queue.task_done()

    def terminate(self):
        """ wait until queue is empty and terminate processes """
        self.queue.join()
        for p in self.processes:
            p.terminate()

r = Renderer()
r.render(item1)
r.render(item2)
r.terminate()

IF/ELSE Stored Procedure

Just a tip for this, you don't need the BEGIN and END if it only contains a single statement.

ie:

IF(@Trans_type = 'subscr_signup')    
 set @tmpType = 'premium' 
ELSE iF(@Trans_type = 'subscr_cancel')  
     set    @tmpType = 'basic'

Difference between e.target and e.currentTarget

e.currentTarget would always return the component onto which the event listener is added.

On the other hand, e.target can be the component itself or any direct child or grand child or grand-grand-child and so on who received the event. In other words, e.target returns the component which is on top in the Display List hierarchy and must be in the child hierarchy or the component itself.

One use can be when you have several Image in Canvas and you want to drag Images inside the component but Canvas. You can add a listener on Canvas and in that listener you can write the following code to make sure that Canvas wouldn't get dragged.

function dragImageOnly(e:MouseEvent):void
{
    if(e.target==e.currentTarget)
    {
        return;
     }
     else
     {
        Image(e.target).startDrag();
     }
}

Bootstrap 3: Keep selected tab on page refresh

In addition to Xavi Martínez's answer avoiding the jump on click

Avoiding Jump

$(document).ready(function(){

    // show active tab

    if(location.hash) {

        $('a[href=' + location.hash + ']').tab('show');
    }

    // set hash on click without jumb

    $(document.body).on("click", "a[data-toggle]", function(e) {

        e.preventDefault();

        if(history.pushState) {

            history.pushState(null, null, this.getAttribute("href"));
        }
        else {

            location.hash = this.getAttribute("href");
        }

        $('a[href=' + location.hash + ']').tab('show');

        return false;
    });
});

// set hash on popstate

$(window).on('popstate', function() {

    var anchor = location.hash || $("a[data-toggle=tab]").first().attr("href");

    $('a[href=' + anchor + ']').tab('show');
});

Nested tabs

implementation with "_" character as separator

$(document).ready(function(){

    // show active tab

    if(location.hash) {

        var tabs = location.hash.substring(1).split('_');

        $.each(tabs,function(n){

            $('a[href=#' + tabs[n] + ']').tab('show');
        });         

        $('a[href=' + location.hash + ']').tab('show');
    }

    // set hash on click without jumb

    $(document.body).on("click", "a[data-toggle]", function(e) {

        e.preventDefault();

        if(history.pushState) {

            history.pushState(null, null, this.getAttribute("href"));
        }
        else {

            location.hash = this.getAttribute("href");
        }

        var tabs = location.hash.substring(1).split('_');

        //console.log(tabs);

        $.each(tabs,function(n){

            $('a[href=#' + tabs[n] + ']').tab('show');
        });

        $('a[href=' + location.hash + ']').tab('show');

        return false;
    });
});

// set hash on popstate

$(window).on('popstate', function() {

    var anchor = location.hash || $("a[data-toggle=tab]").first().attr("href");

    var tabs = anchor.substring(1).split('_');

    $.each(tabs,function(n){

        $('a[href=#' + tabs[n] + ']').tab('show');
    });

    $('a[href=' + anchor + ']').tab('show');
});

Authenticate Jenkins CI for Github private repository

An alternative to the answer from sergey_mo is to create multiple ssh keys on the jenkins server.

(Though as the first commenter to sergey_mo's answer said, this may end up being more painful than managing a single key-pair.)

How to drop a unique constraint from table column?

Expand to database name >> expand to table >> expand to keys >> copy the name of key then execute the below command:

ALTER TABLE Test DROP UQ__test__3213E83EB607700F;

Here UQ__test__3213E83EB607700F is the name of unique key which was created on a particular column on test table.

Converting list to numpy array

If you have a list of lists, you only needed to use ...

import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

How do you find the sum of all the numbers in an array in Java?

public class AddDemo {

    public static void main(String[] args) {

        ArrayList <Integer>A = new ArrayList<Integer>();

        Scanner S = new Scanner(System.in);

        System.out.println("Enter the Numbers: ");

        for(int i=0; i<5; i++){

            A.add(S.nextInt());
        }

        System.out.println("You have entered: "+A);

        int Sum = 0;

        for(int i=0; i<A.size(); i++){

            Sum = Sum + A.get(i);

        }

        System.out.println("The Sum of Entered List is: "+Sum);

    }

}

Asp.net 4.0 has not been registered

I had the same issue but solved it...... Microsoft has a fix for something close to this that actually worked to solve this issue. you can visit this page http://blogs.msdn.com/b/webdev/archive/2014/11/11/dialog-box-may-be-displayed-to-users-when-opening-projects-in-microsoft-visual-studio-after-installation-of-microsoft-net-framework-4-6.aspx

The issue occurs after you installed framework 4.5 and/or framework 4.6. The Visual Studio 2012 Update 5 doesn't fix the issue, I tried that first.

The msdn blog has this to say: "After the installation of the Microsoft .NET Framework 4.6, users may experience the following dialog box displayed in Microsoft Visual Studio when either creating new Web Site or Windows Azure project or when opening existing projects....."

According to the Blog the dialog is benign. just click OK, nothing is effected by the dialog... The comments in the blog suggests that VS 2015 has the same problem, maybe even worse.

Finding an element in an array in Java

You can use one of the many Arrays.binarySearch() methods. Keep in mind that the array must be sorted first.

How do I make Java register a string input with spaces?

I found a very weird thing in Java today, so it goes like -

If you are inputting more than 1 thing from the user, say

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();

System.out.println(i);
System.out.println(d);
System.out.println(s);

So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java" The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s

But, the output that you will get is -

10
2.5

And that's it, it doesn't even prompt for the String input. Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().

So changing my code to something like this -

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();

System.out.println(i);
System.out.println(d);
System.out.println(s);

does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.

Please if anybody knows help me with an explanation for this.

How to calculate sum of a formula field in crystal Reports?

You can try like this:

Sum({Tablename.Columnname})

It will work without creating a summarize field in formulae.

Encode URL in JavaScript?

I always use this to encode stuff for URLs. This is completely safe because it will encode every single character even if it doesn't have to be encoded.

function urlEncode(text) {
    encoded = '';
    for (let char of text) {
        encoded += '%' + char.charCodeAt(0).toString(16);
    }
    return encoded;
}

How can I force a hard reload in Chrome for Android

Here is another simple solution that may work when others fail:

Today, a fairly simple developer-side solution worked for me when the caching problem was a cached CSS file. In short: Create a temporary html file copy and browse to it to update the CSS cache.

This trick can refresh the CSS file, at least in Android's blue-globe-iconed default browser (but quite likely its twin, the official Chrome browser, too, and whatever other browsers we encounter on "smart"phones with their trend of aggressive caching).

Details:

At first I tried some of the fairly simple solutions shared here, but without success (for example clearing the recent history of the specific site, but not months and months of it). My latest CSS would however not be applied apon refresh. And that even though I had already employed the version-number-trick in the CSS file-call in the head section of the html which had helped me avoid these pesky aggressive cachings in the past. (example: link rel="stylesheet" href="style.css?v=001" where you upgrade this pseudo-version number every time you make a change to a CSS file, e.g. 001, 002, 003, 004... (should be done in every html file of the site))

This time (August 2019) the CSS file version number update no longer sufficed, nor did some of the simpler measures mentioned here work for me, or I couldn't even find access to some of them (on a borrowed android phone).

In the end I tried something relatively simple that finally solved the problem:

I made a copy of the site's index.html file giving it a different name (indexcopy.html), uploaded it, browsed to it on the Android device, then browsed back to the original page, refreshed it (with the refresh button left of the address bar), and voilà: This time the refresh of index.html finally worked.

Explanation: The latest CSS file version was now finally applied on Android when refreshing the html page in question because the cached copy of the CSS file had now been updated when the CSS file was called from a differently named temporary html page that did not exist anywhere in the browser history and that I could delete again afterwards. The aggressive caching apparently ignored the CSS URL and went instead by the HTML URL, even though it was the CSS file that needed to be updated in the cache.

Best way to integrate Python and JavaScript?

You might also want to check out the PyPy project - they have a Python to (anything) compiler, including Python to Javascript, C, and llvm. This allows you to write your code in Python and then compile it into Javascript as you desire.

http://codespeak.net/pypy

Also, check out the informative blog:

http://morepypy.blogspot.com/

Unfortunately though, you can't convert Javascript to Python this way. It seems to work really well overall, they used to have a Javascript (made from compiled Python) version of the Bub'n'Bros game online (though the server has been down for a while).

http://bub-n-bros.sourceforge.net

Opacity of div's background without affecting contained element in IE 8?

opacity on parent element sets it for the whole sub DOM tree

You can't really set opacity for certain element that wouldn't cascade to descendants as well. That's not how CSS opacity works I'm afraid.

What you can do is to have two sibling elements in one container and set transparent one's positioning:

<div id="container">
    <div id="transparent"></div>
    <div id="content"></div>
</div>

then you have to set transparent position: absolute/relative so its content sibling will be rendered over it.

rgba can do background transparency of coloured backgrounds

rgba colour setting on element's background-color will of course work, but it will limit you to only use colour as background. No images I'm afraid. You can of course use CSS3 gradients though if you provide gradient stop colours in rgba. That works as well.

But be advised that rgba may not be supported by your required browsers.

Alert-free modal dialog functionality

But if you're after some kind of masking the whole page, this is usually done by adding a separate div with this set of styles:

position: fixed;
width: 100%;
height: 100%;
z-index: 1000; /* some high enough value so it will render on top */
opacity: .5;
filter: alpha(opacity=50);

Then when you display the content it should have a higher z-index. But these two elements are not related in terms of siblings or anything. They're just displayed as they should be. One over the other.

CURLOPT_RETURNTRANSFER set to true doesnt work on hosting server

If it works fine on your local environment, probably your remote server's IP is being blocked by the server at the target URL you've set for cURL to use. You need to verify that your remote server is allowed to access the URL you've set for CURLOPT_URL.

C# LINQ find duplicates in List

there is an answer but i did not understand why is not working;

var anyDuplicate = enumerable.GroupBy(x => x.Key).Any(g => g.Count() > 1);

my solution is like that in this situation;

var duplicates = model.list
                    .GroupBy(s => s.SAME_ID)
                    .Where(g => g.Count() > 1).Count() > 0;
if(duplicates) {
    doSomething();
}

Attach (open) mdf file database with SQL Server Management Studio

I had the same problem.

system configuration:-single system with window 7 sp1 server and client both are installed on same system

I was trying to access the window desktop. As some the answer say that your Sqlserver service don't have full access to the directory. This is totally right.

I solved this problem by doing a few simple steps

  1. Go to All Programs->microsoft sql server 2008 -> configuration tools and then select sql server configuration manager.
  2. Select the service and go to properties. In the build in Account dialog box select local system and then select ok button.

enter image description here

Steps 3 and 4 in image are demo with accessing the folder

How do I modify a MySQL column to allow NULL?

Use: ALTER TABLE mytable MODIFY mycolumn VARCHAR(255);

Find the max of two or more columns with pandas

@DSM's answer is perfectly fine in almost any normal scenario. But if you're the type of programmer who wants to go a little deeper than the surface level, you might be interested to know that it is a little faster to call numpy functions on the underlying .to_numpy() (or .values for <0.24) array instead of directly calling the (cythonized) functions defined on the DataFrame/Series objects.

For example, you can use ndarray.max() along the first axis.

# Data borrowed from @DSM's post.
df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
df
   A  B
0  1 -2
1  2  8
2  3  1

df['C'] = df[['A', 'B']].values.max(1)
# Or, assuming "A" and "B" are the only columns, 
# df['C'] = df.values.max(1) 
df

   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3 

If your data has NaNs, you will need numpy.nanmax:

df['C'] = np.nanmax(df.values, axis=1)
df

   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3 

You can also use numpy.maximum.reduce. numpy.maximum is a ufunc (Universal Function), and every ufunc has a reduce:

df['C'] = np.maximum.reduce(df['A', 'B']].values, axis=1)
# df['C'] = np.maximum.reduce(df[['A', 'B']], axis=1)
# df['C'] = np.maximum.reduce(df, axis=1)
df

   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3

enter image description here

np.maximum.reduce and np.max appear to be more or less the same (for most normal sized DataFrames)—and happen to be a shade faster than DataFrame.max. I imagine this difference roughly remains constant, and is due to internal overhead (indexing alignment, handling NaNs, etc).

The graph was generated using perfplot. Benchmarking code, for reference:

import pandas as pd
import perfplot

np.random.seed(0)
df_ = pd.DataFrame(np.random.randn(5, 1000))

perfplot.show(
    setup=lambda n: pd.concat([df_] * n, ignore_index=True),
    kernels=[
        lambda df: df.assign(new=df.max(axis=1)),
        lambda df: df.assign(new=df.values.max(1)),
        lambda df: df.assign(new=np.nanmax(df.values, axis=1)),
        lambda df: df.assign(new=np.maximum.reduce(df.values, axis=1)),
    ],
    labels=['df.max', 'np.max', 'np.maximum.reduce', 'np.nanmax'],
    n_range=[2**k for k in range(0, 15)],
    xlabel='N (* len(df))',
    logx=True,
    logy=True)

How to get the stream key for twitch.tv

You will get it here (change "yourtwitch" by your twitch nickname")

http://www.twitch.tv/yourtwitch/dashboard/streamkey

The link simply moved. You can get this link on the main page of twitch.tv, click on your name then "Dashboard".

No 'Access-Control-Allow-Origin' header is present on the requested resource- AngularJS

The Chrome Webstore has an extension that adds the 'Access-Control-Allow-Origin' header for you when there is an asynchronous call in the page that tries to access a different host than yours.

The name of the extension is: "Allow-Control-Allow-Origin: *" and this is the link: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

Checking if element exists with Python Selenium

Solution without try&catch and without new imports:

if len(driver.find_elements_by_id('blah')) > 0: #pay attention: find_element*s*
    driver.find_element_by_id('blah').click #pay attention: find_element

Unable to create a constant value of type Only primitive types or enumeration types are supported in this context

In my case, I was able to resolve the issue by doing the following:

I changed my code from this:

var r2 = db.Instances.Where(x => x.Player1 == inputViewModel.InstanceList.FirstOrDefault().Player2 && x.Player2 == inputViewModel.InstanceList.FirstOrDefault().Player1).ToList();

To this:

var p1 = inputViewModel.InstanceList.FirstOrDefault().Player1;
var p2 = inputViewModel.InstanceList.FirstOrDefault().Player2;
var r1 = db.Instances.Where(x => x.Player1 == p1 && x.Player2 == p2).ToList();

Android checkbox style

The correct way to do it for Material design is :

Style :

<style name="MyCheckBox" parent="Theme.AppCompat.Light">  
    <item name="colorControlNormal">@color/foo</item>
    <item name="colorControlActivated">@color/bar</item>
</style>  

Layout :

<CheckBox  
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true"
    android:text="Check Box"
    android:theme="@style/MyCheckBox"/>

It will preserve Material animations on Lollipop+.

Cloudfront custom-origin distribution returns 502 "ERROR The request could not be satisfied." for some URLs

In my case, I use nginx as reverse-proxy for an API Gateway URL. I got same error.

I resolved the issue when I added the following two lines to the Nginx config:

proxy_set_header Host "XXXXXX.execute-api.REGION.amazonaws.com";
proxy_ssl_server_name on;

Source is here: Setting up proxy_pass on nginx to make API calls to API Gateway

SQL SERVER: Check if variable is null and then assign statement for Where Clause

Isnull() syntax is built in for this kind of thing.

declare @Int int = null;

declare @Values table ( id int, def varchar(8) )

insert into @Values values (8, 'I am 8');

-- fails
select *
from @Values
where id = @Int

-- works fine
select *
from @Values
where id = isnull(@Int, 8);

For your example keep in mind you can change scope to be yet another where predicate off of a different variable for complex boolean logic. Only caveat is you need to cast it differently if you need to examine for a different data type. So if I add another row but wish to specify int of 8 AND also the reference of text similar to 'repeat' I can do that with a reference again back to the 'isnull' of the first variable yet return an entirely different result data type for a different reference to a different field.

declare @Int int = null;

declare @Values table ( id int, def varchar(16) )

insert into @Values values (8, 'I am 8'), (8, 'I am 8 repeat');

select *
from @Values
where id = isnull(@Int, 8)
and def like isnull(cast(@Int as varchar), '%repeat%')

How can I close a window with Javascript on Mozilla Firefox 3?

If the browser people see this as a security and/or usability problem, then the answer to your question is to simply not close the window, since by definition they will come up with solutions for your workaround anyway. There is a nice summation about the reasoning why the choice have been in the firefox bug database https://bugzilla.mozilla.org/show_bug.cgi?id=190515#c70

So what can you do?

Change the specification of your website, so that you have a solution for these people. You could for instance take it as an opportunity to direct them to a partner.

That is, see it as a handoff to someone else that (potentially) needs it. As an example, Hanselman had a recent article about what to do in the other similar situation, namely 404 errors: http://www.hanselman.com/blog/PutMissingKidsOnYour404PageEntirelyClientSideSolutionWithYQLJQueryAndMSAjax.aspx

What replaces cellpadding, cellspacing, valign, and align in HTML5 tables?

/* cellpadding */
th, td { padding: 5px; }

/* cellspacing */
table { border-collapse: separate; border-spacing: 5px; } /* cellspacing="5" */
table { border-collapse: collapse; border-spacing: 0; }   /* cellspacing="0" */

/* valign */
th, td { vertical-align: top; }

/* align (center) */
table { margin: 0 auto; }

How to open a new tab in GNOME Terminal from command line?

A bit more elaborate version (to use from another window):

#!/bin/bash

DELAY=3

TERM_PID=$(echo `ps -C gnome-terminal -o pid= | head -1`) # get first gnome-terminal's PID
WID=$(wmctrl -lp | awk -v pid=$TERM_PID '$3==pid{print $1;exit;}') # get window id

xdotool windowfocus $WID
xdotool key alt+t # my key map
xdotool sleep $DELAY # it may take a while to start new shell :(
xdotool type --delay 1 --clearmodifiers "$@"
xdotool key Return

wmctrl -i -a $WID # go to that window (WID is numeric)

# vim:ai
# EOF #

unix sort descending order

If you only want to sort only on the 5th field then use -k5,5.

Also, use the -t command line switch to specify the delimiter to tab. Try this:

sort  -k5,5 -r -n -t \t filename

or if the above doesn't work (with the tab) this:

sort  -k5,5 -r -n -t $'\t' filename

The man page for sort states:

-t, --field-separator=SEP use SEP instead of non-blank to blank transition

Finally, this SO question Unix Sort with Tab Delimiter might be helpful.

Use of Application.DoEvents()

I've seen many commercial applications, using the "DoEvents-Hack". Especially when rendering comes into play, I often see this:

while(running)
{
    Render();
    Application.DoEvents();
}

They all know about the evil of that method. However, they use the hack, because they don't know any other solution. Here are some approaches taken from a blog post by Tom Miller:

  • Set your form to have all drawing occur in WmPaint, and do your rendering there. Before the end of the OnPaint method, make sure you do a this.Invalidate(); This will cause the OnPaint method to be fired again immediately.
  • P/Invoke into the Win32 API and call PeekMessage/TranslateMessage/DispatchMessage. (Doevents actually does something similar, but you can do this without the extra allocations).
  • Write your own forms class that is a small wrapper around CreateWindowEx, and give yourself complete control over the message loop. -Decide that the DoEvents method works fine for you and stick with it.

anaconda - path environment variable in windows

Provide the Directory/Folder path where python.exe is available in Anaconda folder like

C:\Users\user_name\Anaconda3\

This should must work.

Can I add a custom attribute to an HTML tag?

You can set properties from JavaScript.

document.getElementById("foo").myAttri = "myVal"

How do you decrease navbar height in Bootstrap 3?

In Bootstrap 4

In my case I have just changed the .navbar min-height and the links font-size and it decreased the navbar.

For example:

.navbar{
    min-height:12px;
}
.navbar  a {
    font-size: 11.2px;
}

And this also worked for increasing the navbar height.

This also helps to change the navbar size when scrolling down the browser.

HTML: how to make 2 tables with different CSS

In your html

<table class="table1">
<tr>
<td>
...
</table>

<table class="table2">

<tr>
<td>
...
</table>

In your css:

table.table1 {...}
table.table1 tr {...}
table.table1 td {...}

table.table2 {...}
table.table2 tr {...}
table.table2 td {...}

Which version of C# am I using

The current answers are outdated. You should be able to use #error version (at the top of any C# file in the project, or nearly anywhere in the code). The compiler treats this in a special way and reports a compiler error, CS8304, indicating the language version, and also the compiler version. The message of CS8304 is something that looks like the following:

error CS8304: Compiler version: '3.7.0-3.20312.3 (ec484126)'. Language version: 6.

How to fix the "508 Resource Limit is reached" error in WordPress?

Actually it happens when the number of processes exceeds the limits set by the hosting provider.

To avoid either we need to enhance the capacity by hosting providers or we need to check in the code whether any process takes longer time (like background tasks).

How to pass command-line arguments to a PowerShell ps1 file

Maybe you can wrap the PowerShell invocation in a .bat file like so:

rem ps.bat
@echo off
powershell.exe -command "%*"

If you then placed this file under a folder in your PATH, you could call PowerShell scripts like this:

ps foo 1 2 3

Quoting can get a little messy, though:

ps write-host """hello from cmd!""" -foregroundcolor green

Xcode swift am/pm time to 24 hour format

Swift 3

Time format 24 hours to 12 hours

let dateAsString = "13:15"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"

let date = dateFormatter.date(from: dateAsString)
dateFormatter.dateFormat = "h:mm a"
let Date12 = dateFormatter.string(from: date!)
print("12 hour formatted Date:",Date12)

output will be 12 hour formatted Date: 1:15 PM

Time format 12 hours to 24 hours

let dateAsString = "1:15 PM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"

let date = dateFormatter.date(from: dateAsString)
dateFormatter.dateFormat = "HH:mm"

let Date24 = dateFormatter.string(from: date!)
print("24 hour formatted Date:",Date24)

output will be 24 hour formatted Date: 13:15

How to do Select All(*) in linq to sql

Why don't you use

DbTestDataContext obj = new DbTestDataContext();
var q =from a in obj.GetTable<TableName>() select a;

This is simple.

How to redirect the output of print to a TXT file

Redirect sys.stdout to an open file handle and then all printed output goes to a file:

import sys
filename  = open("outputfile",'w')
sys.stdout = filename
print "Anything printed will go to the output file"

What is the reason for having '//' in Python?

// is unconditionally "flooring division", e.g:

>>> 4.0//1.5
2.0

As you see, even though both operands are floats, // still floors -- so you always know securely what it's going to do.

Single / may or may not floor depending on Python release, future imports, and even flags on which Python's run, e.g.:

$ python2.6 -Qold -c 'print 2/3'
0
$ python2.6 -Qnew -c 'print 2/3'
0.666666666667

As you see, single / may floor, or it may return a float, based on completely non-local issues, up to and including the value of the -Q flag...;-).

So, if and when you know you want flooring, always use //, which guarantees it. If and when you know you don't want flooring, slap a float() around other operand and use /. Any other combination, and you're at the mercy of version, imports, and flags!-)