Programs & Examples On #Qgraphicsitem

The QGraphicsItem class is the base class for all graphical items in a QGraphicsScene.

UILabel with text of two different colors

For displaying short, formatted text that doesn't need to be editable, Core Text is the way to go. There are several open-source projects for labels that use NSAttributedString and Core Text for rendering. See CoreTextAttributedLabel or OHAttributedLabel for example.

Combine two integer arrays

Find the total size of both array and set array1and2 to the total size of both array added. Then loop array1 and then array2 and add the values into array1and2.

AngularJS error: 'argument 'FirstCtrl' is not a function, got undefined'

I have faced this issue and it fixed with following way:

  1. first remove ng-app from:

    <html ng-app>
    
  2. add name of ng-app to myApp:

    <div ng-app="myApp">
    
  3. add this line of code before function:

    angular.module('myApp', []).controller('FirstCtrl',FirstCtrl);
    

final look of script:

angular.module('myApp', []).controller('FirstCtrl',FirstCtrl);

function FirstCtrl($scope){
    $scope.data = {message: "Hello"};
} 

Use of "instanceof" in Java

instanceof is used to check if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

Read more from the Oracle language definition here.

How to put a List<class> into a JSONObject and then read that object?

You could use a JSON serializer/deserializer like flexjson to do the conversion for you.

How to update Ruby to 1.9.x on Mac?

There are several other version managers to consider, see for a few examples and one that's not listed there that I'll be giving a try soon is ch-ruby. I tried rbenv but had too many problems with it. RVM is my mainstay, though it sometimes has the odd problem (hence my wish to try ch-ruby when I get a chance). I wouldn't touch the system Ruby, as other things may rely on it.

I should add I've also compiled my own Ruby several times, and using the Hivelogic article (as Dave Everitt has suggested) is a good idea if you take that route.

How to find the extension of a file in C#?

string FileExtn = System.IO.Path.GetExtension(fpdDocument.PostedFile.FileName);

The above method works fine with the firefox and IE , i am able to view all types of files like zip,txt,xls,xlsx,doc,docx,jpg,png

but when i try to find the extension of file from googlechrome , i failed.

Interface vs Base class

Don't use a base class unless you know what it means, and that it applies in this case. If it applies, use it, otherwise, use interfaces. But note the answer about small interfaces.

Public Inheritance is overused in OOD and expresses a lot more than most developers realize or are willing to live up to. See the Liskov Substitutablity Principle

In short, if A "is a" B then A requires no more than B and delivers no less than B, for every method it exposes.

Function to check if a string is a date

strtotime? Lists? Regular expressions?

What's wrong with PHP's native DateTime object?

http://www.php.net/manual/en/datetime.construct.php

HTML tag <a> want to add both href and onclick working

To achieve this use following html:

<a href="www.mysite.com" onclick="make(event)">Item</a>

<script>
    function make(e) {
        // ...  your function code
        // e.preventDefault();   // use this to NOT go to href site
    }
</script>

Here is working example.

How to write LaTeX in IPython Notebook?

Use $$ if you want your math to appear in a single line, e.g.,

$$a = b + c$$ (line break after the equation)

If you don't need a line break after the math, use single dollar sign $, e.g.,

$a = b + c$   (no line break after the equation)

You must enable the openssl extension to download files via https

I had to uncomment extension=openssl in php.ini file for everything to work!

Webpack how to build production code and how to use it

If you have a lot of duplicate code in your webpack.dev.config and your webpack.prod.config, you could use a boolean isProd to activate certain features only in certain situations and only have a single webpack.config.js file.

const isProd = (process.env.NODE_ENV === 'production');

 if (isProd) {
     plugins.push(new AotPlugin({
      "mainPath": "main.ts",
      "hostReplacementPaths": {
        "environments/index.ts": "environments/index.prod.ts"
      },
      "exclude": [],
      "tsConfigPath": "src/tsconfig.app.json"
    }));
    plugins.push(new UglifyJsPlugin({
      "mangle": {
        "screw_ie8": true
      },
      "compress": {
        "screw_ie8": true,
        "warnings": false
      },
      "sourceMap": false
    }));
  }

By the way: The DedupePlugin plugin was removed from Webpack. You should remove it from your configuration.

UPDATE:

In addition to my previous answer:

If you want to hide your code for release, try enclosejs.com. It allows you to:

  • make a release version of your application without sources
  • create a self-extracting archive or installer
  • Make a closed source GUI application
  • Put your assets inside the executable

You can install it with npm install -g enclose

Shuffle an array with python, randomize array item order with python

In addition to the previous replies, I would like to introduce another function.

numpy.random.shuffle as well as random.shuffle perform in-place shuffling. However, if you want to return a shuffled array numpy.random.permutation is the function to use.

Naming returned columns in Pandas aggregate function?

If you want to have a behavior similar to JMP, creating column titles that keep all info from the multi index you can use:

newidx = []
for (n1,n2) in df.columns.ravel():
    newidx.append("%s-%s" % (n1,n2))
df.columns=newidx

It will change your dataframe from:

    I                       V
    mean        std         first
V
4200.0  25.499536   31.557133   4200.0
4300.0  25.605662   31.678046   4300.0
4400.0  26.679005   32.919996   4400.0
4500.0  26.786458   32.811633   4500.0

to

    I-mean      I-std       V-first
V
4200.0  25.499536   31.557133   4200.0
4300.0  25.605662   31.678046   4300.0
4400.0  26.679005   32.919996   4400.0
4500.0  26.786458   32.811633   4500.0

Undefined reference to pow( ) in C, despite including math.h

You need to link with the math library:

gcc -o sphere sphere.c -lm

The error you are seeing: error: ld returned 1 exit status is from the linker ld (part of gcc that combines the object files) because it is unable to find where the function pow is defined.

Including math.h brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a. You need to link your program with this library so that the calls to functions like pow() are resolved.

SOAP request to WebService with java

When the WSDL is available, it is just two steps you need to follow to invoke that web service.

Step 1: Generate the client side source from a WSDL2Java tool

Step 2: Invoke the operation using:

YourService service = new YourServiceLocator();
Stub stub = service.getYourStub();
stub.operation();

If you look further, you will notice that the Stub class is used to invoke the service deployed at the remote location as a web service. When invoking that, your client actually generates the SOAP request and communicates. Similarly the web service sends the response as a SOAP. With the help of a tool like Wireshark, you can view the SOAP messages exchanged.

However since you have requested more explanation on the basics, I recommend you to refer here and write a web service with it's client to learn it further.

Invalid application path

The error message might be a bug. I ignored it and everything worked for me.

IIS Invalid Application Path Screen Shot

See Here: http://forums.iis.net/t/1177952.aspx

and here http://forums.iis.net/p/1182820/2000936.aspx

ASP.NET 5 MVC: unable to connect to web server 'IIS Express'

If you can afford to restart your machine then do it, this fixed my issue after almost an hour of trying to fix this issue with no hope.

How to automatically generate N "distinct" colors?

Here's an idea. Imagine an HSV cylinder

Define the upper and lower limits you want for the Brightness and Saturation. This defines a square cross section ring within the space.

Now, scatter N points randomly within this space.

Then apply an iterative repulsion algorithm on them, either for a fixed number of iterations, or until the points stabilise.

Now you should have N points representing N colours that are about as different as possible within the colour space you're interested in.

Hugo

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

I faced exactly the same issue in a Spring web app. In fact, I had removed spring-security by commenting the config annotation:

// @ImportResource({"/WEB-INF/spring-security.xml"})

but I had forgotten to remove the corresponding filters in web.xml:

<!-- Filters --> 
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Commenting filters solved the issue.

Using sendmail from bash script for multiple recipients

Try doing this :

recipients="[email protected],[email protected],[email protected]"

And another approach, using shell here-doc :

/usr/sbin/sendmail "$recipients" <<EOF
subject:$subject
from:$from

Example Message
EOF

Be sure to separate the headers from the body with a blank line as per RFC 822.

pip install mysql-python fails with EnvironmentError: mysql_config not found

Sequence to be followed.

pip install mysqlclient
sudo apt-get install python3-dev libmysqlclient-dev
pip install configparser 
sudo cp /usr/lib/python3.6/configparser.py /usr/lib/python3.6/ConfigParser.py 

Then try to install the MYSQL-python again. That Worked for me

How can I call PHP functions by JavaScript?

This work perfectly for me:

To call a PHP function (with parameters too) you can, like a lot of people said, send a parameter opening the PHP file and from there check the value of the parameter to call the function. But you can also do that lot of people say it's impossible: directly call the proper PHP function, without adding code to the PHP file.

I found a way:

This for JavaScript:

function callPHP(expression, objs, afterHandler) {
        expression = expression.trim();
        var si = expression.indexOf("(");
        if (si == -1)
            expression += "()";
        else if (Object.keys(objs).length > 0) {
            var sfrom = expression.substring(si + 1);
            var se = sfrom.indexOf(")");
            var result = sfrom.substring(0, se).trim();
            if (result.length > 0) {
                var params = result.split(",");
                var theend = expression.substring(expression.length - sfrom.length + se);
                expression = expression.substring(0, si + 1);
                for (var i = 0; i < params.length; i++) {
                    var param = params[i].trim();
                    if (param in objs) {
                        var value = objs[param];
                        if (typeof value == "string")
                            value = "'" + value + "'";
                        if (typeof value != "undefined")
                            expression += value + ",";
                    }
                }
                expression = expression.substring(0, expression.length - 1) + theend;
            }
        }
        var doc = document.location;
        var phpFile = "URL of your PHP file";
        var php =
            "$docl = str_replace('/', '\\\\', '" + doc + "'); $absUrl = str_replace($docl, $_SERVER['DOCUMENT_ROOT'], str_replace('/', '\\\\', '" + phpFile + "'));" +
            "$fileName = basename($absUrl);$folder = substr($absUrl, 0, strlen($absUrl) - strlen($fileName));" +
            "set_include_path($folder);include $fileName;" + expression + ";";
        var url = doc + "/phpCompiler.php" + "?code=" + encodeURIComponent(php);
        $.ajax({
            type: 'GET',
            url: url,
            complete: function(resp){
                var response = resp.responseText;
                afterHandler(response);
            }
        });
    }


This for a PHP file which isn't your PHP file, but another, which path is written in url variable of JS function callPHP , and it's required to evaluate PHP code. This file is called 'phpCompiler.php' and it's in the root directory of your website:

<?php
$code = urldecode($_REQUEST['code']);
$lines = explode(";", $code);
foreach($lines as $line)
    eval(trim($line, " ") . ";");
?>


So, your PHP code remain equals except return values, which will be echoed:

<?php
function add($a,$b){
  $c=$a+$b;
  echo $c;
}
function mult($a,$b){
  $c=$a*$b;
  echo $c;
}

function divide($a,$b){
  $c=$a/$b;
  echo $c;
}
?>


I suggest you to remember that jQuery is required:
Download it from Google CDN:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

or from Microsoft CDN: "I prefer Google! :)"

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>

Better is to download the file from one of two CDNs and put it as local file, so the startup loading of your website's faster!

The choice is to you!


Now you finished! I just tell you how to use callPHP function. This is the JavaScript to call PHP:

//Names of parameters are custom, they haven't to be equals of these of the PHP file.
//These fake names are required to assign value to the parameters in PHP
//using an hash table.
callPHP("add(num1, num2)", {
            'num1' : 1,
            'num2' : 2
        },
            function(output) {
                alert(output); //This to display the output of the PHP file.
        });

Making custom right-click context menus for my web-app

Simple One

  1. show context menu when right click anywhere in document
  2. avoid context menu hide when click inside context menu
  3. close context menu when press left mouse button

Note: dont use display:none instead use opacity to hide and show

_x000D_
_x000D_
var menu= document.querySelector('.context_menu');
document.addEventListener("contextmenu", function(e) {      
            e.preventDefault();  
            menu.style.position = 'absolute';
            menu.style.left = e.pageX + 'px';
            menu.style.top = e.pageY + 'px';        
             menu.style.opacity = 1;
        });
       
  document.addEventListener("click", function(e){
  if(e.target.closest('.context_menu'))
  return;
      menu.style.opacity = 0;
  });
_x000D_
.context_menu{

width:70px;
background:lightgrey;
padding:5px;
 opacity :0;
}
.context_menu div{
margin:5px;
background:grey;

}
.context_menu div:hover{
margin:5px;
background:red;
   cursor:pointer;

}
_x000D_
<div class="context_menu">
<div>menu 1</div>
<div>menu 2</div>
</div>
_x000D_
_x000D_
_x000D_

extra css

_x000D_
_x000D_
var menu= document.querySelector('.context_menu');
document.addEventListener("contextmenu", function(e) {      
            e.preventDefault();  
            menu.style.position = 'absolute';
            menu.style.left = e.pageX + 'px';
            menu.style.top = e.pageY + 'px';        
             menu.style.opacity = 1;
        });
       
  document.addEventListener("click", function(e){
  if(e.target.closest('.context_menu'))
  return;
      menu.style.opacity = 0;
  });
_x000D_
.context_menu{

width:120px;
background:white;
border:1px solid lightgrey;

 opacity :0;
}
.context_menu div{
padding:5px;
padding-left:15px;
margin:5px 2px;
border-bottom:1px solid lightgrey;
}
.context_menu div:last-child {
border:none;
}
.context_menu div:hover{

background:lightgrey;
   cursor:pointer;

}
_x000D_
<div class="context_menu">
<div>menu 1</div>
<div>menu 2</div>
<div>menu 3</div>
<div>menu 4</div>
</div>
_x000D_
_x000D_
_x000D_

Add / remove input field dynamically with jQuery

Jquery Code

$(document).ready(function() {
    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID

    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
        }
    });

    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});

HTML CODE

<div class="input_fields_wrap">
    <button class="add_field_button">Add More Fields</button>
    <div><input type="text" name="mytext[]"></div>
</div>

PHP Error: Cannot use object of type stdClass as array (array and object issues)

$blog is an object, not an array, so you should access it like so:

$blog->id;
$blog->title;
$blog->content;

No generated R.java file in my project

Probably u might be using a incorrect SDK version. Right click on your project. Select Properties-->Android. Note that 2.2 is the latest SDK. Check it and see if it gets compiled...

Edit

Also Do a clean after that

CustomErrors mode="Off"

Also make sure you're editing web.config and not website.config, as I was doing.

Comparing two hashmaps for equal values and same key sets?

if you have two maps lets say map1 and map2 then using java8 Streams,we can compare maps using code below.But it is recommended to use equals rather then != or ==

boolean b = map1.entrySet().stream().filter(value -> 
            map2.entrySet().stream().anyMatch(value1 -> 
            (value1.getKey().equals(value.getKey()) && 
  value1.getValue().equals(value.getValue())))).findAny().isPresent();   


System.out.println("comparison  "+b);

How to make MySQL table primary key auto increment with some prefix

Create a table with a normal numeric auto_increment ID, but either define it with ZEROFILL, or use LPAD to add zeroes when selecting. Then CONCAT the values to get your intended behavior. Example #1:

create table so (
 id int(3) unsigned zerofill not null auto_increment primary key,
 name varchar(30) not null
);

insert into so set name = 'John';
insert into so set name = 'Mark';

select concat('LHPL', id) as id, name from so;
+---------+------+
| id      | name |
+---------+------+
| LHPL001 | John |
| LHPL002 | Mark |
+---------+------+

Example #2:

create table so (
 id int unsigned not null auto_increment primary key,
 name varchar(30) not null
);

insert into so set name = 'John';
insert into so set name = 'Mark';

select concat('LHPL', LPAD(id, 3, 0)) as id, name from so;
+---------+------+
| id      | name |
+---------+------+
| LHPL001 | John |
| LHPL002 | Mark |
+---------+------+

Is there a simple way that I can sort characters in a string in alphabetical order

You can use LINQ:

String.Concat(str.OrderBy(c => c))

If you want to remove duplicates, add .Distinct().

What is the difference between application server and web server?

Application server and web server both are used to host web application. Web Server is deal with web container on the other hand Application Server is deal with web container as well as EJB (Enterprise JavaBean) container or COM+ container for Microsoft dot Net.

Web Server is designed to serve HTTP static Content like HTML, images etc. and for the dynamic content have plugins to support scripting languages like Perl, PHP, ASP, JSP etc and it is limited to HTTP protocol. Below servers can generate dynamic HTTP content.

Web Server's Programming Environment:

IIS : ASP (.NET)

Apache Tomcat: Servlet

Jetty: Servlet

Apache: Php, CGI

Application Server can do whatever Web Server is capable and listens using any protocol as well as App Server have components and features to support Application level services such as Connection Pooling, Object Pooling, Transaction Support, Messaging services etc.

Application Server's Programming Environment:

MTS: COM+

WAS: EJB

JBoss: EJB

WebLogic Application Server: EJB

Setting different color for each series in scatter plot on matplotlib

A MUCH faster solution for large dataset and limited number of colors is the use of Pandas and the groupby function:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import time


# a generic set of data with associated colors
nsamples=1000
x=np.random.uniform(0,10,nsamples)
y=np.random.uniform(0,10,nsamples)
colors={0:'r',1:'g',2:'b',3:'k'}
c=[colors[i] for i in np.round(np.random.uniform(0,3,nsamples),0)]

plt.close('all')

# "Fast" Scatter plotting
starttime=time.time()
# 1) make a dataframe
df=pd.DataFrame()
df['x']=x
df['y']=y
df['c']=c
plt.figure()
# 2) group the dataframe by color and loop
for g,b in df.groupby(by='c'):
    plt.scatter(b['x'],b['y'],color=g)
print('Fast execution time:', time.time()-starttime)

# "Slow" Scatter plotting
starttime=time.time()
plt.figure()
# 2) group the dataframe by color and loop
for i in range(len(x)):
    plt.scatter(x[i],y[i],color=c[i])
print('Slow execution time:', time.time()-starttime)

plt.show()

Mockito verify order / sequence of method calls

With BDD it's

@Test
public void testOrderWithBDD() {


    // Given
    ServiceClassA firstMock = mock(ServiceClassA.class);
    ServiceClassB secondMock = mock(ServiceClassB.class);

    //create inOrder object passing any mocks that need to be verified in order
    InOrder inOrder = inOrder(firstMock, secondMock);

    willDoNothing().given(firstMock).methodOne();
    willDoNothing().given(secondMock).methodTwo();

    // When
    firstMock.methodOne();
    secondMock.methodTwo();

    // Then
    then(firstMock).should(inOrder).methodOne();
    then(secondMock).should(inOrder).methodTwo();


}

How to close a web page on a button click, a hyperlink or a link button click?

Assuming you're using WinForms, as it was the first thing I did when I was starting C# you need to create an event to close this form.

Lets say you've got a button called myNewButton. If you double click it on WinForms designer you will create an event. After that you just have to use this.Close

    private void myNewButton_Click(object sender, EventArgs e) {
        this.Close();
    }

And that should be it.

The only reason for this not working is that your Event is detached from button. But it should create new event if old one is no longer attached when you double click on the button in WinForms designer.

How to verify if $_GET exists?

You are use PHP isset

Example

if (isset($_GET["id"])) {
    echo $_GET["id"];
}

Login to website, via C#

Sometimes, it may help switching off AllowAutoRedirect and setting both login POST and page GET requests the same user agent.

request.UserAgent = userAgent;
request.AllowAutoRedirect = false;

How do I remove background-image in css?

Doesn't this work:

.clear-background{
background-image: none;
}

Might have problems on older browsers...

Ruby: How to iterate over a range, but in set increments?

Here's another, perhaps more familiar-looking way to do it:

for i in (0..10).step(2) do
    puts i
end

How can I replace non-printable Unicode characters in Java?

You may be interested in the Unicode categories "Other, Control" and possibly "Other, Format" (unfortunately the latter seems to contain both unprintable and printable characters).

In Java regular expressions you can check for them using \p{Cc} and \p{Cf} respectively.

Single Form Hide on Startup

Based on various suggestions, all I had to do was this:

To hide the form:

Me.Opacity = 0
Me.ShowInTaskbar = false

To show the form:

Me.Opacity = 100
Me.ShowInTaskbar = true

Loading inline content using FancyBox

Just something I found for Wordpress users,

As obvious as it sounds, If your div is returning some AJAX content based on say a header that would commonly link out to a new post page, some tutorials will say to return false since you're returning the post data on the same page and the return would prevent the page from moving. However if you return false, you also prevent Fancybox2 from doing it's thing as well. I spent hours trying to figure that stupid simple thing out.

So for these kind of links, just make sure that the href property is the hashed (#) div you wish to select, and in your javascript, make sure that you do not return false since you no longer will need to.

Simple I know ^_^

What's the difference between ng-model and ng-bind

ng-model

ng-model directive in AngularJS is one of the greatest strength to bind the variables used in application with input components. This works as two way data binding. If you want to understand better about the two way bindings, you have an input component and the value updated into that field must be reflected in other part of the application. The better solution is to bind a variable to that field and output that variable whereever you wish to display the updated value throughoput the application.

ng-bind

ng-bind works much different than ng-model. ng-bind is one way data binding used for displaying the value inside html component as inner HTML. This directive can not be used for binding with the variable but only with the HTML elements content. Infact this can be used along with ng-model to bind the component to HTML elements. This directive is very useful for updating the blocks like div, span, etc. with inner HTML content.

This example would help you to understand.

jQuery vs document.querySelectorAll

Here's a comparison if I want to apply the same attribute, e.g. hide all elements of class "my-class". This is one reason to use jQuery.

jQuery:

$('.my-class').hide();

JavaScript:

var cls = document.querySelectorAll('.my-class');
for (var i = 0; i < cls.length; i++) {
    cls[i].style.display = 'none';
}

With jQuery already so popular, they should have made document.querySelector() behave just like $(). Instead, document.querySelector() only selects the first matching element which makes it only halfway useful.

Get Locale Short Date Format using javascript

Try this:

new Date().toLocaleFormat("%x");

All formats for this function can be found here: http://pubs.opengroup.org/onlinepubs/007908799/xsh/strftime.html

Ruby Arrays: select(), collect(), and map()

EDIT: I just realized you want to filter details, which is an array of hashes. In that case you could do

details.reject { |item| item[:qty].empty? }

The inner data structure itself is not an Array, but a Hash. You can also use select here, but the block is given the key and value in this case:

irb(main):001:0> h = {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", :qty=>"", :qty2=>"1", :price=>"5,204.34 P"}
irb(main):002:0> h.select { |key, value| !value.empty? }
=> {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", 
    :qty2=>"1", :price=>"5,204.34 P"}

Or using reject, which is the inverse of select (excludes all items for which the given condition holds):

h.reject { |key, value| value.empty? }

Note that this is Ruby 1.9. If you have to maintain compatibility with 1.8, you could do:

Hash[h.reject { |key, value| value.empty? }]

Python JSON encoding

JSON uses square brackets for lists ( [ "one", "two", "three" ] ) and curly brackets for key/value dictionaries (also called objects in JavaScript, {"one":1, "two":"b"}).

The dump is quite correct, you get a list of three elements, each one is a list of two strings.

if you wanted a dictionary, maybe something like this:

x = simplejson.dumps(dict(data))
>>> {"pear": "fish", "apple": "cat", "banana": "dog"}

your expected string ('{{"apple":{"cat"},{"banana":"dog"}}') isn't valid JSON. A

Perform an action in every sub-directory using Bash

Use find command.

In GNU find, you can use -execdir parameter:

find . -type d -execdir realpath "{}" ';'

or by using -exec parameter:

find . -type d -exec sh -c 'cd -P "$0" && pwd -P' {} \;

or with xargs command:

find . -type d -print0 | xargs -0 -L1 sh -c 'cd "$0" && pwd && echo Do stuff'

Or using for loop:

for d in */; { echo "$d"; }

For recursivity try extended globbing (**/) instead (enable by: shopt -s extglob).


For more examples, see: How to go to each directory and execute a command? at SO

Difference between x86, x32, and x64 architectures?

x86 refers to the Intel processor architecture that was used in PCs. Model numbers were 8088 (8 bit bus version of 8086 and used in the first IBM PC), 8086, 286, 386, 486. After which they switched to names instead of numbers to stop AMD from copying the processor names. Pentium etc, never a Hexium :).

x64 is the architecture name for the extensions to the x86 instruction set that enable 64-bit code. Invented by AMD and later copied by Intel when they couldn't get their own 64-bit arch to be competitive, Itanium didn't fare well. Other names for it are x86_64, AMD's original name and commonly used in open source tools. And amd64, AMD's next name and commonly used in Microsoft tools. Intel's own names for it (EM64T and "Intel 64") never caught on.

x32 is a fuzzy term that's not associated with hardware. It tends to be used to mean "32-bit" or "32-bit pointer architecture", Linux has an ABI by that name.

Angular ng-click with call to a controller function not working

You should probably use the ngHref directive along with the ngClick:

 <a ng-href='#here' ng-click='go()' >click me</a>

Here is an example: http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview

<body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    {{msg}}
    <a ng-href='#here' ng-click='go()' >click me</a>
    <div style='height:1000px'>

      <a id='here'></a>

    </div>
     <h1>here</h1>
  </body>

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';

  $scope.go = function() {

    $scope.msg = 'clicked';
  }
});

I don't know if this will work with the library you are using but it will at least let you link and use the ngClick function.

** Update **

Here is a demo of the set and get working fine with a service.

http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, sharedProperties) {
  $scope.name = 'World';

  $scope.go = function(item) {
    sharedProperties.setListName(item);


  }

  $scope.getItem = function() {

    $scope.msg = sharedProperties.getListName();
  }
});

app.service('sharedProperties', function () {
    var list_name = '';

    return {

        getListName: function() {
            return list_name;
        },
        setListName: function(name) {
            list_name = name;
        }
    };


});

* Edit *

Please review https://github.com/centralway/lungo-angular-bridge which talks about how to use lungo and angular. Also note that if your page is completely reloading when browsing to another link, you will need to persist your shared properties into localstorage and/or a cookie.

What is the difference between the operating system and the kernel?

Basically the Kernel is the interface between hardware (devices which are available in Computer) and Application software is like MS Office, Visual Studio, etc.

If I answer "what is an OS?" then the answer could be the same. Hence the kernel is the part & core of the OS.

The very sensitive tasks of an OS like memory management, I/O management, process management are taken care of by the kernel only.

So the ultimate difference is:

  1. Kernel is responsible for Hardware level interactions at some specific range. But the OS is like hardware level interaction with full scope of computer.
  2. Kernel triggers SystemCalls to tell the OS that this resource is available at this point of time. The OS is responsible to handle those system calls in order to utilize the resource.

What are the differences between Abstract Factory and Factory design patterns?

Allow me to put it precisely. Most of the answers have already explained, provided diagrams and examples as well.

So my answer would just be a one-liner. My own words: “An abstract factory pattern adds on the abstract layer over multiple factory method implementations. It means an abstract factory contains or composite one or more than one factory method pattern”

django admin - add custom form fields that are not part of the model

It it possible to do in the admin, but there is not a very straightforward way to it. Also, I would like to advice to keep most business logic in your models, so you won't be dependent on the Django Admin.

Maybe it would be easier (and maybe even better) if you have the two seperate fields on your model. Then add a method on your model that combines them.

For example:

class MyModel(models.model):

    field1 = models.CharField(max_length=10)
    field2 = models.CharField(max_length=10)

    def combined_fields(self):
        return '{} {}'.format(self.field1, self.field2)

Then in the admin you can add the combined_fields() as a readonly field:

class MyModelAdmin(models.ModelAdmin):

    list_display = ('field1', 'field2', 'combined_fields')
    readonly_fields = ('combined_fields',)

    def combined_fields(self, obj):
        return obj.combined_fields()

If you want to store the combined_fields in the database you could also save it when you save the model:

def save(self, *args, **kwargs):
    self.field3 = self.combined_fields()
    super(MyModel, self).save(*args, **kwargs)

How to Split Image Into Multiple Pieces in Python

Not sure if this is the most efficient answer, but it works for me:

import os
import glob
from PIL import Image
Image.MAX_IMAGE_PIXELS = None # to avoid image size warning

imgdir = "/path/to/image/folder"
# if you want file of a specific extension (.png):
filelist = [f for f in glob.glob(imgdir + "**/*.png", recursive=True)]
savedir = "/path/to/image/folder/output"

start_pos = start_x, start_y = (0, 0)
cropped_image_size = w, h = (500, 500)

for file in filelist:
    img = Image.open(file)
    width, height = img.size

    frame_num = 1
    for col_i in range(0, width, w):
        for row_i in range(0, height, h):
            crop = img.crop((col_i, row_i, col_i + w, row_i + h))
            name = os.path.basename(file)
            name = os.path.splitext(name)[0]
            save_to= os.path.join(savedir, name+"_{:03}.png")
            crop.save(save_to.format(frame_num))
            frame_num += 1

This is mostly based on DataScienceGuy answer here

Get attribute name value of <input>

Use the attr method of jQuery like this:

alert($('input').attr('name'));

Note that you can also use attr to set the attribute values by specifying second argument:

$('input').attr('name', 'new_name')

Difference between $(this) and event.target?

There is a significant different in how jQuery handles the this variable with a "on" method

$("outer DOM element").on('click',"inner DOM element",function(){
  $(this) // refers to the "inner DOM element"
})

If you compare this with :-

$("outer DOM element").click(function(){
  $(this) // refers to the "outer DOM element"
})

Relative paths in Python

This code will return the absolute path to the main script.

import os
def whereAmI():
    return os.path.dirname(os.path.realpath(__import__("__main__").__file__))

This will work even in a module.

Unzip files programmatically in .net

From Embed Ressources:

using (Stream _pluginZipResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(programName + "." + "filename.zip"))
{
    using (ZipArchive zip = new ZipArchive(_pluginZipResourceStream))
    {
        zip.ExtractToDirectory(Application.StartupPath);
    }
}

Best method for reading newline delimited files and discarding the newlines?

What do you think about this approach?

with open(filename) as data:
    datalines = (line.rstrip('\r\n') for line in data)
    for line in datalines:
        ...do something awesome...

Generator expression avoids loading whole file into memory and with ensures closing the file

How to get HttpClient to pass credentials along with the request?

What you are trying to do is get NTLM to forward the identity on to the next server, which it cannot do - it can only do impersonation which only gives you access to local resources. It won't let you cross a machine boundary. Kerberos authentication supports delegation (what you need) by using tickets, and the ticket can be forwarded on when all servers and applications in the chain are correctly configured and Kerberos is set up correctly on the domain. So, in short you need to switch from using NTLM to Kerberos.

For more on Windows Authentication options available to you and how they work start at: http://msdn.microsoft.com/en-us/library/ff647076.aspx

Class vs. static method in JavaScript

If you have to write static methods in ES5 I found a great tutorial for that:

//Constructor
var Person = function (name, age){
//private properties
var priv = {};

//Public properties
this.name = name;
this.age = age;

//Public methods
this.sayHi = function(){
    alert('hello');
}
}


// A static method; this method only 
// exists on the class and doesn't exist  
// on child objects
Person.sayName = function() {
   alert("I am a Person object ;)");  
};

see @https://abdulapopoola.com/2013/03/30/static-and-instance-methods-in-javascript/

How to render pdfs using C#

PdfiumViewer is great, but relatively tightly coupled to System.Drawingand WinForms. For this reason I created my own wrapper around PDFium: PDFiumSharp

Pages can be rendered to a PDFiumBitmap which in turn can be saved to disk or exposed as a stream. This way any framework capable of loading an image in BMP format from a stream can use this library to display pdf pages.

For example in a WPF application you could use the following method to render a pdf page:

using System.Linq;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using PDFiumSharp;

static class PdfRenderer
{
    public static ImageSource RenderPage(string filename, int pageIndex, string password = null, bool withTransparency = true)
    {
        using (var doc = new PdfDocument(filename, password))
        {
            var page = doc.Pages[pageIndex];
            using (var bitmap = new PDFiumBitmap((int)page.Width, (int)page.Height, withTransparency))
            {
                page.Render(bitmap);
                return new BmpBitmapDecoder(bitmap.AsBmpStream(), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();
            }
        }
    }
}

Running Git through Cygwin from Windows

I can tell you from personal experience this is a bad idea. Native Windows programs cannot accept Cygwin paths. For example with Cygwin you might run a command

grep -r --color foo /opt

with no issue. With Cygwin / represents the root directory. Native Windows programs have no concept of this, and will likely fail if invoked this way. You should not mix Cygwin and Native Windows programs unless you have no other choice.

Uninstall what Git you have and install the Cygwin git package, save yourself the headache.

Display a tooltip over a button using Windows Forms

Using the form designer:

  • Drag the ToolTip control from the Toolbox, onto the form.
  • Select the properties of the control you want the tool tip to appear on.
  • Find the property 'ToolTip on toolTip1' (the name may not be toolTip1 if you changed it's default name).
  • Set the text of the property to the tool tip text you would like to display.

You can set also the tool tip programatically using the following call:

this.toolTip1.SetToolTip(this.targetControl, "My Tool Tip");

Easier way to create circle div than using an image?

I have 4 solution to finish this task:

  1. border-radius
  2. clip-path
  3. pseudo elements
  4. radial-gradient

_x000D_
_x000D_
#circle1 {
  background-color: #B90136;
  width: 100px;
  height: 100px;
  border-radius: 50px;/* specify the radius */
}

#circle2 {
  background-color: #B90136;
  width: 100px;/* specify the radius */
  height: 100px;/* specify the radius */
  clip-path: circle();
}

#circle3::before {
  content: "";
  display: block;
  width: 100px;
  height: 100px;
  border-radius: 50px;/* specify the radius */
  background-color: #B90136;
}

#circle4 {
  background-image: radial-gradient(#B90136 70%, transparent 30%);
  height: 100px;/* specify the radius */
  width: 100px;/* specify the radius */
}
_x000D_
<h3>1 border-radius</h3>
<div id="circle1"></div>
<hr/>
<h3>2 clip-path</h3>
<div id="circle2"></div>
<hr/>
<h3>3 pseudo element</h3>
<div id="circle3"></div>
<hr/>
<h3>4 radial-gradient</h3>
<div id="circle4"></div>
_x000D_
_x000D_
_x000D_

How can I write variables inside the tasks file in ansible

Variable definitions are meant to be used in tasks. But if you want to include them in tasks probably use the register directive. Like this:

- name: Define variable in task.
  shell: echo "http://www.my.url.com"
  register: url

- name: Download apache
  shell: wget {{ item }}
  with_items: url.stdout

You can also look at roles as a way of separating tasks depending on the different roles roles. This way you can have separate variables for each of one of your roles. For example you may have a url variable for apache1 and a separate url variable for the role apache2.

How to comment multiple lines in Visual Studio Code?

In Windows

Select the lines you want to comment. Then press Ctrl + /

How to check if IsNumeric

There's a slightly better way:

int valueParsed;
if(Int32.TryParse(txtMyText.Text.Trim(), out valueParsed))
{ ... }

If you try to parse the text and it can't be parsed, the Int32.Parse method will raise an exception. I think it is better for you to use the TryParse method which will capture the exception and let you know as a boolean if any exception was encountered.

There are lot of complications in parsing text which Int32.Parse takes into account. It is foolish to duplicate the effort. As such, this is very likely the approach taken by VB's IsNumeric. You can also customize the parsing rules through the NumberStyles enumeration to allow hex, decimal, currency, and a few other styles.

Another common approach for non-web based applications is to restrict the input of the text box to only accept characters which would be parseable into an integer.

EDIT: You can accept a larger variety of input formats, such as money values ("$100") and exponents ("1E4"), by specifying the specific NumberStyles:

int valueParsed;
if(Int32.TryParse(txtMyText.Text.Trim(), NumberStyles.AllowCurrencySymbol | NumberStyles.AllowExponent, CultureInfo.CurrentCulture, out valueParsed))
{ ... }

... or by allowing any kind of supported formatting:

int valueParsed;
if(Int32.TryParse(txtMyText.Text.Trim(), NumberStyles.Any, CultureInfo.CurrentCulture, out valueParsed))
{ ... }

Difference between attr_accessor and attr_accessible

Many people on this thread and on google explain very well that attr_accessible specifies a whitelist of attributes that are allowed to be updated in bulk (all the attributes of an object model together at the same time) This is mainly (and only) to protect your application from "Mass assignment" pirate exploit.

This is explained here on the official Rails doc : Mass Assignment

attr_accessor is a ruby code to (quickly) create setter and getter methods in a Class. That's all.

Now, what is missing as an explanation is that when you create somehow a link between a (Rails) model with a database table, you NEVER, NEVER, NEVER need attr_accessor in your model to create setters and getters in order to be able to modify your table's records.

This is because your model inherits all methods from the ActiveRecord::Base Class, which already defines basic CRUD accessors (Create, Read, Update, Delete) for you. This is explained on the offical doc here Rails Model and here Overwriting default accessor (scroll down to the chapter "Overwrite default accessor")

Say for instance that: we have a database table called "users" that contains three columns "firstname", "lastname" and "role" :

SQL instructions :

CREATE TABLE users (
  firstname string,
  lastname string
  role string
);

I assumed that you set the option config.active_record.whitelist_attributes = true in your config/environment/production.rb to protect your application from Mass assignment exploit. This is explained here : Mass Assignment

Your Rails model will perfectly work with the Model here below :

class User < ActiveRecord::Base

end

However you will need to update each attribute of user separately in your controller for your form's View to work :

def update
    @user = User.find_by_id(params[:id])
    @user.firstname = params[:user][:firstname]
    @user.lastname = params[:user][:lastname]

    if @user.save
        # Use of I18 internationalization t method for the flash message
        flash[:success] = t('activerecord.successful.messages.updated', :model => User.model_name.human)
    end

    respond_with(@user)
end

Now to ease your life, you don't want to make a complicated controller for your User model. So you will use the attr_accessible special method in your Class model :

class User < ActiveRecord::Base

  attr_accessible :firstname, :lastname

end

So you can use the "highway" (mass assignment) to update :

def update
    @user = User.find_by_id(params[:id])

    if @user.update_attributes(params[:user])
        # Use of I18 internationlization t method for the flash message
        flash[:success] = t('activerecord.successful.messages.updated', :model => User.model_name.human)
    end

    respond_with(@user)
end

You didn't add the "role" attributes to the attr_accessible list because you don't let your users set their role by themselves (like admin). You do this yourself on another special admin View.

Though your user view doesn't show a "role" field, a pirate could easily send a HTTP POST request that include "role" in the params hash. The missing "role" attribute on the attr_accessible is to protect your application from that.

You can still modify your user.role attribute on its own like below, but not with all attributes together.

@user.role = DEFAULT_ROLE

Why the hell would you use the attr_accessor?

Well, this would be in the case that your user-form shows a field that doesn't exist in your users table as a column.

For instance, say your user view shows a "please-tell-the-admin-that-I'm-in-here" field. You don't want to store this info in your table. You just want that Rails send you an e-mail warning you that one "crazy" ;-) user has subscribed.

To be able to make use of this info you need to store it temporarily somewhere. What more easy than recover it in a user.peekaboo attribute ?

So you add this field to your model :

class User < ActiveRecord::Base

  attr_accessible :firstname, :lastname
  attr_accessor :peekaboo

end

So you will be able to make an educated use of the user.peekaboo attribute somewhere in your controller to send an e-mail or do whatever you want.

ActiveRecord will not save the "peekaboo" attribute in your table when you do a user.save because she don't see any column matching this name in her model.

Count specific character occurrences in a string

I use LINQ, and the solution is very simple:

Code in C#:

count = yourString.ToCharArray().Count(c => c == 'e');

The code in a function:

public static int countTheCharacters(string str, char charToCount){
   return str.ToCharArray().Count(c => c == charToCount);
}

Call the function:

count = countTheCharacters(yourString, 'e');

How to compile LEX/YACC files on Windows?

As for today (2011-04-05, updated 2017-11-29) you will need the lastest versions of:

  1. flex-2.5.4a-1.exe

  2. bison-2.4.1-setup.exe

  3. After that, do a full install in a directory of your preference without spaces in the name. I suggest C:\GnuWin32. Do not install it in the default (C:\Program Files (x86)\GnuWin32) because bison has problems with spaces in directory names, not to say parenthesis.

  4. Also, consider installing Dev-CPP in the default directory (C:\Dev-Cpp)

  5. After that, set the PATH variable to include the bin directories of gcc (in C:\Dev-Cpp\bin) and flex\bison (in C:\GnuWin32\bin). To do that, copy this: ;C:\Dev-Cpp\bin;C:\GnuWin32\bin and append it to the end of the PATH variable, defined in the place show by this figure:
    step-by-step to set PATH variable under Win-7.
    If the figure is not in good resolution, you can see a step-by-step here.

  6. Open a prompt, cd to the directory where your ".l" and ".y" are, and compile them with:

    1. flex hello.l
    2. bison -dy hello.y
    3. gcc lex.yy.c y.tab.c -o hello.exe

Commands to create lexical analyzer, parser and executable.

You will be able to run the program. I made the sources for a simple test (the infamous Hello World):

Hello.l

%{

#include "y.tab.h"
int yyerror(char *errormsg);

%}

%%

("hi"|"oi")"\n"       { return HI;  }
("tchau"|"bye")"\n"   { return BYE; }
.                     { yyerror("Unknown char");  }

%%

int main(void)
{
   yyparse();
   return 0;
}

int yywrap(void)
{
   return 0;
}

int yyerror(char *errormsg)
{
    fprintf(stderr, "%s\n", errormsg);
    exit(1);
}

Hello.y

%{

#include <stdio.h>
#include <stdlib.h>
int yylex(void);
int yyerror(const char *s);

%}

%token HI BYE

%%

program: 
         hi bye
        ;

hi:     
        HI     { printf("Hello World\n");   }
        ;
bye:    
        BYE    { printf("Bye World\n"); exit(0); }
         ;

Edited: avoiding "warning: implicit definition of yyerror and yylex".

Disclaimer: remember, this answer is very old (since 2011!) and if you run into problems due to versions and features changing, you might need more research, because I can't update this answer to reflect new itens. Thanks and I hope this will be a good entry point for you as it was for many.

Updates: if something (really small changes) needs to be done, please check out the official repository at github: https://github.com/drbeco/hellex

Happy hacking.

Ansible: Set variable to file content

You can use lookups in Ansible in order to get the contents of a file, e.g.

user_data: "{{ lookup('file', user_data_file) }}"

Caveat: This lookup will work with local files, not remote files.

Here's a complete example from the docs:

- hosts: all
  vars:
     contents: "{{ lookup('file', '/etc/foo.txt') }}"
  tasks:
     - debug: msg="the value of foo.txt is {{ contents }}"

Python dictionary: are keys() and values() always the same order?

I wasn't satisfied with these answers since I wanted to ensure the exported values had the same ordering even when using different dicts.

Here you specify the key order upfront, the returned values will always have the same order even if the dict changes, or you use a different dict.

keys = dict1.keys()
ordered_keys1 = [dict1[cur_key] for cur_key in keys]
ordered_keys2 = [dict2[cur_key] for cur_key in keys]

Why doesn't Python have multiline comments?

Multi-line comments are easily breakable. What if you have the following in a simple calculator program?

operation = ''
print("Pick an operation:  +-*/")
# Get user input here

Try to comment that with a multi-line comment:

/*
operation = ''
print("Pick an operation:  +-*/")
# Get user input here
*/

Oops, your string contains the end comment delimiter.

Force add despite the .gitignore file

Another way of achieving it would be to temporary edit the gitignore file, add the file and then revert back the gitignore. A bit hacky i feel

Loop through list with both content and index

Like everyone else:

for i, val in enumerate(data):
    print i, val

but also

for i, val in enumerate(data, 1):
    print i, val

In other words, you can specify as starting value for the index/count generated by enumerate() which comes in handy if you don't want your index to start with the default value of zero.

I was printing out lines in a file the other day and specified the starting value as 1 for enumerate(), which made more sense than 0 when displaying information about a specific line to the user.

Deleting all pending tasks in celery / rabbitmq

1. To properly purge the queue of waiting tasks you have to stop all the workers (http://celery.readthedocs.io/en/latest/faq.html#i-ve-purged-messages-but-there-are-still-messages-left-in-the-queue):

$ sudo rabbitmqctl stop

or (in case RabbitMQ/message broker is managed by Supervisor):

$ sudo supervisorctl stop all

2. ...and then purge the tasks from a specific queue:

$ cd <source_dir>
$ celery amqp queue.purge <queue name>

3. Start RabbitMQ:

$ sudo rabbitmqctl start

or (in case RabbitMQ is managed by Supervisor):

$ sudo supervisorctl start all

Center a position:fixed element

#modal {
    display: flex;
    justify-content: space-around;
    align-items: center;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
}

inside it can be any element with diffenet width, height or without. all are centered.

Oracle - how to remove white spaces?

Say, we have a column with values consisting of alphanumeric characters and underscore only. We need to trim this column off all spaces, tabs or whatever white characters. The below example will solve the problem. The trimmed one and the original one both are being displayed for comparison. select '/'||REGEXP_REPLACE(my_column,'[^A-Z,^0-9,^_]','')||'/' my_column,'/'||my_column||'/' from my_table;

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

I see you are connecting to a remote host. Now the question is what type of a network are you using to connect to the internet?

WINDOWS

If it's a mobile broadband device then get your machines IP address and add it to your hosting server so that your host server can allow connections coming from your machine.[your host might have turned this off due to security reasons]. Note that every time you use a different network device your IP changes.

If you are using a LAN then set a static IP address on your machine then add it to your host.

I hope this helps!! :)

How to display Woocommerce product price by ID number on a custom page?

Other answers work, but

To get the full/default price:

$product->get_price_html();

Where do you include the jQuery library from? Google JSAPI? CDN?

In addition to people who advices to host it on own server, I'd proposed to keep it on separate domain (e.g. static.website.com) to allow browsers to load it into separate from other content thread. This tip also works for all static stuff, say images and css.

ImageView in circular through xml

If you use Material Design in your app then use this

<com.google.android.material.card.MaterialCardView
            android:layout_width="75dp"
            android:layout_height="75dp"
            app:cardCornerRadius="50dp"
            app:strokeWidth="1dp"
            app:strokeColor="@color/black">
            <ImageView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:id="@+id/circular_image"
                android:scaleType="fitCenter"
                android:src="@drawable/your_img" />
        </com.google.android.material.card.MaterialCardView>

Open multiple Projects/Folders in Visual Studio Code

What I suggest for now is to create symlinks in a folder, since VSCode isn't supporting that feature.

First, make a folder called whatever you'd like it to be.

$ mkdir random_project_folder
$ cd random_project_folder
$ ln -s /path/to/folder1/you/want/to/open folder1
$ ln -s /path/to/folder2/you/want/to/open folder2
$ ln -s /path/to/folder3/you/want/to/open folder3
$ code .

And you'll see your folders in the same VSCode window.

How to copy selected files from Android with adb pull

You can move your files to other folder and then pull whole folder.

adb shell mkdir /sdcard/tmp
adb shell mv /sdcard/mydir/*.jpg /sdcard/tmp # move your jpegs to temporary dir
adb pull /sdcard/tmp/ # pull this directory (be sure to put '/' in the end)
adb shell mv /sdcard/tmp/* /sdcard/mydir/ # move them back
adb shell rmdir /sdcard/tmp # remove temporary directory

Add newly created specific folder to .gitignore in Git

From "git help ignore" we learn:

If the pattern ends with a slash, it is removed for the purpose of the following description, but it would only find a match with a directory. In other words, foo/ will match a directory foo and paths underneath it, but will not match a regular file or a symbolic link foo (this is consistent with the way how pathspec works in general in git).

Therefore what you need is

public_html/stats/

Detect change to ngModel on a select tag (Angular 2)

I have stumbled across this question and I will submit my answer that I used and worked pretty well. I had a search box that filtered and array of objects and on my search box I used the (ngModelChange)="onChange($event)"

in my .html

<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">

then in my component.ts

reSearch(newValue: string) {
    //this.searchText would equal the new value
    //handle my filtering with the new value
}

How to declare a local variable in Razor?

If you want a variable to be accessible across the entire page, it works well to define it at the top of the file. (You can use either an implicit or explicit type.)

@{
    // implicit type
    var something1 = "something";

    // explicit type
    string something2 = "something";
}

<div>@something1</div> @*display first variable*@
<div>@something2</div> @*display second variable*@

Loop until a specific user input

As an alternative to @Mark Byers' approach, you can use while True:

guess = 50     # this should be outside the loop, I think
while True:    # infinite loop
    n = raw_input("\n\nTrue, False or Correct?: ")
    if n == "Correct":
        break  # stops the loop
    elif n == "True":
        # etc.

Import python package from local directory into interpreter

A simple way to make it work is to run your script from the parent directory using python's -m flag, e.g. python -m packagename.scriptname. Obviously in this situation you need an __init__.py file to turn your directory into a package.

Datetime equal or greater than today in MySQL

The below code worked for me.

declare @Today date

Set @Today=getdate() --date will equal today    

Select *

FROM table_name
WHERE created <= @Today

I got error "The DELETE statement conflicted with the REFERENCE constraint"

The error means that you have data in other tables that references the data you are trying to delete.

You would need to either drop and recreate the constraints or delete the data that the Foreign Key references.

Suppose you have the following tables

dbo.Students
(
StudentId
StudentName
StudentTypeId
)


dbo.StudentTypes
(
StudentTypeId
StudentType
)

Suppose a Foreign Key constraint exists between the StudentTypeId column in StudentTypes and the StudentTypeId column in Students

If you try to delete all the data in StudentTypes an error will occur as the StudentTypeId column in Students reference the data in the StudentTypes table.

EDIT:

DELETE and TRUNCATE essentially do the same thing. The only difference is that TRUNCATE does not save the changes in to the Log file. Also you can't use a WHERE clause with TRUNCATE

AS to why you can run this in SSMS but not via your Application. I really can't see this happening. The FK constraint would still throw an error regardless of where the transaction originated from.

How can I exclude $(this) from a jQuery selector?

You can use the not function rather than the :not selector:

$(".content a").not(this).hide("slow")

VC++ fatal error LNK1168: cannot open filename.exe for writing

The Reason is that your previous build is still running in the background. I solve this problem by following these steps:

  • Open Task Manager
  • Goto Details Tab
  • Find Your Application
  • End Task it by right clicking on it
  • Done!

How can I specify the required Node.js version in package.json?

I think you can use the "engines" field:

{ "engines" : { "node" : ">=0.12" } }

As you're saying your code definitely won't work with any lower versions, you probably want the "engineStrict" flag too:

{ "engineStrict" : true }

Documentation for the package.json file can be found on the npmjs site

Update

engineStrict is now deprecated, so this will only give a warning. It's now down to the user to run npm config set engine-strict true if they want this.

Update 2

As ben pointed out below, creating a .npmrc file at the root of your project (the same level as your package.json file) with the text engine-strict=true will force an error during installation if the Node version is not compatible.

Centos/Linux setting logrotate to maximum file size for all logs

As mentioned by Zeeshan, the logrotate options size, minsize, maxsize are triggers for rotation.

To better explain it. You can run logrotate as often as you like, but unless a threshold is reached such as the filesize being reached or the appropriate time passed, the logs will not be rotated.

The size options do not ensure that your rotated logs are also of the specified size. To get them to be close to the specified size you need to call the logrotate program sufficiently often. This is critical.

For log files that build up very quickly (e.g. in the hundreds of MB a day), unless you want them to be very large you will need to ensure logrotate is called often! this is critical.

Therefore to stop your disk filling up with multi-gigabyte log files you need to ensure logrotate is called often enough, otherwise the log rotation will not work as well as you want.

on Ubuntu, you can easily switch to hourly rotation by moving the script /etc/cron.daily/logrotate to /etc/cron.hourly/logrotate

Or add

*/5 * * * * /etc/cron.daily/logrotate 

To your /etc/crontab file. To run it every 5 minutes.

The size option ignores the daily, weekly, monthly time options. But minsize & maxsize take it into account.

The man page is a little confusing there. Here's my explanation.

minsize rotates only when the file has reached an appropriate size and the set time period has passed. e.g. minsize 50MB + daily If file reaches 50MB before daily time ticked over, it'll keep growing until the next day.

maxsize will rotate when the log reaches a set size or the appropriate time has passed. e.g. maxsize 50MB + daily. If file is 50MB and we're not at the next day yet, the log will be rotated. If the file is only 20MB and we roll over to the next day then the file will be rotated.

size will rotate when the log > size. Regardless of whether hourly/daily/weekly/monthly is specified. So if you have size 100M - it means when your log file is > 100M the log will be rotated if logrotate is run when this condition is true. Once it's rotated, the main log will be 0, and a subsequent run will do nothing.

So in the op's case. Specficially 50MB max I'd use something like the following:

/var/log/logpath/*.log {
    maxsize 50M
    hourly
    missingok
    rotate 8
    compress
    notifempty
    nocreate
}

Which means he'd create 8hrs of logs max. And there would be 8 of them at no more than 50MB each. Since he's saying that he's getting multi gigabytes each day and assuming they build up at a fairly constant rate, and maxsize is used he'll end up with around close to the max reached for each file. So they will be likely close to 50MB each. Given the volume they build, he would need to ensure that logrotate is run often enough to meet the target size.

Since I've put hourly there, we'd need logrotate to be run a minimum of every hour. But since they build up to say 2 gigabytes per day and we want 50MB... assuming a constant rate that's 83MB per hour. So you can imagine if we run logrotate every hour, despite setting maxsize to 50 we'll end up with 83MB log's in that case. So in this instance set the running to every 30 minutes or less should be sufficient.

Ensure logrotate is run every 30 mins.

*/30 * * * * /etc/cron.daily/logrotate 

password-check directive in angularjs

The following is my take on the problem. This directive would compare against a form value instead of the scope.

'use strict';
(function () {
    angular.module('....').directive('equals', function ($timeout) {
        return {
            restrict: 'A',
            require: ['^form', 'ngModel'],
            scope: false,
            link: function ($scope, elem, attrs, controllers) {
                var validationKey = 'equals';
                var form = controllers[0];
                var ngModel = controllers[1];

                if (!ngModel) {
                    return;
                }

                //run after view has rendered
                $timeout(function(){
                    $scope.$watch(attrs.ngModel, validate);

                    $scope.$watch(form[attrs.equals], validate);
                }, 0);

                var validate = function () {
                    var value1 = ngModel.$viewValue;
                    var value2 = form[attrs.equals].$viewValue;
                    var validity = !value1 || !value2 || value1 === value2;
                    ngModel.$setValidity(validationKey, validity);
                    form[attrs.equals].$setValidity(validationKey,validity);
                };
            }
        };
    });
})();

in the HTML one now refers to the actual form instead of the scoped value:

<form name="myForm">
  <input type="text" name="value1" equals="value2">
  <input type="text" name="value2" equals="value1">
  <div ng-show="myForm.$invalid">The form is invalid!</div>
</form>

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

if you're using the compiled bootstrap, one of the ways of fixing it is by editing the bootstrap.min.js before the line

$next[0].offsetWidth 

force reflow Change to

if (typeof $next == 'object' && $next.length) $next[0].offsetWidth // force reflow

ASP.NET Web Api: The requested resource does not support http method 'GET'

If you are decorating your method with HttpGet, add the following using at the top of the controller:

using System.Web.Http;

If you are using System.Web.Mvc, then this problem can occur.

C: printf a float value

You can do it like this:

printf("%.6f", myFloat);

6 represents the number of digits after the decimal separator.

How can I view the shared preferences file using Android Studio?

You could simply create a special Activity for debugging purpose:

@SuppressWarnings("unchecked")
public void loadPreferences() {
// create a textview with id (tv_pref) in Layout.
TextView prefTextView;
prefTextView = (TextView) findViewById(R.id.tv_pref);
    Map<String, ?> prefs = PreferenceManager.getDefaultSharedPreferences(
            context).getAll();
    for (String key : prefs.keySet()) {
        Object pref = prefs.get(key);
        String printVal = "";
        if (pref instanceof Boolean) {
            printVal =  key + " : " + (Boolean) pref;
        }
        if (pref instanceof Float) {
            printVal =  key + " : " + (Float) pref;
        }
        if (pref instanceof Integer) {
            printVal =  key + " : " + (Integer) pref;
        }
        if (pref instanceof Long) {
            printVal =  key + " : " + (Long) pref;
        }
        if (pref instanceof String) {
            printVal =  key + " : " + (String) pref;
        }
        if (pref instanceof Set<?>) {
            printVal =  key + " : " + (Set<String>) pref;
        }
        // Every new preference goes to a new line
        prefTextView.append(printVal + "\n\n");     
    }
}
// call loadPreferences() in the onCreate of your Activity.

Confused about stdin, stdout and stderr?

As a complement of the answers above, here is a sum up about Redirections: Redirections cheatsheet

EDIT: This graphic is not entirely correct.

The first example does not use stdin at all, it's passing "hello" as an argument to the echo command.

The graphic also says 2>&1 has the same effect as &> however

ls Documents ABC > dirlist 2>&1
#does not give the same output as 
ls Documents ABC > dirlist &>

This is because &> requires a file to redirect to, and 2>&1 is simply sending stderr into stdout

CSS ''background-color" attribute not working on checkbox inside <div>

My solution

Initially posted here.

_x000D_
_x000D_
input[type="checkbox"] {_x000D_
  cursor: pointer;_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
  appearance: none;_x000D_
  outline: 0;_x000D_
  background: lightgray;_x000D_
  height: 16px;_x000D_
  width: 16px;_x000D_
  border: 1px solid white;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:checked {_x000D_
  background: #2aa1c0;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:hover {_x000D_
  filter: brightness(90%);_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:disabled {_x000D_
  background: #e6e6e6;_x000D_
  opacity: 0.6;_x000D_
  pointer-events: none;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:after {_x000D_
  content: '';_x000D_
  position: relative;_x000D_
  left: 40%;_x000D_
  top: 20%;_x000D_
  width: 15%;_x000D_
  height: 40%;_x000D_
  border: solid #fff;_x000D_
  border-width: 0 2px 2px 0;_x000D_
  transform: rotate(45deg);_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:checked:after {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:disabled:after {_x000D_
  border-color: #7b7b7b;_x000D_
}
_x000D_
<input type="checkbox"><br>_x000D_
<input type="checkbox" checked><br>_x000D_
<input type="checkbox" disabled><br>_x000D_
<input type="checkbox" disabled checked><br>
_x000D_
_x000D_
_x000D_

Can you animate a height change on a UITableViewCell when selected?

Swift version of Simon Lee's answer:

tableView.beginUpdates()
tableView.endUpdates()

Keep in mind that you should modify the height properties BEFORE endUpdates().

SQL Server equivalent to Oracle's CREATE OR REPLACE VIEW

You can use 'IF EXISTS' to check if the view exists and drop if it does.

IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS
        WHERE TABLE_NAME = 'MyView')
    DROP VIEW MyView
GO

CREATE VIEW MyView
AS 
     ....
GO

Unrecognized SSL message, plaintext connection? Exception

if connection is FTPS test:

FTPSClient ftpClient = new FTPSClient(protocol, false);

protocol = TLS,SSL and false = isImplicit.

Find records from one table which don't exist in another

There's several different ways of doing this, with varying efficiency, depending on how good your query optimiser is, and the relative size of your two tables:

This is the shortest statement, and may be quickest if your phone book is very short:

SELECT  *
FROM    Call
WHERE   phone_number NOT IN (SELECT phone_number FROM Phone_book)

alternatively (thanks to Alterlife)

SELECT *
FROM   Call
WHERE  NOT EXISTS
  (SELECT *
   FROM   Phone_book
   WHERE  Phone_book.phone_number = Call.phone_number)

or (thanks to WOPR)

SELECT * 
FROM   Call
LEFT OUTER JOIN Phone_Book
  ON (Call.phone_number = Phone_book.phone_number)
  WHERE Phone_book.phone_number IS NULL

(ignoring that, as others have said, it's normally best to select just the columns you want, not '*')

Failed to resolve: com.android.support:appcompat-v7:26.0.0

Go to SDK path: SDK\extras\android\m2repository\com\android\support\appcompat-v7 to see correct dependency name, then change name if your dependency is alpha version:

dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  compile 'com.android.support:appcompat-v7:26.0.0'
}

to :

dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
}

Installation Issue with matplotlib Python

Problem Cause

In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.

Solution

  • I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.
  • Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

From this link you can try different diagrams.

Why am I getting a FileNotFoundError?

As noted above the problem is in specifying the path to your file. The default path in OS X is your home directory (/Users/macbook represented by ~ in terminal ...you can change or rename the home directory with the advanced options in System Preferences > Users & Groups).

Or you can specify the path from the drive to your file in the filename:

path = "/Users/macbook/Documents/MyPython/"
myFile = path + fileName

You can also catch the File Not Found Error and give another response using try:

try:
    with open(filename) as f:
        sequences = pick_lines(f)
except FileNotFoundError:
    print("File not found. Check the path variable and filename")
    exit()

How to check if Location Services are enabled?

Working off the answer above, in API 23 you need to add "dangerous" permissions checks as well as checking the system's itself:

public static boolean isLocationServicesAvailable(Context context) {
    int locationMode = 0;
    String locationProviders;
    boolean isAvailable = false;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
        try {
            locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }

        isAvailable = (locationMode != Settings.Secure.LOCATION_MODE_OFF);
    } else {
        locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        isAvailable = !TextUtils.isEmpty(locationProviders);
    }

    boolean coarsePermissionCheck = (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED);
    boolean finePermissionCheck = (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED);

    return isAvailable && (coarsePermissionCheck || finePermissionCheck);
}

What is NODE_ENV and how to use it in Express?

NODE_ENV is an environmental variable that stands for node environment in express server.

It's how we set and detect which environment we are in.

It's very common using production and development.

Set:

export NODE_ENV=production

Get:

You can get it using app.get('env')

Spring cron expression for every day 1:01:am

For my scheduler, I am using it to fire at 6 am every day and my cron notation is:

0 0 6 * * *

If you want 1:01:am then set it to

0 1 1 * * *

Complete code for the scheduler

@Scheduled(cron="0 1 1 * * *")
public void doScheduledWork() {
    //complete scheduled work
}

** VERY IMPORTANT

To be sure about the firing time correctness of your scheduler, you have to set zone value like this (I am in Istanbul):

@Scheduled(cron="0 1 1 * * *", zone="Europe/Istanbul")
public void doScheduledWork() {
    //complete scheduled work
}

You can find the complete time zone values from here.

Note: My Spring framework version is: 4.0.7.RELEASE

Set min-width in HTML table's <td>

<table style="min-width:50px; max-width:150px;">
    <tr>
        <td style="min-width:50px">one</td>
        <td style="min-width:100px">two</td>
    </tr>
</table>

This works for me using an email script.

How to calculate cumulative normal distribution?

Taken from above:

from scipy.stats import norm
>>> norm.cdf(1.96)
0.9750021048517795
>>> norm.cdf(-1.96)
0.024997895148220435

For a two-tailed test:

Import numpy as np
z = 1.96
p_value = 2 * norm.cdf(-np.abs(z))
0.04999579029644087

How to execute an oracle stored procedure?

Both 'is' and 'as' are valid syntax. Output is disabled by default. Try a procedure that also enables output...

create or replace procedure temp_proc is
begin
  DBMS_OUTPUT.ENABLE(1000000);
  DBMS_OUTPUT.PUT_LINE('Test');
end;

...and call it in a PLSQL block...

begin
  temp_proc;
end;

...as SQL is non-procedural.

Can you run GUI applications in a Docker container?

You can also use subuser: https://github.com/timthelion/subuser

This allows you to package many gui apps in docker. Firefox and emacs have been tested so far. With firefox, webGL doesn't work though. Chromium doesn't work at all.

EDIT: Sound works!

EDIT2: In the time since I first posted this, subuser has progressed greatly. I now have a website up subuser.org, and a new security model for connecting to X11 via XPRA bridging.

Pythonic way to check if a list is sorted or not

more_itertools.is_sorted

I'm not sure when this was added, but this hasn't been mentioned yet:

import more_itertools

ls = [1, 4, 2]

print(more_itertools.is_sorted(ls))

ls2 = ["ab", "c", "def"]

print(more_itertools.is_sorted(ls2, key=len))

Converting HTML to Excel?

Change the content type to ms-excel in the html and browser shall open the html in the Excel as xls. If you want control over the transformation of HTML to excel use POI libraries to do so.

jQuery validate: How to add a rule for regular expression validation?

Have you tried this??

$("Textbox").rules("add", { regex: "^[a-zA-Z'.\\s]{1,40}$", messages: { regex: "The text is invalid..." } })

Note: make sure to escape all the "\" of ur regex by adding another "\" in front of them else the regex wont work as expected.

How to generate and manually insert a uniqueidentifier in sql server?

Kindly check Column ApplicationId datatype in Table aspnet_Users , ApplicationId column datatype should be uniqueidentifier .

*Your parameter order is passed wrongly , Parameter @id should be passed as first argument, but in your script it is placed in second argument..*

So error is raised..

Please refere sample script:

DECLARE @id uniqueidentifier
SET @id = NEWID()
Create Table #temp1(AppId uniqueidentifier)

insert into #temp1 values(@id)

Select * from #temp1

Drop Table #temp1

Regex: matching up to the first occurrence of a character

This was very helpful for me as I was trying to figure out how to match all the characters in an xml tag including attributes. I was running into the "matches everything to the end" problem with:

/<simpleChoice.*>/

but was able to resolve the issue with:

/<simpleChoice[^>]*>/

after reading this post. Thanks all.

Changing element style attribute dynamically using JavaScript

It's almost correct.

Since the - is a javascript operator, you can't really have that in property names. If you were setting, border or something single-worded like that instead, your code would work just fine.

However, the thing you need to remember for padding-top, and for any hyphenated attribute name, is that in javascript, you remove the hyphen, and make the next letter uppercase, so in your case that'd be paddingTop.

There are some other exceptions. JavaScript has some reserved words, so you can't set float like that, for instance. Instead, in some browsers you need to use cssFloat and in others styleFloat. It is for discrepancies like this that it is recommended that you use a framework such as jQuery, that handles browser incompatibilities for you...

How to send POST request?

You can't achieve POST requests using urllib (only for GET), instead try using requests module, e.g.:

Example 1.0:

import requests

base_url="www.server.com"
final_url="/{0}/friendly/{1}/url".format(base_url,any_value_here)

payload = {'number': 2, 'value': 1}
response = requests.post(final_url, data=payload)

print(response.text) #TEXT/HTML
print(response.status_code, response.reason) #HTTP

Example 1.2:

>>> import requests

>>> payload = {'key1': 'value1', 'key2': 'value2'}

>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print(r.text)
{
  ...
  "form": {
    "key2": "value2",
    "key1": "value1"
  },
  ...
}

Example 1.3:

>>> import json

>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}

>>> r = requests.post(url, data=json.dumps(payload))

MySQL my.ini location

Press the windows key > type services > press enter > Look up mysql in the list > right click > properties > Path to Executable will have the location of the defaults file right below it (my.ini)

Best/Most Comprehensive API for Stocks/Financial Data

Yahoo's api provides a CSV dump:

Example: http://finance.yahoo.com/d/quotes.csv?s=msft&f=price

I'm not sure if it is documented or not, but this code sample should showcase all of the features (namely the stat types [parameter f in the query string]. I'm sure you can find documentation (official or not) if you search for it.

http://www.goldb.org/ystockquote.html

Edit

I found some unofficial documentation:

http://ilmusaham.wordpress.com/tag/stock-yahoo-data/

What's the difference between KeyDown and KeyPress in .NET?

The KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events.

https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.keypress

How to know Laravel version and where is it defined?

Yet another way is to read the composer.json file, but it can end with wildcard character *

iOS - Ensure execution on main thread

When you're using iOS >= 4

dispatch_async(dispatch_get_main_queue(), ^{
  //Your main thread code goes in here
  NSLog(@"Im on the main thread");       
});

Set specific precision of a BigDecimal

 BigDecimal decPrec = (BigDecimal)yo.get("Avg");
 decPrec = decPrec.setScale(5, RoundingMode.CEILING);
 String value= String.valueOf(decPrec);

This way you can set specific precision of a BigDecimal.

The value of decPrec was 1.5726903423607562595809913132345426 which is rounded off to 1.57267.

How can I have same rule for two locations in NGINX config?

This is short, yet efficient and proven approach:

location ~ (patternOne|patternTwo){ #rules etc. }

So one can easily have multiple patterns with simple pipe syntax pointing to the same location block / rules.

How to add Apache HTTP API (legacy) as compile-time dependency to build.grade for Android M?

As the answers are a bit old, I will put my solution (what worked for me), it can be helpful for somebody else... I took my solution from the official documentation of Apache, no work-around.

1/ in gradle:

dependencies {
...
// This is the maintained version from apache.
compile group: 'cz.msebera.android', name: 'httpclient', version: '4.4.1.1'
}

2/ in the rest of the app replace the org.apache.http by cz.msebera.android.httpclient and all your imports (dependencies) will be fixed. you can just do ctrl+shift+R and replace it in the whole project.

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

I could resolve it by overriding Configuration in MyContext through adding connection string to the DbContextOptionsBuilder:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json")
               .Build();
            var connectionString = configuration.GetConnectionString("DbCoreConnectionString");
            optionsBuilder.UseSqlServer(connectionString);
        }
    }

How do I iterate through children elements of a div using jQuery?

It can be done this way as well:

$('input', '#div').each(function () {
    console.log($(this)); //log every element found to console output
});

How to draw a rectangle around a region of interest in python

You can use cv2.rectangle():

cv2.rectangle(img, pt1, pt2, color, thickness, lineType, shift)

Draws a simple, thick, or filled up-right rectangle.

The function rectangle draws a rectangle outline or a filled rectangle
whose two opposite corners are pt1 and pt2.

Parameters
    img   Image.
    pt1   Vertex of the rectangle.
    pt2    Vertex of the rectangle opposite to pt1 .
    color Rectangle color or brightness (grayscale image).
    thickness  Thickness of lines that make up the rectangle. Negative values,
    like CV_FILLED , mean that the function has to draw a filled rectangle.
    lineType  Type of the line. See the line description.
    shift   Number of fractional bits in the point coordinates.

I have a PIL Image object and I want to draw rectangle on this image, but PIL's ImageDraw.rectangle() method does not have the ability to specify line width. I need to convert Image object to opencv2's image format and draw rectangle and convert back to Image object. Here is how I do it:

# im is a PIL Image object
im_arr = np.asarray(im)
# convert rgb array to opencv's bgr format
im_arr_bgr = cv2.cvtColor(im_arr, cv2.COLOR_RGB2BGR)
# pts1 and pts2 are the upper left and bottom right coordinates of the rectangle
cv2.rectangle(im_arr_bgr, pts1, pts2,
              color=(0, 255, 0), thickness=3)
im_arr = cv2.cvtColor(im_arr_bgr, cv2.COLOR_BGR2RGB)
# convert back to Image object
im = Image.fromarray(im_arr)

Inserting a tab character into text using C#

Hazar is right with his \t. Here's the full list of escape characters for C#:

\' for a single quote.

\" for a double quote.

\\ for a backslash.

\0 for a null character.

\a for an alert character.

\b for a backspace.

\f for a form feed.

\n for a new line.

\r for a carriage return.

\t for a horizontal tab.

\v for a vertical tab.

\uxxxx for a unicode character hex value (e.g. \u0020).

\x is the same as \u, but you don't need leading zeroes (e.g. \x20).

\Uxxxxxxxx for a unicode character hex value (longer form needed for generating surrogates).

What to do on TransactionTooLargeException

I found the root cause of this (we got both "adding window failed" and file descriptor leak as mvds says).

There is a bug in BitmapFactory.decodeFileDescriptor() of Android 4.4. It only occurs when inPurgeable and inInputShareable of BitmapOptions are set to true. This causes many problem in many places interact with files.

Note that the method is also called from MediaStore.Images.Thumbnails.getThumbnail().

Universal Image Loader is affected by this issue. Picasso and Glide seems to be not affected. https://github.com/nostra13/Android-Universal-Image-Loader/issues/1020

Modulo operator in Python

In addition to the other answers, the fmod documentation has some interesting things to say on the subject:

math.fmod(x, y)

Return fmod(x, y), as defined by the platform C library. Note that the Python expression x % y may not return the same result. The intent of the C standard is that fmod(x, y) be exactly (mathematically; to infinite precision) equal to x - n*y for some integer n such that the result has the same sign as x and magnitude less than abs(y). Python’s x % y returns a result with the sign of y instead, and may not be exactly computable for float arguments. For example, fmod(-1e-100, 1e100) is -1e-100, but the result of Python’s -1e-100 % 1e100 is 1e100-1e-100, which cannot be represented exactly as a float, and rounds to the surprising 1e100. For this reason, function fmod() is generally preferred when working with floats, while Python’s x % y is preferred when working with integers.

DNS caching in linux

Firefox contains a dns cache. To disable the DNS cache:

  1. Open your browser
  2. Type in about:config in the address bar
  3. Right click on the list of Properties and select New > Integer in the Context menu
  4. Enter 'network.dnsCacheExpiration' as the preference name and 0 as the integer value

When disabled, Firefox will use the DNS cache provided by the OS.

How to install and run Typescript locally in npm?

It took me a while to figure out the solution to this problem - it's in the original question. You need to have a script that calls tsc in your package.json file so that you can run:

npm run tsc 

Include -- before you pass in options (or just include them in the script):

npm run tsc -- -v

Here's an example package.json:

{
  "name": "foo",
  "scripts": {
    "tsc": "tsc"
  },
  "dependencies": {
    "typescript": "^1.8.10"
  }
}

How to call Base Class's __init__ method from the child class?

As Mingyu pointed out, there is a problem in formatting. Other than that, I would strongly recommend not using the Derived class's name while calling super() since it makes your code inflexible (code maintenance and inheritance issues). In Python 3, Use super().__init__ instead. Here is the code after incorporating these changes :

class Car(object):
    condition = "new"

    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

class ElectricCar(Car):

    def __init__(self, battery_type, model, color, mpg):
        self.battery_type=battery_type
        super().__init__(model, color, mpg)

Thanks to Erwin Mayer for pointing out the issue in using __class__ with super()

Custom header to HttpClient request

Here is an answer based on that by Anubis (which is a better approach as it doesn't modify the headers for every request) but which is more equivalent to the code in the original question:

using Newtonsoft.Json;
...

var client = new HttpClient();
var httpRequestMessage = new HttpRequestMessage
    {
        Method = HttpMethod.Post,
        RequestUri = new Uri("https://api.clickatell.com/rest/message"),
        Headers = { 
            { HttpRequestHeader.Authorization.ToString(), "Bearer xxxxxxxxxxxxxxxxxxx" },
            { HttpRequestHeader.Accept.ToString(), "application/json" },
            { "X-Version", "1" }
        },
        Content = new StringContent(JsonConvert.SerializeObject(svm))
    };

var response = client.SendAsync(httpRequestMessage).Result;

How to customize Bootstrap 3 tab color

_x000D_
_x000D_
.panel.with-nav-tabs .panel-heading {_x000D_
  padding: 5px 5px 0 5px;_x000D_
}_x000D_
_x000D_
.panel.with-nav-tabs .nav-tabs {_x000D_
  border-bottom: none;_x000D_
}_x000D_
_x000D_
.panel.with-nav-tabs .nav-justified {_x000D_
  margin-bottom: -1px;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL DEFAULT ***/_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:focus {_x000D_
  color: #777;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:focus {_x000D_
  color: #777;_x000D_
  background-color: #ddd;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.active>a:focus {_x000D_
  color: #555;_x000D_
  background-color: #fff;_x000D_
  border-color: #ddd;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #f5f5f5;_x000D_
  border-color: #ddd;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #777;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #ddd;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #555;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL PRIMARY ***/_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:focus {_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #3071a9;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.active>a:focus {_x000D_
  color: #428bca;_x000D_
  background-color: #fff;_x000D_
  border-color: #428bca;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #428bca;_x000D_
  border-color: #3071a9;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #3071a9;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  background-color: #4a9fe9;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL SUCCESS ***/_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:focus {_x000D_
  color: #3c763d;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:focus {_x000D_
  color: #3c763d;_x000D_
  background-color: #d6e9c6;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.active>a:focus {_x000D_
  color: #3c763d;_x000D_
  background-color: #fff;_x000D_
  border-color: #d6e9c6;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #dff0d8;_x000D_
  border-color: #d6e9c6;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #3c763d;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #d6e9c6;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #3c763d;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL INFO ***/_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:focus {_x000D_
  color: #31708f;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:focus {_x000D_
  color: #31708f;_x000D_
  background-color: #bce8f1;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.active>a:focus {_x000D_
  color: #31708f;_x000D_
  background-color: #fff;_x000D_
  border-color: #bce8f1;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #d9edf7;_x000D_
  border-color: #bce8f1;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #31708f;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #bce8f1;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #31708f;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL WARNING ***/_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:focus {_x000D_
  color: #8a6d3b;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:focus {_x000D_
  color: #8a6d3b;_x000D_
  background-color: #faebcc;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.active>a:focus {_x000D_
  color: #8a6d3b;_x000D_
  background-color: #fff;_x000D_
  border-color: #faebcc;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #fcf8e3;_x000D_
  border-color: #faebcc;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #8a6d3b;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #faebcc;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #8a6d3b;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL DANGER ***/_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:focus {_x000D_
  color: #a94442;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:focus {_x000D_
  color: #a94442;_x000D_
  background-color: #ebccd1;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.active>a:focus {_x000D_
  color: #a94442;_x000D_
  background-color: #fff;_x000D_
  border-color: #ebccd1;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #f2dede;_x000D_
  /* bg color */_x000D_
  border-color: #ebccd1;_x000D_
  /* border color */_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #a94442;_x000D_
  /* normal text color */_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #ebccd1;_x000D_
  /* hover bg color */_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  /* active text color */_x000D_
  background-color: #a94442;_x000D_
  /* active bg color */_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">_x000D_
<script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
<!------ Include the above in your HEAD tag ---------->_x000D_
_x000D_
<div class="container">_x000D_
  <div class="page-header">_x000D_
    <h1>Panels with nav tabs.<span class="pull-right label label-default">:)</span></h1>_x000D_
  </div>_x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-default">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1default" data-toggle="tab">Default 1</a></li>_x000D_
            <li><a href="#tab2default" data-toggle="tab">Default 2</a></li>_x000D_
            <li><a href="#tab3default" data-toggle="tab">Default 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4default" data-toggle="tab">Default 4</a></li>_x000D_
                <li><a href="#tab5default" data-toggle="tab">Default 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1default">Default 1</div>_x000D_
            <div class="tab-pane fade" id="tab2default">Default 2</div>_x000D_
            <div class="tab-pane fade" id="tab3default">Default 3</div>_x000D_
            <div class="tab-pane fade" id="tab4default">Default 4</div>_x000D_
            <div class="tab-pane fade" id="tab5default">Default 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-primary">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1primary" data-toggle="tab">Primary 1</a></li>_x000D_
            <li><a href="#tab2primary" data-toggle="tab">Primary 2</a></li>_x000D_
            <li><a href="#tab3primary" data-toggle="tab">Primary 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4primary" data-toggle="tab">Primary 4</a></li>_x000D_
                <li><a href="#tab5primary" data-toggle="tab">Primary 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1primary">Primary 1</div>_x000D_
            <div class="tab-pane fade" id="tab2primary">Primary 2</div>_x000D_
            <div class="tab-pane fade" id="tab3primary">Primary 3</div>_x000D_
            <div class="tab-pane fade" id="tab4primary">Primary 4</div>_x000D_
            <div class="tab-pane fade" id="tab5primary">Primary 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-success">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1success" data-toggle="tab">Success 1</a></li>_x000D_
            <li><a href="#tab2success" data-toggle="tab">Success 2</a></li>_x000D_
            <li><a href="#tab3success" data-toggle="tab">Success 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4success" data-toggle="tab">Success 4</a></li>_x000D_
                <li><a href="#tab5success" data-toggle="tab">Success 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1success">Success 1</div>_x000D_
            <div class="tab-pane fade" id="tab2success">Success 2</div>_x000D_
            <div class="tab-pane fade" id="tab3success">Success 3</div>_x000D_
            <div class="tab-pane fade" id="tab4success">Success 4</div>_x000D_
            <div class="tab-pane fade" id="tab5success">Success 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-info">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1info" data-toggle="tab">Info 1</a></li>_x000D_
            <li><a href="#tab2info" data-toggle="tab">Info 2</a></li>_x000D_
            <li><a href="#tab3info" data-toggle="tab">Info 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4info" data-toggle="tab">Info 4</a></li>_x000D_
                <li><a href="#tab5info" data-toggle="tab">Info 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1info">Info 1</div>_x000D_
            <div class="tab-pane fade" id="tab2info">Info 2</div>_x000D_
            <div class="tab-pane fade" id="tab3info">Info 3</div>_x000D_
            <div class="tab-pane fade" id="tab4info">Info 4</div>_x000D_
            <div class="tab-pane fade" id="tab5info">Info 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-warning">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1warning" data-toggle="tab">Warning 1</a></li>_x000D_
            <li><a href="#tab2warning" data-toggle="tab">Warning 2</a></li>_x000D_
            <li><a href="#tab3warning" data-toggle="tab">Warning 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4warning" data-toggle="tab">Warning 4</a></li>_x000D_
                <li><a href="#tab5warning" data-toggle="tab">Warning 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1warning">Warning 1</div>_x000D_
            <div class="tab-pane fade" id="tab2warning">Warning 2</div>_x000D_
            <div class="tab-pane fade" id="tab3warning">Warning 3</div>_x000D_
            <div class="tab-pane fade" id="tab4warning">Warning 4</div>_x000D_
            <div class="tab-pane fade" id="tab5warning">Warning 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-danger">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1danger" data-toggle="tab">Danger 1</a></li>_x000D_
            <li><a href="#tab2danger" data-toggle="tab">Danger 2</a></li>_x000D_
            <li><a href="#tab3danger" data-toggle="tab">Danger 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4danger" data-toggle="tab">Danger 4</a></li>_x000D_
                <li><a href="#tab5danger" data-toggle="tab">Danger 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1danger">Danger 1</div>_x000D_
            <div class="tab-pane fade" id="tab2danger">Danger 2</div>_x000D_
            <div class="tab-pane fade" id="tab3danger">Danger 3</div>_x000D_
            <div class="tab-pane fade" id="tab4danger">Danger 4</div>_x000D_
            <div class="tab-pane fade" id="tab5danger">Danger 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<br/>
_x000D_
_x000D_
_x000D_

DateDiff to output hours and minutes

No need to jump through hoops. Subtracting Start from End essentially gives you the timespan (combining Vignesh Kumar's and Carl Nitzsche's answers) :

SELECT *,
    --as a time object
    TotalHours = CONVERT(time, EndDate - StartDate),
    --as a formatted string
    TotalHoursText = CONVERT(varchar(20), EndDate - StartDate, 114)
FROM (
    --some test values (across days, but OP only cares about the time, not date)
    SELECT
        StartDate = CONVERT(datetime,'20090213 02:44:37.923'),
        EndDate   = CONVERT(datetime,'20090715 13:24:45.837')
) t

Ouput

StartDate               EndDate                 TotalHours       TotalHoursText
----------------------- ----------------------- ---------------- --------------------
2009-02-13 02:44:37.923 2009-07-15 13:24:45.837 10:40:07.9130000 10:40:07:913

See the full cast and convert options here: https://msdn.microsoft.com/en-us/library/ms187928.aspx

php/mySQL on XAMPP: password for phpMyAdmin and mysql_connect different?

if you open localhost/phpmyadmin you will find a tab called "User accounts". There you can define all your users that can access the mysql database, set their rights and even limit from where they can connect.

Best way to define error codes/strings in Java?

As far as I am concerned, I prefer to externalize the error messages in a properties files. This will be really helpful in case of internationalization of your application (one properties file per language). It is also easier to modify an error message, and it won't need any re-compilation of the Java sources.

On my projects, generally I have an interface that contains errors codes (String or integer, it doesn't care much), which contains the key in the properties files for this error:

public interface ErrorCodes {
    String DATABASE_ERROR = "DATABASE_ERROR";
    String DUPLICATE_USER = "DUPLICATE_USER";
    ...
}

in the properties file:

DATABASE_ERROR=An error occurred in the database.
DUPLICATE_USER=The user already exists.
...

Another problem with your solution is the maintenability: you have only 2 errors, and already 12 lines of code. So imagine your Enumeration file when you will have hundreds of errors to manage!

Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project

try this :

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
defaultConfig {

        targetSdkVersion 26
    }

}


compile 'com.android.support:appcompat-v7:25.1.0'

It has worked for me

Simple DateTime sql query

This has worked for me in both SQL Server 2005 and 2008:

SELECT * from TABLE
WHERE FIELDNAME > {ts '2013-02-01 15:00:00.001'}
  AND FIELDNAME < {ts '2013-08-05 00:00:00.000'}

How to send SMS in Java

(Disclaimer: I work at Twilio)

Twilio offers a Java SDK for sending SMS via the Twilio REST API.

Rails - controller action name to string

I just did the same. I did it in helper controller, my code is:

def get_controller_name
  controller_name    
end


def get_action_name
  action_name   
end

These methods will return current contoller and action name. Hope it helps

ImportError: No module named six

pip install --ignore-installed six

Source: 1233 thumbs up on this comment

Disable eslint rules for folder

The previous answers were in the right track, but the complete answer for this is going to Disabling rules only for a group of files, there you'll find the documentation needed to disable/enable rules for certain folders (Because in some cases you don't want to ignore the whole thing, only disable certain rules). Example:

{
    "env": {},
    "extends": [],
    "parser": "",
    "plugins": [],
    "rules": {},
    "overrides": [
      {
        "files": ["test/*.spec.js"], // Or *.test.js
        "rules": {
          "require-jsdoc": "off"
        }
      }
    ],
    "settings": {}
}

must appear in the GROUP BY clause or be used in an aggregate function

SELECT t1.cname, t1.wmname, t2.max
FROM makerar t1 JOIN (
    SELECT cname, MAX(avg) max
    FROM makerar
    GROUP BY cname ) t2
ON t1.cname = t2.cname AND t1.avg = t2.max;

Using rank() window function:

SELECT cname, wmname, avg
FROM (
    SELECT cname, wmname, avg, rank() 
    OVER (PARTITION BY cname ORDER BY avg DESC)
    FROM makerar) t
WHERE rank = 1;

Note

Either one will preserve multiple max values per group. If you want only single record per group even if there is more than one record with avg equal to max you should check @ypercube's answer.

How can I print the contents of a hash in Perl?

Data::Dumper is your friend.

use Data::Dumper;
my %hash = ('abc' => 123, 'def' => [4,5,6]);
print Dumper(\%hash);

will output

$VAR1 = {
          'def' => [
                     4,
                     5,
                     6
                   ],
          'abc' => 123
        };

Does JavaScript have the interface type (such as Java's 'interface')?

When you want to use a transcompiler, then you could give TypeScript a try. It supports draft ECMA features (in the proposal, interfaces are called "protocols") similar to what languages like coffeescript or babel do.

In TypeScript your interface can look like:

interface IMyInterface {
    id: number; // TypeScript types are lowercase
    name: string;
    callback: (key: string; value: any; array: string[]) => void;
    type: "test" | "notATest"; // so called "union type"
}

What you can't do:

How to hide the soft keyboard from inside a fragment?

This code works for fragments:

getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

Oracle SQL, concatenate multiple columns + add text

Try this:

SELECT 'I like ' || type_column_name || ' cake with ' || 
icing_column_name || ' and a ' fruit_column_name || '.' 
AS Cake_Column FROM your_table_name;

It should concatenate all that data as a single column entry named "Cake_Column".

Why is the jquery script not working?

This worked for me:

<script>
     jQuery.noConflict();
     // Use jQuery via jQuery() instead of via $()
     jQuery(document).ready(function(){
       jQuery("div").hide();
     });  
</script>

Reason: "Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $".

Read full reason here: https://api.jquery.com/jquery.noconflict/

If this solves your issue, it's likely another library is also using $.

How to reenable event.preventDefault?

I had a similar problem recently. I had a form and PHP function that to be run once the form is submitted. However, I needed to run a javascript first.

        // This variable is used in order to determine if we already did our js fun
        var window.alreadyClicked = "NO"
        $("form:not('#press')").bind("submit", function(e){
            // Check if we already run js part
            if(window.alreadyClicked == "NO"){
                // Prevent page refresh
                e.preventDefault();
                // Change variable value so next time we submit the form the js wont run
                window.alreadyClicked = "YES"
                // Here is your actual js you need to run before doing the php part
                xxxxxxxxxx

                // Submit the form again but since we changed the value of our variable js wont be run and page can reload (and php can do whatever you told it to)
                $("form:not('#press')").submit()
            } 
        });

How to read until end of file (EOF) using BufferedReader in Java?

With text files, maybe the EOF is -1 when using BufferReader.read(), char by char. I made a test with BufferReader.readLine()!=null and it worked properly.

Adding a parameter to the URL with JavaScript

Ok here I compare Two functions, one made by myself (regExp) and another one made by (annakata).

Split array:

function insertParam(key, value)
{
    key = escape(key); value = escape(value);

    var kvp = document.location.search.substr(1).split('&');

    var i=kvp.length; var x; while(i--) 
    {
        x = kvp[i].split('=');

        if (x[0]==key)
        {
                x[1] = value;
                kvp[i] = x.join('=');
                break;
        }
    }

    if(i<0) {kvp[kvp.length] = [key,value].join('=');}

    //this will reload the page, it's likely better to store this until finished
    return "&"+kvp.join('&'); 
}

Regexp method:

function addParameter(param, value)
{
    var regexp = new RegExp("(\\?|\\&)" + param + "\\=([^\\&]*)(\\&|$)");
    if (regexp.test(document.location.search)) 
        return (document.location.search.toString().replace(regexp, function(a, b, c, d)
        {
                return (b + param + "=" + value + d);
        }));
    else 
        return document.location.search+ param + "=" + value;
}

Testing case:

time1=(new Date).getTime();
for (var i=0;i<10000;i++)
{
addParameter("test","test");
}
time2=(new Date).getTime();
for (var i=0;i<10000;i++)
{
insertParam("test","test");
}

time3=(new Date).getTime();

console.log((time2-time1)+" "+(time3-time2));

It seems that even with simplest solution (when regexp use only test and do not enter .replace function) it is still slower than spliting... Well. Regexp is kinda slow but... uhh...

Handling JSON Post Request in Go

I was driving myself crazy with this exact problem. My JSON Marshaller and Unmarshaller were not populating my Go struct. Then I found the solution at https://eager.io/blog/go-and-json:

"As with all structs in Go, it’s important to remember that only fields with a capital first letter are visible to external programs like the JSON Marshaller."

After that, my Marshaller and Unmarshaller worked perfectly!

Lookup City and State by Zip Google Geocode Api

I found a couple of ways to do this with web based APIs. I think the US Postal Service would be the most accurate, since Zip codes are their thing, but Ziptastic looks much easier.

Using the US Postal Service HTTP/XML API

According to this page on the US Postal Service website which documents their XML based web API, specifically Section 4.0 (page 22) of this PDF document, they have a URL where you can send an XML request containing a 5 digit Zip Code and they will respond with an XML document containing the corresponding City and State.

According to their documentation, here's what you would send:

http://SERVERNAME/ShippingAPITest.dll?API=CityStateLookup&XML=<CityStateLookupRequest%20USERID="xxxxxxx"><ZipCode ID= "0"><Zip5>90210</Zip5></ZipCode></CityStateLookupRequest>

And here's what you would receive back:

<?xml version="1.0"?> 
<CityStateLookupResponse> 
    <ZipCode ID="0"> 
        <Zip5>90210</Zip5> 
        <City>BEVERLY HILLS</City> 
        <State>CA</State> 
    </ZipCode> 
</CityStateLookupResponse>

USPS does require that you register with them before you can use the API, but, as far as I could tell, there is no charge for access. By the way, their API has some other features: you can do Address Standardization and Zip Code Lookup, as well as the whole suite of tracking, shipping, labels, etc.

Using the Ziptastic HTTP/JSON API (no longer supported)

Update: As of August 13, 2017, Ziptastic is now a paid API and can be found here

This is a pretty new service, but according to their documentation, it looks like all you need to do is send a GET request to http://ziptasticapi.com, like so:

GET http://ziptasticapi.com/48867

And they will return a JSON object along the lines of:

{"country": "US", "state": "MI", "city": "OWOSSO"}

Indeed, it works. You can test this from a command line by doing something like:

curl http://ziptasticapi.com/48867 

Create dataframe from a matrix

I've found the following "cheat" to work very neatly and error-free

> dimnames <- list(time=c(0, 0.5, 1), name=c("C_0", "C_1"))
> mat <- matrix(data, ncol=2, nrow=3, dimnames=dimnames)
> head(mat, 2) #this returns the number of rows indicated in a data frame format
> df <- data.frame(head(mat, 2)) #"data.frame" might not be necessary

Et voila!

How to do a LIKE query with linq?

You can use contains:

string[] example = { "sample1", "sample2" };
var result = (from c in example where c.Contains("2") select c);
// returns only sample2

What is Activity.finish() method doing exactly?

Various answers and notes are claiming that finish() can skip onPause() and onStop() and directly execute onDestroy(). To be fair, the Android documentation on this (http://developer.android.com/reference/android/app/Activity.html) notes "Activity is finishing or being destroyed by the system" which is pretty ambiguous but might suggest that finish() can jump to onDestroy().

The JavaDoc on finish() is similarly disappointing (http://developer.android.com/reference/android/app/Activity.html#finish()) and does not actually note what method(s) are called in response to finish().

So I wrote this mini-app below which logs each state upon entry. It includes a button which calls finish() -- so you can see the logs of which methods get fired. This experiment would suggested that finish() does indeed also call onPause() and onStop(). Here is the output I get:

2170-2170/? D/LIFECYCLE_DEMO? INSIDE: onCreate
2170-2170/? D/LIFECYCLE_DEMO? INSIDE: onStart
2170-2170/? D/LIFECYCLE_DEMO? INSIDE: onResume
2170-2170/? D/LIFECYCLE_DEMO? User just clicked button to initiate finish() 
2170-2170/? D/LIFECYCLE_DEMO? INSIDE: onPause
2170-2170/? D/LIFECYCLE_DEMO? INSIDE: onStop 
2170-2170/? D/LIFECYCLE_DEMO? INSIDE: onDestroy

package com.mvvg.apps.lifecycle;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class AndroidLifecycle extends Activity {

    private static final String TAG = "LIFECYCLE_DEMO";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "INSIDE: onCreate");
        setContentView(R.layout.activity_main);
        LinearLayout layout = (LinearLayout) findViewById(R.id.myId);
        Button button = new Button(this);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                Toast.makeText(AndroidLifecycle.this, "Initiating finish()",
                        Toast.LENGTH_SHORT).show();
                Log.d(TAG, "User just clicked button to initiate finish()");
                finish();
            }

        });

        layout.addView(button);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "INSIDE: onStart");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "INSIDE: onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "INSIDE: onDestroy");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "INSIDE: onPause");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "INSIDE: onResume");
    }

}

'AND' vs '&&' as operator

I guess it's a matter of taste, although (mistakenly) mixing them up might cause some undesired behaviors:

true && false || false; // returns false

true and false || false; // returns true

Hence, using && and || is safer for they have the highest precedence. In what regards to readability, I'd say these operators are universal enough.

UPDATE: About the comments saying that both operations return false ... well, in fact the code above does not return anything, I'm sorry for the ambiguity. To clarify: the behavior in the second case depends on how the result of the operation is used. Observe how the precedence of operators comes into play here:

var_dump(true and false || false); // bool(false)

$a = true and false || false; var_dump($a); // bool(true)

The reason why $a === true is because the assignment operator has precedence over any logical operator, as already very well explained in other answers.

Change the Value of h1 Element within a Form with JavaScript

You can also use this

document.querySelector('yourId').innerHTML = 'Content';

SQL Server loop - how do I loop through a set of records

By using cursor you can easily iterate through records individually and print records separately or as a single message including all the records.

DECLARE @CustomerID as INT;
declare @msg varchar(max)
DECLARE @BusinessCursor as CURSOR;

SET @BusinessCursor = CURSOR FOR
SELECT CustomerID FROM Customer WHERE CustomerID IN ('3908745','3911122','3911128','3911421')

OPEN @BusinessCursor;
    FETCH NEXT FROM @BusinessCursor INTO @CustomerID;
    WHILE @@FETCH_STATUS = 0
        BEGIN
            SET @msg = '{
              "CustomerID": "'+CONVERT(varchar(10), @CustomerID)+'",
              "Customer": {
                "LastName": "LastName-'+CONVERT(varchar(10), @CustomerID) +'",
                "FirstName": "FirstName-'+CONVERT(varchar(10), @CustomerID)+'",    
              }
            }|'
        print @msg
    FETCH NEXT FROM @BusinessCursor INTO @CustomerID;
END

set the iframe height automatically

Try this coding

<div>
    <iframe id='iframe2' src="Mypage.aspx" frameborder="0" style="overflow: hidden; height: 100%;
        width: 100%; position: absolute;"></iframe>
</div>

What is the best alternative IDE to Visual Studio

If you are looking to try Java, I believe NetBeans is a very, very good IDE. However, for .NET, sure there are alternative IDEs but I don't think it makes much sense to use them unless you are developing on an Open Source platform, in which case SharpDevelop is a good choice and is reasonably mature.

Best implementation for Key Value Pair Data Structure?

I think what you might be after (as a literal implementation of your question), is:

public class TokenTree
{
    public TokenTree()
    {
        tree = new Dictionary<string, IDictionary<string,string>>();
    }

    IDictionary<string, IDictionary<string, string>> tree; 
}

You did actually say a "list" of key-values in your question, so you might want to swap the inner IDictionary with a:

IList<KeyValuePair<string, string>>

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

I think you should indeed be using the Control overload of the RegisterStartupScript.

I've tried the following code in a server control:

[ToolboxData("<{0}:AlertControl runat=server></{0}:AlertControl>")]
public class AlertControl : Control{
    protected override void OnInit(EventArgs e){
        base.OnInit(e);
        string script = "alert(\"Hello!\");";
        ScriptManager.RegisterStartupScript(this, GetType(), 
                      "ServerControlScript", script, true);
    }
}

Then in my page I have:

protected override void OnInit(EventArgs e){
    base.OnInit(e);
    Placeholder1.Controls.Add(new AlertControl());
}

Where Placeholder1 is a placeholder in an update panel. The placeholder has a couple of other controls on in it, including buttons.

This behaved exactly as you would expect, I got an alert saying "Hello" every time I loaded the page or caused the update panel to update.

The other thing you could look at is to hook into some of the page lifecycle events that are fired during an update panel request:

Sys.WebForms.PageRequestManager.getInstance()
   .add_endRequest(EndRequestHandler);

The PageRequestManager endRequestHandler event fires every time an update panel completes its update - this would allow you to call a method to set up your control.

My only other questions are:

  • What is your script actually doing?
  • Presumably you can see the script in the HTML at the bottom of the page (just before the closing </form> tag)?
  • Have you tried putting a few "alert("Here");" calls in your startup script to see if it's being called correctly?
  • Have you tried Firefox and Firebug - is that reporting any script errors?

bash script read all the files in directory

You can go without the loop:

find /path/to/dir -type f -exec /your/first/command \{\} \; -exec /your/second/command \{\} \; 

HTH

How do I run a simple bit of code in a new thread?

// following declaration of delegate ,,,
public delegate long GetEnergyUsageDelegate(DateTime lastRunTime, 
                                            DateTime procDateTime);

// following inside of some client method
GetEnergyUsageDelegate nrgDel = GetEnergyUsage;
IAsyncResult aR = nrgDel.BeginInvoke(lastRunTime, procDT, null, null);
while (!aR.IsCompleted) Thread.Sleep(500);
int usageCnt = nrgDel.EndInvoke(aR);

Charles your code(above) is not correct. You do not need to spin wait for completion. EndInvoke will block until the WaitHandle is signaled.

If you want to block until completion you simply need to

nrgDel.EndInvoke(nrgDel.BeginInvoke(lastRuntime,procDT,null,null));

or alternatively

ar.AsyncWaitHandle.WaitOne();

But what is the point of issuing anyc calls if you block? You might as well just use a synchronous call. A better bet would be to not block and pass in a lambda for cleanup:

nrgDel.BeginInvoke(lastRuntime,procDT,(ar)=> {ar.EndInvoke(ar);},null);

One thing to keep in mind is that you must call EndInvoke. A lot of people forget this and end up leaking the WaitHandle as most async implementations release the waithandle in EndInvoke.

Can't import Numpy in Python

To install it on Debian/Ubuntu:

sudo apt-get install python-numpy

Where to put Gradle configuration (i.e. credentials) that should not be committed?

For those of you who are building on a MacOS, and don't like leaving your password in clear text on your machine, you can use the keychain tool to store the credentials and then inject it into the build. Credits go to Viktor Eriksson. https://pilloxa.gitlab.io/posts/safer-passwords-in-gradle/

JavaScript query string

If you are using lodash + ES6, here is a one line solution: _.object(window.location.search.replace(/(^\?)/, '').split('&').map(keyVal => keyVal.split('=')));

jQuery UI accordion that keeps multiple sections open?

Just call each section of the accordion as its own accordion. active: n will be 0 for the first one( so it will display) and 1, 2, 3, 4, etc for the rest. Since each one is it's own accordion, they will all have only 1 section, and the rest will be collapsed to start.

$('.accordian').each(function(n, el) {
  $(el).accordion({
    heightStyle: 'content',
    collapsible: true,
    active: n
  });
});

Wait until flag=true

Try avoid while loop as it could be blocking your code, use async and promises.

Just wrote this library:

https://www.npmjs.com/package/utilzed

There is a function waitForTrue

import utilzed from 'utilzed'

const checkCondition = async () => {
  // anything that you are polling for to be expecting to be true
  const response = await callSomeExternalApi();
  return response.success;
}

// this will waitForTrue checkCondition to be true
// checkCondition will be called every 100ms
const success = await utilzed.waitForTrue(100, checkCondition, 1000);

if (success) {
  // Meaning checkCondition function returns true before 1000 ms
  return;
}

// meaning after 1000ms the checkCondition returns false still
// handle unsuccessful "poll for true" 

How to set editor theme in IntelliJ Idea

It's simple please follow the below step.

  1. On IntelliJ press 'Ctrl Alt + S' [ press ctrl alt and S together], this will open 'Setting popup'
  2. In Search panel 'left top search 'Theme' keyword.
  3. In left panel itself you can see 'Appearance', click on this
  4. Right side panel you can see Theme: and drop down with following option

    • Dracula
    • IntelliJ
    • Windows

just select which ever you want and click on apply and Ok.

I hope this may work for you..enter image description here

I misunderstood question. Sorry. for editor - File->Settings->Editor->Colors &Fonts and choose your scheme.... :)

How should I tackle --secure-file-priv in MySQL?

This thread has been viewed 570k times at the time of this post. Honestly when did MySQL become our over protective unreasonable mom? What a time consuming attempt at security - which really only serves to shackle us!

After many searches and many attempts everything failed. My solution:

What worked for me was:

  1. Import the .csv file via PhpMyAdmin import on older box (if large do at cmd line)
  2. Generate a .sql file.
  3. Download .sql file.
  4. Import .sql file via MySQL Workbench.

In Eclipse, what can cause Package Explorer "red-x" error-icon when all Java sources compile without errors?

In my case what solved this problem was simply to Close Eclipse and opening it again...However I am still not sure why this happened or why it worked. I was having problems Cleaning my project (it said it could not Delete certain file) and this solved it :):

CSS body background image fixed to full screen even when zooming in/out

Use Directly like this

.bg-div{
     background: url(../img/beach.jpg) no-repeat fixed 100% 100%;
}

or call CSS separately like

.bg-div{
    background-image: url(../img/beach.jpg);
    -moz-background-size: cover;
    -webkit-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Laravel update model with unique validation rule for attribute

or what you could do in your Form Request is (for Laravel 5.3+)

public function rules()
    {
        return [

            'email' => 'required|email|unique:users,email,'.$this->user, //here user is users/{user} from resource's route url
               ];
    }

i've done it in Laravel 5.6 and it worked.

Shift elements in a numpy array

Benchmarks & introducing Numba

1. Summary

  • The accepted answer (scipy.ndimage.interpolation.shift) is the slowest solution listed in this page.
  • Numba (@numba.njit) gives some performance boost when array size smaller than ~25.000
  • "Any method" equally good when array size large (>250.000).
  • The fastest option really depends on
        (1)  Length of your arrays
        (2)  Amount of shift you need to do.
  • Below is the picture of the timings of all different methods listed on this page (2020-07-11), using constant shift = 10. As one can see, with small array sizes some methods are use more than +2000% time than the best method.

Relative timings, constant shift (10), all methods

2. Detailed benchmarks with the best options

  • Choose shift4_numba (defined below) if you want good all-arounder

Relative timings, best methods (Benchmarks)

3. Code

3.1 shift4_numba

  • Good all-arounder; max 20% wrt. to the best method with any array size
  • Best method with medium array sizes: ~ 500 < N < 20.000.
  • Caveat: Numba jit (just in time compiler) will give performance boost only if you are calling the decorated function more than once. The first call takes usually 3-4 times longer than the subsequent calls.
import numba

@numba.njit
def shift4_numba(arr, num, fill_value=np.nan):
    if num >= 0:
        return np.concatenate((np.full(num, fill_value), arr[:-num]))
    else:
        return np.concatenate((arr[-num:], np.full(-num, fill_value)))

3.2. shift5_numba

  • Best option with small (N <= 300.. 1500) array sizes. Treshold depends on needed amount of shift.
  • Good performance on any array size; max + 50% compared to the fastest solution.
  • Caveat: Numba jit (just in time compiler) will give performance boost only if you are calling the decorated function more than once. The first call takes usually 3-4 times longer than the subsequent calls.
import numba

@numba.njit
def shift5_numba(arr, num, fill_value=np.nan):
    result = np.empty_like(arr)
    if num > 0:
        result[:num] = fill_value
        result[num:] = arr[:-num]
    elif num < 0:
        result[num:] = fill_value
        result[:num] = arr[-num:]
    else:
        result[:] = arr
    return result

3.3. shift5

  • Best method with array sizes ~ 20.000 < N < 250.000
  • Same as shift5_numba, just remove the @numba.njit decorator.

4 Appendix

4.1 Details about used methods

  • shift_scipy: scipy.ndimage.interpolation.shift (scipy 1.4.1) - The option from accepted answer, which is clearly the slowest alternative.
  • shift1: np.roll and out[:num] xnp.nan by IronManMark20 & gzc
  • shift2: np.roll and np.put by IronManMark20
  • shift3: np.pad and slice by gzc
  • shift4: np.concatenate and np.full by chrisaycock
  • shift5: using two times result[slice] = x by chrisaycock
  • shift#_numba: @numba.njit decorated versions of the previous.

The shift2 and shift3 contained functions that were not supported by the current numba (0.50.1).

4.2 Other test results

4.2.1 Relative timings, all methods

4.2.2 Raw timings, all methods

4.2.3 Raw timings, few best methods

How do I disable directory browsing?

The best way to do this is disable it with webserver apache2. In my Ubuntu 14.X - open /etc/apache2/apache2.conf change from

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

to

<Directory /var/www/>
        Options FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

then restart apache by:

sudo service apache2 reload

This will disable directory listing from all folder that apache2 serves.

How to downgrade python from 3.7 to 3.6

I just now downgraded my Python 3.9 to 3.6 because I wanted to use the librosa package but it does not support Python 3.9 still now.

Steps -

  • Go to python official website
  • Download the Python version which you want
  • Install in your machine normally

Run python3 --version in the terminal and it will show this version of Python.

How to manage exceptions thrown in filters in Spring?

So, here's what I did based on an amalgamation of the above answers... We already had a GlobalExceptionHandler annotated with @ControllerAdvice and I also wanted to find a way to re-use that code to handle exceptions that come from filters.

The simplest solution I could find was to leave the exception handler alone, and implement an error controller as follows:

@Controller
public class ErrorControllerImpl implements ErrorController {
  @RequestMapping("/error")
  public void handleError(HttpServletRequest request) throws Throwable {
    if (request.getAttribute("javax.servlet.error.exception") != null) {
      throw (Throwable) request.getAttribute("javax.servlet.error.exception");
    }
  }
}

So, any errors caused by exceptions first pass through the ErrorController and are re-directed off to the exception handler by rethrowing them from within a @Controller context, whereas any other errors (not caused directly by an exception) pass through the ErrorController without modification.

Any reasons why this is actually a bad idea?

Xamarin.Forms ListView: Set the highlight color of a tapped item

The easiest way to accomplish this on android is by adding the following code to your custom style :

@android:color/transparent

SQLite with encryption/password protection

You can use SQLite's function creation routines (PHP manual):

$db_obj->sqliteCreateFunction('Encrypt', 'MyEncryptFunction', 2);
$db_obj->sqliteCreateFunction('Decrypt', 'MyDecryptFunction', 2);

When inserting data, you can use the encryption function directly and INSERT the encrypted data or you can use the custom function and pass unencrypted data:

$insert_obj = $db_obj->prepare('INSERT INTO table (Clear, Encrypted) ' .
 'VALUES (:clear, Encrypt(:data, "' . $passwordhash_str . '"))');

When retrieving data, you can also use SQL search functionality:

$select_obj = $db_obj->prepare('SELECT Clear, ' .
 'Decrypt(Encrypted, "' . $passwordhash_str . '") AS PlainText FROM table ' .
 'WHERE PlainText LIKE :searchterm');

How to get substring of NSString?

Use this also

NSString *ChkStr = [MyString substringWithRange:NSMakeRange(5, 26)];

Note - Your NSMakeRange(start, end) should be NSMakeRange(start, end- start);

Context.startForegroundService() did not then call Service.startForeground()

So many answer but none worked in my case.

I have started service like this.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    startForegroundService(intent);
} else {
    startService(intent);
}

And in my service in onStartCommand

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        Notification.Builder builder = new Notification.Builder(this, ANDROID_CHANNEL_ID)
                .setContentTitle(getString(R.string.app_name))
                .setContentText("SmartTracker Running")
                .setAutoCancel(true);
        Notification notification = builder.build();
        startForeground(NOTIFICATION_ID, notification);
    } else {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setContentTitle(getString(R.string.app_name))
                .setContentText("SmartTracker is Running...")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setAutoCancel(true);
        Notification notification = builder.build();
        startForeground(NOTIFICATION_ID, notification);
    }

And don't forgot to set NOTIFICATION_ID non zero

private static final String ANDROID_CHANNEL_ID = "com.xxxx.Location.Channel";
private static final int NOTIFICATION_ID = 555;

SO everything was perfect but still crashing on 8.1 so cause was as below.

     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            stopForeground(true);
        } else {
            stopForeground(true);
        }

I have called stop foreground with remove notificaton but once notification removed service become background and background service can not run in android O from background. started after push received.

So magical word is

   stopSelf();

So far so any reason your service is crashing follow all above steps and enjoy.