Programs & Examples On #Totalview

RogueWave's GUI-based source code defect analysis tool.

How to check whether a string contains a substring in JavaScript?

Another alternative is KMP (Knuth–Morris–Pratt).

The KMP algorithm searches for a length-m substring in a length-n string in worst-case O(n+m) time, compared to a worst-case of O(n·m) for the naive algorithm, so using KMP may be reasonable if you care about worst-case time complexity.

Here's a JavaScript implementation by Project Nayuki, taken from https://www.nayuki.io/res/knuth-morris-pratt-string-matching/kmp-string-matcher.js:

// Searches for the given pattern string in the given text string using the Knuth-Morris-Pratt string matching algorithm.
// If the pattern is found, this returns the index of the start of the earliest match in 'text'. Otherwise -1 is returned.

_x000D_
_x000D_
function kmpSearch(pattern, text) {_x000D_
  if (pattern.length == 0)_x000D_
    return 0; // Immediate match_x000D_
_x000D_
  // Compute longest suffix-prefix table_x000D_
  var lsp = [0]; // Base case_x000D_
  for (var i = 1; i < pattern.length; i++) {_x000D_
    var j = lsp[i - 1]; // Start by assuming we're extending the previous LSP_x000D_
    while (j > 0 && pattern.charAt(i) != pattern.charAt(j))_x000D_
      j = lsp[j - 1];_x000D_
    if (pattern.charAt(i) == pattern.charAt(j))_x000D_
      j++;_x000D_
    lsp.push(j);_x000D_
  }_x000D_
_x000D_
  // Walk through text string_x000D_
  var j = 0; // Number of chars matched in pattern_x000D_
  for (var i = 0; i < text.length; i++) {_x000D_
    while (j > 0 && text.charAt(i) != pattern.charAt(j))_x000D_
      j = lsp[j - 1]; // Fall back in the pattern_x000D_
    if (text.charAt(i) == pattern.charAt(j)) {_x000D_
      j++; // Next char matched, increment position_x000D_
      if (j == pattern.length)_x000D_
        return i - (j - 1);_x000D_
    }_x000D_
  }_x000D_
  return -1; // Not found_x000D_
}_x000D_
_x000D_
console.log(kmpSearch('ays', 'haystack') != -1) // true_x000D_
console.log(kmpSearch('asdf', 'haystack') != -1) // false
_x000D_
_x000D_
_x000D_

How to install a plugin in Jenkins manually

This is a way to copy plugins from one Jenkins box to another.

Copy over the plugins directory:

scp -r jenkins-box.url.com:/var/lib/jenkins/plugins .

Compress the plugins:

tar cvfJ plugins.tar.xz plugins

Copy them over to the other Jenkins box:

scp plugins.tar.xz different-jenkins-box.url.com
ssh different-jenkins-box.url.com "tar xvfJ plugins.tar.xz -C /var/lib/jenkins"

Restart Jenkins.

Change <select>'s option and trigger events with JavaScript

The whole creating and dispatching events works, but since you are using the onchange attribute, your life can be a little simpler:

http://jsfiddle.net/xwywvd1a/3/

var selEl = document.getElementById("sel");
selEl.options[1].selected = true;
selEl.onchange();

If you use the browser's event API (addEventListener, IE's AttachEvent, etc), then you will need to create and dispatch events as others have pointed out already.

typeof operator in C

It's not exactly an operator, rather a keyword. And no, it doesn't do any runtime-magic.

Correct Way to Load Assembly, Find Class and Call Run() Method

Use an AppDomain

It is safer and more flexible to load the assembly into its own AppDomain first.

So instead of the answer given previously:

var asm = Assembly.LoadFile(@"C:\myDll.dll");
var type = asm.GetType("TestRunner");
var runnable = Activator.CreateInstance(type) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();

I would suggest the following (adapted from this answer to a related question):

var domain = AppDomain.CreateDomain("NewDomainName");
var t = typeof(TypeIWantToLoad);
var runnable = domain.CreateInstanceFromAndUnwrap(@"C:\myDll.dll", t.Name) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();

Now you can unload the assembly and have different security settings.

If you want even more flexibility and power for dynamic loading and unloading of assemblies, you should look at the Managed Add-ins Framework (i.e. the System.AddIn namespace). For more information, see this article on Add-ins and Extensibility on MSDN.

Export a list into a CSV or TXT file in R

cat(capture.output(print(my.list), file="test.txt"))

from R: Export and import a list to .txt file https://stackoverflow.com/users/1855677/42 is the only thing that worked for me. This outputs the list of lists as it is in the text file

git stash changes apply to new branch?

Is the standard procedure not working?

  • make changes
  • git stash save
  • git branch xxx HEAD
  • git checkout xxx
  • git stash pop

Shorter:

  • make changes
  • git stash
  • git checkout -b xxx
  • git stash pop

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

Please

  1. locate the file [XAMPP Installation Directory]\php\php.ini (e.g. C:\xampp\php\php.ini)
  2. open php.ini in Notepad or any Text editor
  3. locate the line containing max_execution_time and
  4. increase the value from 30 to some larger number (e.g. set: max_execution_time = 90)
  5. then restart Apache web server from the XAMPP control panel

If there will still be the same error after that, try to increase the value for the max_execution_time further more.

Update Angular model after setting input value with jQuery

I've written this little plugin for jQuery which will make all calls to .val(value) update the angular element if present:

(function($, ng) {
  'use strict';

  var $val = $.fn.val; // save original jQuery function

  // override jQuery function
  $.fn.val = function (value) {
    // if getter, just return original
    if (!arguments.length) {
      return $val.call(this);
    }

    // get result of original function
    var result = $val.call(this, value);

    // trigger angular input (this[0] is the DOM object)
    ng.element(this[0]).triggerHandler('input');

    // return the original result
    return result; 
  }
})(window.jQuery, window.angular);

Just pop this script in after jQuery and angular.js and val(value) updates should now play nice.


Minified version:

!function(n,t){"use strict";var r=n.fn.val;n.fn.val=function(n){if(!arguments.length)return r.call(this);var e=r.call(this,n);return t.element(this[0]).triggerHandler("input"),e}}(window.jQuery,window.angular);

Example:

_x000D_
_x000D_
// the function_x000D_
(function($, ng) {_x000D_
  'use strict';_x000D_
  _x000D_
  var $val = $.fn.val;_x000D_
  _x000D_
  $.fn.val = function (value) {_x000D_
    if (!arguments.length) {_x000D_
      return $val.call(this);_x000D_
    }_x000D_
    _x000D_
    var result = $val.call(this, value);_x000D_
    _x000D_
    ng.element(this[0]).triggerHandler('input');_x000D_
    _x000D_
    return result;_x000D_
    _x000D_
  }_x000D_
})(window.jQuery, window.angular);_x000D_
_x000D_
(function(ng){ _x000D_
  ng.module('example', [])_x000D_
    .controller('ExampleController', function($scope) {_x000D_
      $scope.output = "output";_x000D_
      _x000D_
      $scope.change = function() {_x000D_
        $scope.output = "" + $scope.input;_x000D_
      }_x000D_
    });_x000D_
})(window.angular);_x000D_
_x000D_
(function($){  _x000D_
  $(function() {_x000D_
    var button = $('#button');_x000D_
  _x000D_
    if (button.length)_x000D_
      console.log('hello, button');_x000D_
    _x000D_
    button.click(function() {_x000D_
      var input = $('#input');_x000D_
      _x000D_
      var value = parseInt(input.val());_x000D_
      value = isNaN(value) ? 0 : value;_x000D_
      _x000D_
      input.val(value + 1);_x000D_
    });_x000D_
  });_x000D_
})(window.jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div ng-app="example" ng-controller="ExampleController">_x000D_
  <input type="number" id="input" ng-model="input" ng-change="change()" />_x000D_
  <span>{{output}}</span>_x000D_
  <button id="button">+</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to open a new HTML page using jQuery?

use window.open("file2.html"); to open on new window,

or use window.location.href = "file2.html" to open on same window.

Background color on input type=button :hover state sticks in IE

You need to make sure images come first and put in a comma after the background image call. then it actually does work:

    background:url(egg.png) no-repeat 70px 2px #82d4fe; /* Old browsers */
background:url(egg.png) no-repeat 70px 2px, -moz-linear-gradient(top, #82d4fe 0%, #1db2ff 78%) ; /* FF3.6+ */
background:url(egg.png) no-repeat 70px 2px, -webkit-gradient(linear, left top, left bottom, color-stop(0%,#82d4fe), color-stop(78%,#1db2ff)); /* Chrome,Safari4+ */
background:url(egg.png) no-repeat 70px 2px, -webkit-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* Chrome10+,Safari5.1+ */
background:url(egg.png) no-repeat 70px 2px, -o-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* Opera11.10+ */
background:url(egg.png) no-repeat 70px 2px, -ms-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#82d4fe', endColorstr='#1db2ff',GradientType=0 ); /* IE6-9 */
background:url(egg.png) no-repeat 70px 2px, linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* W3C */

Casting to string in JavaScript

According to this JSPerf test, they differ in speed. But unless you're going to use them in huge amounts, any of them should perform fine.

For completeness: As asawyer already mentioned, you can also use the .toString() method.

Put Excel-VBA code in module or sheet?

In my experience it's best to put as much code as you can into well-named modules, and only put as much code as you need to into the actual worksheet objects.

Example: Any code that uses worksheet events like Worksheet_SelectionChange or Worksheet_Calculate.

Can I add an image to an ASP.NET button?

.my_btn{ 
  font-family:Arial; 
  font-size:10pt; 
  font-weight:normal; 
  height:30px; 
  line-height:30px; 
  width:98px; 
  border:0px;
  background-image:url('../Images/menu_image.png'); 
  cursor:pointer;
}

<asp:Button ID="clickme" runat="server" Text="Click" CssClass="my_btn" />

Creating Accordion Table with Bootstrap

This seems to be already asked before:

This might help:

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

UPDATE:

Your fiddle wasn't loading jQuery, so anything worked.

<table class="table table-hover">
<thead>
  <tr>
    <th></th>
    <th></th>
    <th></th>
  </tr>
</thead>

<tbody>
    <tr data-toggle="collapse" data-target="#accordion" class="clickable">
        <td>Some Stuff</td>
        <td>Some more stuff</td>
        <td>And some more</td>
    </tr>
    <tr>
        <td colspan="3">
            <div id="accordion" class="collapse">Hidden by default</div>
        </td>
    </tr>
</tbody>
</table>

Try this one: http://jsfiddle.net/Nb7wy/2/

I also added colspan='2' to the details row. But it's essentially your fiddle with jQuery loaded (in frameworks in the left column)

Vagrant stuck connection timeout retrying

I've found out that on MacOS with VirtualBox adding this to Vagrantfile will let you go further:

config.vm.provider 'virtualbox' do |vb|
  vb.customize ['modifyvm', :id, '--cableconnected1', 'on']
end

Simple way to calculate median with MySQL

Most of the solutions above work only for one field of the table, you might need to get the median (50th percentile) for many fields on the query.

I use this:

SELECT CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(
 GROUP_CONCAT(field_name ORDER BY field_name SEPARATOR ','),
  ',', 50/100 * COUNT(*) + 1), ',', -1) AS DECIMAL) AS `Median`
FROM table_name;

You can replace the "50" in example above to any percentile, is very efficient.

Just make sure you have enough memory for the GROUP_CONCAT, you can change it with:

SET group_concat_max_len = 10485760; #10MB max length

More details: http://web.performancerasta.com/metrics-tips-calculating-95th-99th-or-any-percentile-with-single-mysql-query/

javax.net.ssl.SSLException: Received fatal alert: protocol_version

You can try by adding following line to catalina.bat after last entry of JAVA_OPTS

set JAVA_OPTS=%JAVA_OPTS% -Dhttps.protocols=TLSv1.2 -Djdk.tls.client.protocols=TLSv1.2

How to get thread id from a thread pool?

You can use Thread.getCurrentThread.getId(), but why would you want to do that when LogRecord objects managed by the logger already have the thread Id. I think you are missing a configuration somewhere that logs the thread Ids for your log messages.

Entityframework Join using join method and lambdas

If you have configured navigation property 1-n I would recommend you to use:

var query = db.Categories                                  // source
   .SelectMany(c=>c.CategoryMaps,                          // join
      (c, cm) => new { Category = c, CategoryMaps = cm })  // project result
   .Select(x => x.Category);                               // select result

Much more clearer to me and looks better with multiple nested joins.

IF EXISTS condition not working with PLSQL

IF EXISTS() is semantically incorrect. EXISTS condition can be used only inside a SQL statement. So you might rewrite your pl/sql block as follows:

declare
  l_exst number(1);
begin
  select case 
           when exists(select ce.s_regno 
                         from courseoffering co
                         join co_enrolment ce
                           on ce.co_id = co.co_id
                        where ce.s_regno=403 
                          and ce.coe_completionstatus = 'C' 
                          and ce.c_id = 803
                          and rownum = 1
                        )
           then 1
           else 0
         end  into l_exst
  from dual;

  if l_exst = 1 
  then
    DBMS_OUTPUT.put_line('YES YOU CAN');
  else
    DBMS_OUTPUT.put_line('YOU CANNOT'); 
  end if;
end;

Or you can simply use count function do determine the number of rows returned by the query, and rownum=1 predicate - you only need to know if a record exists:

declare
  l_exst number;
begin
   select count(*) 
     into l_exst
     from courseoffering co
          join co_enrolment ce
            on ce.co_id = co.co_id
    where ce.s_regno=403 
      and ce.coe_completionstatus = 'C' 
      and ce.c_id = 803
      and rownum = 1;

  if l_exst = 0
  then
    DBMS_OUTPUT.put_line('YOU CANNOT');
  else
    DBMS_OUTPUT.put_line('YES YOU CAN');
  end if;
end;

How to inject window into a service?

There is an opportunity for direct access to the object of window through the document

document.defaultView == window

Bulk Insert to Oracle using .NET

Oracle says (http://www.oracle.com/technology/products/database/utilities/htdocs/sql_loader_overview.html)

SQL*Loader is the primary method for quickly populating Oracle tables with data from external files

My experience is that their loader loads their tables faster than anything else.

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

\usepackage{tabularx}
% ...    
\begin{document}
% ...

\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF &  simulation & jsp\\
\hline
\end{tabularx}

Creating a URL in the controller .NET MVC

If you need the full url (for instance to send by email) consider using one of the following built-in methods:

With this you create the route to use to build the url:

Url.RouteUrl("OpinionByCompany", new RouteValueDictionary(new{cid=newop.CompanyID,oid=newop.ID}), HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority)

Here the url is built after the route engine determine the correct one:

Url.Action("Detail","Opinion",new RouteValueDictionary(new{cid=newop.CompanyID,oid=newop.ID}),HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority)

In both methods, the last 2 parameters specifies the protocol and hostname.

Regards.

selecting from multi-index pandas

Understanding how to access multi-indexed pandas DataFrame can help you with all kinds of task like that.

Copy paste this in your code to generate example:

# hierarchical indices and columns
index = pd.MultiIndex.from_product([[2013, 2014], [1, 2]],
                                   names=['year', 'visit'])
columns = pd.MultiIndex.from_product([['Bob', 'Guido', 'Sue'], ['HR', 'Temp']],
                                     names=['subject', 'type'])

# mock some data
data = np.round(np.random.randn(4, 6), 1)
data[:, ::2] *= 10
data += 37

# create the DataFrame
health_data = pd.DataFrame(data, index=index, columns=columns)
health_data

Will give you table like this:

enter image description here

Standard access by column

health_data['Bob']
type       HR   Temp
year visit      
2013    1   22.0    38.6
        2   52.0    38.3
2014    1   30.0    38.9
        2   31.0    37.3


health_data['Bob']['HR']
year  visit
2013  1        22.0
      2        52.0
2014  1        30.0
      2        31.0
Name: HR, dtype: float64

# filtering by column/subcolumn - your case:
health_data['Bob']['HR']==22
year  visit
2013  1         True
      2        False
2014  1        False
      2        False

health_data['Bob']['HR'][2013]    
visit
1    22.0
2    52.0
Name: HR, dtype: float64

health_data['Bob']['HR'][2013][1]
22.0

Access by row

health_data.loc[2013]
subject Bob Guido   Sue
type    HR  Temp    HR  Temp    HR  Temp
visit                       
1   22.0    38.6    40.0    38.9    53.0    37.5
2   52.0    38.3    42.0    34.6    30.0    37.7

health_data.loc[2013,1] 
subject  type
Bob      HR      22.0
         Temp    38.6
Guido    HR      40.0
         Temp    38.9
Sue      HR      53.0
         Temp    37.5
Name: (2013, 1), dtype: float64

health_data.loc[2013,1]['Bob']
type
HR      22.0
Temp    38.6
Name: (2013, 1), dtype: float64

health_data.loc[2013,1]['Bob']['HR']
22.0

Slicing multi-index

idx=pd.IndexSlice
health_data.loc[idx[:,1], idx[:,'HR']]
    subject Bob Guido   Sue
type    HR  HR  HR
year    visit           
2013    1   22.0    40.0    53.0
2014    1   30.0    52.0    45.0

What does the "+=" operator do in Java?

It is the bitwise xor operator in java which results 1 for different value (ie 1 ^ 0 = 1) and 0 for same value (ie 0 ^ 0 = 0).

What causes a TCP/IP reset (RST) flag to be sent?

RST is sent by the side doing the active close because it is the side which sends the last ACK. So if it receives FIN from the side doing the passive close in a wrong state, it sends a RST packet which indicates other side that an error has occured.

Adding to an ArrayList Java

Well, you have to iterate through your abstract type Foo and that depends on the methods available on that object. You don't have to loop through the ArrayList because this object grows automatically in Java. (Don't confuse it with an array in other programming languages)

Recommended reading. Lists in the Java Tutorial

Pull new updates from original GitHub repository into forked GitHub repository

You have to add the original repository (the one you forked) as a remote.

From the GitHub documentation on forking a repository:

Screenshot of the old GitHub interface with a rectangular lens around the "Fork" button

Once the clone is complete your repo will have a remote named “origin” that points to your fork on GitHub.
Don’t let the name confuse you, this does not point to the original repo you forked from. To help you keep track of that repo we will add another remote named “upstream”:

$ cd PROJECT_NAME
$ git remote add upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git
$ git fetch upstream

# then: (like "git pull" which is fetch + merge)
$ git merge upstream/master master

# or, better, replay your local work on top of the fetched branch
# like a "git pull --rebase"
$ git rebase upstream/master

There's also a command-line tool (hub) which can facilitate the operations above.

Here's a visual of how it works:

Flowchart on the result after the commands are executed

See also "Are Git forks actually Git clones?".

How to load a resource bundle from a file resource in Java?

I would prefer to use the resourceboundle class to load the properties - just to get it done in one line instead of 5 lines code through stream, Properties class and load().

FYI ....

    public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);

    try {

            /*** Type1 */
        Properties props = new Properties();

        String fileName = getServletContext().getRealPath("WEB-INF/classes/com/test/my.properties");
    //          stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
    //          stream = ClassLoader.getSystemResourceAsStream("WEB-INF/class/com/test/my.properties");  

        InputStream stream = getServletContext().getResourceAsStream("/WEB-INF/classes/com/test/my.properties");

  //        props.load(new FileInputStream(fileName));
        props.load(stream);

        stream.close();
        Iterator keyIterator = props.keySet().iterator();
        while(keyIterator.hasNext()) {
                String key = (String) keyIterator.next();
                String value = (String) props.getProperty(key);
                System.out.println("key:" + key + " value: " + value);
        }

  /*** Type2:  */
  // Just get it done in one line by rb instead of 5 lines to load the properties
  // WEB-INF/classes/com/test/my.properties file            
  //            ResourceBundle rb = ResourceBundle.getBundle("com.test.my", Locale.ENGLISH, getClass().getClassLoader());
        ResourceBundle rb = ResourceBundle.getBundle("com.ibm.multitool.customerlogs.ui.nl.redirect");
        Enumeration<String> keys = rb.getKeys();
        while(keys.hasMoreElements()) {
            String key = keys.nextElement();
            System.out.println(key + " - " + rb.getObject(key));
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new ServletException("Error loading config.", e);
    } catch (Exception e) {
        e.printStackTrace();
        throw new ServletException("Error loading config.", e);
    }       

}

Trigger a keypress/keydown/keyup event in JS/jQuery?

You can achieve this with: EventTarget.dispatchEvent(event) and by passing in a new KeyboardEvent as the event.

For example: element.dispatchEvent(new KeyboardEvent('keypress', {'key': 'a'}))

Working example:

_x000D_
_x000D_
// get the element in question_x000D_
const input = document.getElementsByTagName("input")[0];_x000D_
_x000D_
// focus on the input element_x000D_
input.focus();_x000D_
_x000D_
// add event listeners to the input element_x000D_
input.addEventListener('keypress', (event) => {_x000D_
  console.log("You have pressed key: ", event.key);_x000D_
});_x000D_
_x000D_
input.addEventListener('keydown', (event) => {_x000D_
  console.log(`key: ${event.key} has been pressed down`);_x000D_
});_x000D_
_x000D_
input.addEventListener('keyup', (event) => {_x000D_
  console.log(`key: ${event.key} has been released`);_x000D_
});_x000D_
_x000D_
// dispatch keyboard events_x000D_
input.dispatchEvent(new KeyboardEvent('keypress',  {'key':'h'}));_x000D_
input.dispatchEvent(new KeyboardEvent('keydown',  {'key':'e'}));_x000D_
input.dispatchEvent(new KeyboardEvent('keyup', {'key':'y'}));
_x000D_
<input type="text" placeholder="foo" />
_x000D_
_x000D_
_x000D_

MDN dispatchEvent

MDN KeyboardEvent

image size (drawable-hdpi/ldpi/mdpi/xhdpi)

As of Octoer 2020, the dimensions for Launcher, ActionBar/Tab and Notification icons are:

enter image description here

A very good online tool to generate launcher icons : https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html

I want to multiply two columns in a pandas DataFrame and add the result into a new column

Since this question came up again, I think a good clean approach is using assign.

The code is quite expressive and self-describing:

df = df.assign(Value = lambda x: x.Prices * x.Amount * x.Action.replace({'Buy' : 1, 'Sell' : -1}))

Is there a way to detect if a browser window is not currently active?

In HTML 5 you could also use:

  • onpageshow: Script to be run when the window becomes visible
  • onpagehide: Script to be run when the window is hidden

See:

What are the git concepts of HEAD, master, origin?

HEAD is not the latest revision, it's the current revision. Usually, it's the latest revision of the current branch, but it doesn't have to be.

master is a name commonly given to the main branch, but it could be called anything else (or there could be no main branch).

origin is a name commonly given to the main remote. remote is another repository that you can pull from and push to. Usually it's on some server, like github.

Can PHP cURL retrieve response headers AND body in a single request?

Just set options :

  • CURLOPT_HEADER, 0

  • CURLOPT_RETURNTRANSFER, 1

and use curl_getinfo with CURLINFO_HTTP_CODE (or no opt param and you will have an associative array with all the informations you want)

More at : http://php.net/manual/fr/function.curl-getinfo.php

angular 4: *ngIf with multiple conditions

Besides the redundant ) this expression will always be true because currentStatus will always match one of these two conditions:

currentStatus !== 'open' || currentStatus !== 'reopen'

perhaps you mean one of

!(currentStatus === 'open' || currentStatus === 'reopen')
(currentStatus !== 'open' && currentStatus !== 'reopen')

Class vs. static method in JavaScript

When you try to call Foo.talk, the JS tries to search a function talk through __proto__ and, of course, it can't be found.

Foo.__proto__ is Function.prototype.

How to put a UserControl into Visual Studio toolBox

In my case, I couldn't see any of the controls in the project. Only when right clicking on toolBox and selecting "Show All" I saw them, but yet they were disabled...

Changing Project type from Windows application to ClassLibrary made the fix.

How to get single value of List<object>

Define a class like this :

public class myclass {
       string id ;
       string title ;
       string content;
 }

 public class program {
        public void Main () {
               List<myclass> objlist = new List<myclass> () ;
               foreach (var value in objlist)  {
                       TextBox1.Text = value.id ;
                       TextBox2.Text= value.title;
                       TextBox3.Text= value.content ;
                }
         }
  }

I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.

python-How to set global variables in Flask?

With:

global index_add_counter

You are not defining, just declaring so it's like saying there is a global index_add_counter variable elsewhere, and not create a global called index_add_counter. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global keyword and initialize your variable:

index_add_counter = 0

Now you can import it with:

from app import index_add_counter

The construction:

global index_add_counter

is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:

index_add_counter = 0
def test():
  global index_add_counter # means: in this scope, use the global name
  print(index_add_counter)

How to initialise a string from NSData in Swift

Another answer based on extensions (boy do I miss this in Java):

extension NSData {
    func toUtf8() -> String? {
        return String(data: self, encoding: NSUTF8StringEncoding)
    }
}

Then you can use it:

let data : NSData = getDataFromEpicServer()
let string : String? = data.toUtf8() 

Note that the string is optional, the initial NSData may be unconvertible to Utf8.

@AspectJ pointcut for all methods of a class with specific annotation

You could use Spring's PerformanceMonitoringInterceptor and programmatically register the advice using a beanpostprocessor.

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Monitorable
{

}


public class PerformanceMonitorBeanPostProcessor extends ProxyConfig implements BeanPostProcessor, BeanClassLoaderAware, Ordered,
    InitializingBean
{

  private Class<? extends Annotation> annotationType = Monitorable.class;

  private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();

  private Advisor advisor;

  public void setBeanClassLoader(ClassLoader classLoader)
  {
    this.beanClassLoader = classLoader;
  }

  public int getOrder()
  {
    return LOWEST_PRECEDENCE;
  }

  public void afterPropertiesSet()
  {
    Pointcut pointcut = new AnnotationMatchingPointcut(this.annotationType, true);
    Advice advice = getInterceptor();
    this.advisor = new DefaultPointcutAdvisor(pointcut, advice);
  }

  private Advice getInterceptor()
  {
    return new PerformanceMonitoringInterceptor();
  }

  public Object postProcessBeforeInitialization(Object bean, String beanName)
  {
    return bean;
  }

  public Object postProcessAfterInitialization(Object bean, String beanName)
  {
    if(bean instanceof AopInfrastructureBean)
    {
      return bean;
    }
    Class<?> targetClass = AopUtils.getTargetClass(bean);
    if(AopUtils.canApply(this.advisor, targetClass))
    {
      if(bean instanceof Advised)
      {
        ((Advised)bean).addAdvisor(this.advisor);
        return bean;
      }
      else
      {
        ProxyFactory proxyFactory = new ProxyFactory(bean);
        proxyFactory.copyFrom(this);
        proxyFactory.addAdvisor(this.advisor);
        return proxyFactory.getProxy(this.beanClassLoader);
      }
    }
    else
    {
      return bean;
    }
  }
}

Refresh a page using JavaScript or HTML

window.location.reload()

should work however there are many different options like:

window.location.href=window.location.href

Vertically aligning CSS :before and :after content

Using flexboxes did the trick for me:

.pdf:before {
    display: flex;
    align-items: center;
    justify-content: center;
}

set font size in jquery

Try:

$("#"+styleTarget).css({ 'font-size': $(this).val() });

By putting the value in quotes, it becomes a string, and "+$(this).val()+"px is definitely not close to a font value. There are a couple of ways of setting the style properties of an element:

Using a map:

$("#elem").css({
    fontSize: 20
});

Using key and value parameters:

All of these are valid.

$("#elem").css("fontSize", 20);
$("#elem").css("fontSize", "20px");
$("#elem").css("font-size", "20");
$("#elem").css("font-size", "20px");

You can replace "fontSize" with "font-size" but it will have to be quoted then.

How to do if-else in Thymeleaf?

In simpler case (when html tags is the same):

<h2 th:text="${potentially_complex_expression} ? 'Hello' : 'Something else'">/h2>

Maximum and minimum values in a textbox

If you are OK with HTML5 it can be accomplished without any JavaScript code at all...

<input type="number" name="textWeight" id="txtWeight" max="5" min="0" />

Otherwise, something like...

var input = document.getElementById('txtWeight');

input.addEventListener('change', function(e) {
    var num = parseInt(this.value, 10),
        min = 0,
        max = 100;

    if (isNaN(num)) {
        this.value = "";
        return;
    }

    this.value = Math.max(num, min);
    this.value = Math.min(num, max);
});

This will only reset the values when the input looses focus, and clears out any input that can't be parsed as an integer...

OBLIGATORY WARNING

You should always perform adequate server-side validation on inputs, regardless of client-side validation.

Putting an if-elif-else statement on one line?

Just nest another if clause in the else statement. But that doesn't make it look any prettier.

>>> x=5
>>> x if x>0 else ("zero" if x==0 else "invalid value")
5
>>> x = 0
>>> x if x>0 else ("zero" if x==0 else "invalid value")
'zero'
>>> x = -1
>>> x if x>0 else ("zero" if x==0 else "invalid value")
'invalid value'

Convert LocalDateTime to LocalDateTime in UTC

tldr: there is simply no way to do that; if you are trying to do that, you get LocalDateTime wrong.

The reason is that LocalDateTime does not record Time Zone after instances are created. You cannot convert a date time without time zone to another date time based on a specific time zone.

As a matter of fact, LocalDateTime.now() should never be called in production code unless your purpose is getting random results. When you construct a LocalDateTime instance like that, this instance contains date time ONLY based on current server's time zone, which means this piece of code will generate different result if it is running a server with a different time zone config.

LocalDateTime can simplify date calculating. If you want a real universally usable data time, use ZonedDateTime or OffsetDateTime: https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html.

How do I specify C:\Program Files without a space in it for programs that can't handle spaces in file paths?

As an alternative to the other answers, you can try symbolic links.

Create the symbolic link first and install the application based on the link. (Depending on the case, this may be way easier to do, for instance when the application has n mentions of the target folder throughout its code)

A symbolic link will create something similar to a shortcut to a folder, but seen as an actual folder by other applications.

This is how you do it:

  • Run cmd as administrator
  • User this command: mklink /D "C:\LinkToProgramFiles" "C:\Program Files"

And then, you start using "C:\LinkToProgramFiles" in the applications that can't handle spaces. (This link can be seen in Windows Explorer as a folder with the symbol of a shortcut)


Be very careful not to create circular links if you start playing too much with this.

Should C# or C++ be chosen for learning Games Programming (consoles)?

Ok here is my two cents.

If you are planning to seriously get into the game industry I recommend you learn both languages. Starting off with C++ then moving into a managed language like C#. C++ has it's advantages over C#, but C# also has advantages over C++.

Personally I prefer C# over C++ any day. This is because many reasons:, just a few:

  1. C# makes programming fun again ;).
  2. It's managed code helps me complete complex tasks easily and not forget safety.
  3. C#s' is pure OOP, forcing rules in your code that helps keep your code more readable, 'maintainable' and execution is more stable. Productivity rate surpasses C++ by at least 10%, the best C++ programmer could be an even better C# programmer.
  4. This isn't really a reason, more like something 'I' like about C#: LINQ.

Now...there are many things that I miss about C++. I miss being able to (completely) manage my own memory. I can't tell you how many times I caught myself trying to 'delete' an instance/reference. Another thing I dislike about C# is the inability to use multiple-inheritance, but then again it has forced me to think more about how to structure my code.

There has been more discussions on this topic than there are stars in the known universe and they all close at a dead end. Neither language is better than the other and refusing either one for the other will just hurt you in the long run. Times change and so do the standards for computer programming.

Whatever language you choose to keep at the top of your list, always keep your options open and don't set your mind to any one single language. You say you already know C++, why not learn C#, it can't hurt and I 'promise' you, it will make you a better C++ programmer.

How to execute a .sql script from bash

If you want to run a script to a database:

mysql -u user -p data_base_name_here < db.sql

Why can't I initialize non-const static member or static array in class?

I think it's to prevent you from mixing declarations and definitions. (Think about the problems that could occur if you include the file in multiple places.)

What is the difference between Left, Right, Outer and Inner Joins?

LEFT JOIN and RIGHT JOIN are types of OUTER JOINs.

INNER JOIN is the default -- rows from both tables must match the join condition.

JQuery .on() method with multiple event handlers to one selector

I learned something really useful and fundamental from here.

chaining functions is very usefull in this case which works on most jQuery Functions including on function output too.

It works because output of most jQuery functions are the input objects sets so you can use them right away and make it shorter and smarter

function showPhotos() {
    $(this).find("span").slideToggle();
}

$(".photos")
    .on("mouseenter", "li", showPhotos)
    .on("mouseleave", "li", showPhotos);

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
    echo "<p>Logged in as ".$user."</p>";
}
else
{
    echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
  authorized:true,
  user: {
      username: 'Joe', 
      securityToken: 'secret'
  }
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

How To: Execute command line in C#, get STD OUT results

Since the most answers here dont implement the using statemant for IDisposable and some other stuff wich I think could be nessecary I will add this answer.

For C# 8.0

// Start a process with the filename or path with filename e.g. "cmd". Please note the 
//using statemant
using myProcess.StartInfo.FileName = "cmd";
// add the arguments - Note add "/c" if you want to carry out tge  argument in cmd and  
// terminate
myProcess.StartInfo.Arguments = "/c dir";
// Allows to raise events
myProcess.EnableRaisingEvents = true;
//hosted by the application itself to not open a black cmd window
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.CreateNoWindow = true;
// Eventhander for data
myProcess.Exited += OnOutputDataRecived;
// Eventhandler for error
myProcess.ErrorDataReceived += OnErrorDataReceived;
// Eventhandler wich fires when exited
myProcess.Exited += OnExited;
// Starts the process
myProcess.Start();
//read the output before you wait for exit
myProcess.BeginOutputReadLine();
// wait for the finish - this will block (leave this out if you dont want to wait for 
// it, so it runs without blocking)
process.WaitForExit();

// Handle the dataevent
private void OnOutputDataRecived(object sender, DataReceivedEventArgs e)
{
    //do something with your data
    Trace.WriteLine(e.Data);
}

//Handle the error
private void OnErrorDataReceived(object sender, DataReceivedEventArgs e)
{        
    Trace.WriteLine(e.Data);
    //do something with your exception
    throw new Exception();
}    

// Handle Exited event and display process information.
private void OnExited(object sender, System.EventArgs e)
{
     Trace.WriteLine("Process exited");
}

java.io.FileNotFoundException: class path resource cannot be opened because it does not exist

Try this:

ApplicationContext context = new ClassPathXmlApplicationContext("app-context.xml");

Error parsing yaml file: mapping values are not allowed here

Or, if spacing is not the problem, it might want the parent directory name rather than the file name.

Not $ dev_appserver helloapp.py
But $ dev_appserver hello/

For example:

Johns-Mac:hello john$ dev_appserver.py helloworld.py
Traceback (most recent call last):
  File "/usr/local/bin/dev_appserver.py", line 82, in <module>
    _run_file(__file__, globals())
...
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/api/yaml_listener.py", line 212, in _GenerateEventParameters
    raise yaml_errors.EventListenerYAMLError(e)
google.appengine.api.yaml_errors.EventListenerYAMLError: mapping values are not allowed here
  in "helloworld.py", line 3, column 39

Versus

Johns-Mac:hello john$ cd ..
Johns-Mac:fbm john$ dev_appserver.py hello/
INFO     2014-09-15 11:44:27,828 api_server.py:171] Starting API server at: http://localhost:61049
INFO     2014-09-15 11:44:27,831 dispatcher.py:183] Starting module "default" running at: http://localhost:8080

This application has no explicit mapping for /error

Change @Controller to @RestController in your controller class and everything should go smoothly.

Find if current time falls in a time range

Try using the TimeRange object in C# to complete your goal.

TimeRange timeRange = new TimeRange();
timeRange = TimeRange.Parse("13:00-14:00");

bool IsNowInTheRange = timeRange.IsIn(DateTime.Now.TimeOfDay);
Console.Write(IsNowInTheRange);

Here is where I got that example of using TimeRange

Nested rows with bootstrap grid system?

Adding to what @KyleMit said, consider using:

  • col-md-* classes for the larger outer columns
  • col-xs-* classes for the smaller inner columns

This will be useful when you view the page on different screen sizes.

On a small screen, the wrapping of larger outer columns will then happen while maintaining the smaller inner columns, if possible

Any way to break if statement in PHP?

You could use a do-while(false):

    <?php
    do if ($foo)
    {
      // Do something first...

      // Shall we continue with this block, or exit now?
      if ($abort_if_block) break;

      // Continue doing something...

    } while (false);
    ?>

as described in http://php.net/manual/en/control-structures.if.php#90073

MySQL update CASE WHEN/THEN/ELSE

If id is sequential starting at 1, the simplest (and quickest) would be:

UPDATE `table` 
SET uid = ELT(id, 2952, 4925, 1592) 
WHERE id IN (1,2,3)

As ELT() returns the Nth element of the list of strings: str1 if N = 1, str2 if N = 2, and so on. Returns NULL if N is less than 1 or greater than the number of arguments.

Clearly, the above code only works if id is 1, 2, or 3. If id was 10, 20, or 30, either of the following would work:

UPDATE `table` 
SET uid = CASE id 
WHEN 10 THEN 2952 
WHEN 20 THEN 4925 
WHEN 30 THEN 1592 END CASE 
WHERE id IN (10, 20, 30)

or the simpler:

UPDATE `table` 
SET uid = ELT(FIELD(id, 10, 20, 30), 2952, 4925, 1592) 
WHERE id IN (10, 20, 30)

As FIELD() returns the index (position) of str in the str1, str2, str3, ... list. Returns 0 if str is not found.

array.select() in javascript

yo can extend your JS with a select method like this

Array.prototype.select = function(closure){
    for(var n = 0; n < this.length; n++) {
        if(closure(this[n])){
            return this[n];
        }
    }

    return null;
};

now you can use this:

var x = [1,2,3,4];

var a = x.select(function(v) {
    return v == 2;
});

console.log(a);

or for objects in a array

var x = [{id: 1, a: true},
    {id: 2, a: true},
    {id: 3, a: true},
    {id: 4, a: true}];

var a = x.select(function(obj) {
    return obj.id = 2;
});

console.log(a);

Change background color of iframe issue

Put the Iframe between aside tags

<aside style="background-color:#FFF"> your IFRAME </aside>

How to convert column with string type to int form in pyspark data frame?

Another way to do it is using the StructField if you have multiple fields that needs to be modified.

Ex:

from pyspark.sql.types import StructField,IntegerType, StructType,StringType
newDF=[StructField('CLICK_FLG',IntegerType(),True),
       StructField('OPEN_FLG',IntegerType(),True),
       StructField('I1_GNDR_CODE',StringType(),True),
       StructField('TRW_INCOME_CD_V4',StringType(),True),
       StructField('ASIAN_CD',IntegerType(),True),
       StructField('I1_INDIV_HHLD_STATUS_CODE',IntegerType(),True)
       ]
finalStruct=StructType(fields=newDF)
df=spark.read.csv('ctor.csv',schema=finalStruct)

Output:

Before

root
 |-- CLICK_FLG: string (nullable = true)
 |-- OPEN_FLG: string (nullable = true)
 |-- I1_GNDR_CODE: string (nullable = true)
 |-- TRW_INCOME_CD_V4: string (nullable = true)
 |-- ASIAN_CD: integer (nullable = true)
 |-- I1_INDIV_HHLD_STATUS_CODE: string (nullable = true)

After:

root
 |-- CLICK_FLG: integer (nullable = true)
 |-- OPEN_FLG: integer (nullable = true)
 |-- I1_GNDR_CODE: string (nullable = true)
 |-- TRW_INCOME_CD_V4: string (nullable = true)
 |-- ASIAN_CD: integer (nullable = true)
 |-- I1_INDIV_HHLD_STATUS_CODE: integer (nullable = true)

This is slightly a long procedure to cast , but the advantage is that all the required fields can be done.

It is to be noted that if only the required fields are assigned the data type, then the resultant dataframe will contain only those fields which are changed.

How to output MySQL query results in CSV format?

If you are getting an error of secure-file-priv then, also after shifting your destination file location inside the C:\ProgramData\MySQL\MySQL Server 8.0\Uploads and also after then the query-

SELECT * FROM attendance INTO OUTFILE 'C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\FileName.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';

is not working, you have to just change \(backsplash) from the query to / (forwardsplash)

And that works !!

Example:

SELECT * FROM attendance INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/FileName.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';

Each time when you run the successful query, it will generate the new csv file each time! Cool Right?

Numpy: find index of the elements within range

You can use np.where to get indices and np.logical_and to set two conditions:

import numpy as np
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])

np.where(np.logical_and(a>=6, a<=10))
# returns (array([3, 4, 5]),)

What is the "continue" keyword and how does it work in Java?

Continue is a keyword in Java & it is used to skip the current iteration.

Suppose you want to print all odd numbers from 1 to 100

public class Main {

    public static void main(String args[]) {

    //Program to print all odd numbers from 1 to 100

        for(int i=1 ; i<=100 ; i++) {
            if(i % 2 == 0) {
                continue;
            }
            System.out.println(i);
        }

    }
}

continue statement in the above program simply skips the iteration when i is even and prints the value of i when it is odd.

Continue statement simply takes you out of the loop without executing the remaining statements inside the loop and triggers the next iteration.

Python 101: Can't open file: No such file or directory

Prior to running python, type cd in the commmand line, and it will tell you the directory you are currently in. When python runs, it can only access files in this directory. hello.py needs to be in this directory, so you can move hello.py from its existing location to this folder as you would move any other file in Windows or you can change directories and run python in the directory hello.py is.

Edit: Python cannot access the files in the subdirectory unless a path to it provided. You can access files in any directory by providing the path. python C:\Python27\Projects\hello.p

The 'json' native gem requires installed build tools

1) Download Ruby 1.9.3

2) cmd check command: ruby -v 'return result ruby 1.9.3 then success full install ruby

3) Download DevKit file from http://rubyinstaller.org/downloads (DevKit-tdm-32-4.5.2-20110712-1620-sfx.exe)

4) Extract DevKit to path C:\Ruby193\DevKit

5) cd C:\Ruby193\DevKit

6) ruby dk.rb init

7) ruby dk.rb review

8) ruby dk.rb install

9) cmd : gem install rails -v3.1.1 'few time installing full process'

10) cmd : rails -v 'return result rails 3.1.1 then its success fully install'

enjoy Ruby on Rails...

Adding a background image to a <div> element

Use like ..

<div style="background-image: url(../images/test-background.gif); height: 200px; width: 400px; border: 1px solid black;">Example of a DIV element with a background image:</div>
<div style="background-image: url(../images/test-background.gif); height: 200px; width: 400px; border: 1px solid black;"> </div>

What's alternative to angular.copy in Angular

I as well as you faced a problem of work angular.copy and angular.expect because they do not copy the object or create the object without adding some dependencies. My solution was this:

  copyFactory = (() ->
    resource = ->
      resource.__super__.constructor.apply this, arguments
      return
    this.extendTo resource
    resource
  ).call(factory)

Select count(*) from multiple tables

SELECT  (
        SELECT COUNT(*)
        FROM   tab1
        ) AS count1,
        (
        SELECT COUNT(*)
        FROM   tab2
        ) AS count2
FROM    dual

Bash script prints "Command Not Found" on empty lines

Problems with running scripts may also be connected to bad formatting of multi-line commands, for example if you have a whitespace character after line-breaking "\". E.g. this:

./run_me.sh \ 
--with-some parameter

(please note the extra space after "\") will cause problems, but when you remove that space, it will run perfectly fine.

Violation Long running JavaScript task took xx ms

These are just warnings as everyone mentioned. However, if you're keen on resolving these (which you should), then you need to identify what is causing the warning first. There's no one reason due to which you can get force reflow warning. Someone has created a list for some possible options. You can follow the discussion for more information.
Here's the gist of the possible reasons:

What forces layout / reflow

All of the below properties or methods, when requested/called in JavaScript, will trigger the browser to synchronously calculate the style and layout*. This is also called reflow or layout thrashing, and is common performance bottleneck.

Element

Box metrics
  • elem.offsetLeft, elem.offsetTop, elem.offsetWidth, elem.offsetHeight, elem.offsetParent
  • elem.clientLeft, elem.clientTop, elem.clientWidth, elem.clientHeight
  • elem.getClientRects(), elem.getBoundingClientRect()
Scroll stuff
  • elem.scrollBy(), elem.scrollTo()
  • elem.scrollIntoView(), elem.scrollIntoViewIfNeeded()
  • elem.scrollWidth, elem.scrollHeight
  • elem.scrollLeft, elem.scrollTop also, setting them
Focus
  • elem.focus() can trigger a double forced layout (source)
Also…
  • elem.computedRole, elem.computedName
  • elem.innerText (source)

getComputedStyle

window.getComputedStyle() will typically force style recalc (source)

window.getComputedStyle() will force layout, as well, if any of the following is true:

  1. The element is in a shadow tree
  2. There are media queries (viewport-related ones). Specifically, one of the following: (source) * min-width, min-height, max-width, max-height, width, height * aspect-ratio, min-aspect-ratio, max-aspect-ratio
    • device-pixel-ratio, resolution, orientation
  3. The property requested is one of the following: (source)
    • height, width * top, right, bottom, left * margin [-top, -right, -bottom, -left, or shorthand] only if the margin is fixed. * padding [-top, -right, -bottom, -left, or shorthand] only if the padding is fixed. * transform, transform-origin, perspective-origin * translate, rotate, scale * webkit-filter, backdrop-filter * motion-path, motion-offset, motion-rotation * x, y, rx, ry

window

  • window.scrollX, window.scrollY
  • window.innerHeight, window.innerWidth
  • window.getMatchedCSSRules() only forces style

Forms

  • inputElem.focus()
  • inputElem.select(), textareaElem.select() (source)

Mouse events

  • mouseEvt.layerX, mouseEvt.layerY, mouseEvt.offsetX, mouseEvt.offsetY (source)

document

  • doc.scrollingElement only forces style

Range

  • range.getClientRects(), range.getBoundingClientRect()

SVG

contenteditable

  • Lots & lots of stuff, …including copying an image to clipboard (source)

Check more here.

Also, here's Chromium source code from the original issue and a discussion about a performance API for the warnings.


Edit: There's also an article on how to minimize layout reflow on PageSpeed Insight by Google. It explains what browser reflow is:

Reflow is the name of the web browser process for re-calculating the positions and geometries of elements in the document, for the purpose of re-rendering part or all of the document. Because reflow is a user-blocking operation in the browser, it is useful for developers to understand how to improve reflow time and also to understand the effects of various document properties (DOM depth, CSS rule efficiency, different types of style changes) on reflow time. Sometimes reflowing a single element in the document may require reflowing its parent elements and also any elements which follow it.

In addition, it explains how to minimize it:

  1. Reduce unnecessary DOM depth. Changes at one level in the DOM tree can cause changes at every level of the tree - all the way up to the root, and all the way down into the children of the modified node. This leads to more time being spent performing reflow.
  2. Minimize CSS rules, and remove unused CSS rules.
  3. If you make complex rendering changes such as animations, do so out of the flow. Use position-absolute or position-fixed to accomplish this.
  4. Avoid unnecessary complex CSS selectors - descendant selectors in particular - which require more CPU power to do selector matching.

What is the Git equivalent for revision number?

Each commit has a unique hash. Other than that there are no revision numbers in git. You'll have to tag commits yourself if you want more user-friendliness.

Remove duplicate rows in MySQL

-- Here is what I used, and it works:
create table temp_table like my_table;
-- t_id is my unique column
insert into temp_table (id) select id from my_table GROUP by t_id;
delete from my_table where id not in (select id from temp_table);
drop table temp_table;

How can I extract a predetermined range of lines from a text file on Unix?

This might work for you (GNU sed):

sed -ne '16224,16482w newfile' -e '16482q' file

or taking advantage of bash:

sed -n $'16224,16482w newfile\n16482q' file

Difference between maven scope compile and provided for JAR packaging

  • compile

Make available into class path, don't add this dependency into final jar if it is normal jar; but add this jar into jar if final jar is a single jar (for example, executable jar)

  • provided

Dependency will be available at run time environment so don't add this dependency in any case; even not in single jar (i.e. executable jar etc)

Browser back button handling

Warn/confirm User if Back button is Pressed is as below.

window.onbeforeunload = function() { return "Your work will be lost."; };

You can get more information using below mentioned links.

Disable Back Button in Browser using JavaScript

I hope this will help to you.

Hive: how to show all partitions of a table?

You can see Hive MetaStore tables,Partitions information in table of "PARTITIONS". You could use "TBLS" join "Partition" to query special table partitions.

How to convert AAR to JAR

If you are using Gradle for your builds - there is a Gradle plugin which allows you to add aar dependency to your java|kotlin|scala|... modules.

https://github.com/stepango/aar2jar

plugins {
    id 'java'
    id 'com.stepango.aar2jar' version “0.6” // <- this one
}

dependencies {
    compileOnlyAar "com.android.support:support-annotations:28.0.0" // <- Use any AAR dependencies
}

How to show uncommitted changes in Git and some Git diffs in detail

How to show uncommitted changes in Git

The command you are looking for is git diff.

git diff - Show changes between commits, commit and working tree, etc


Here are some of the options it expose which you can use

git diff (no parameters)
Print out differences between your working directory and the index.

git diff --cached:
Print out differences between the index and HEAD (current commit).

git diff HEAD:
Print out differences between your working directory and the HEAD.

git diff --name-only
Show only names of changed files.

git diff --name-status
Show only names and status of changed files.

git diff --color-words
Word by word diff instead of line by line.

Here is a sample of the output for git diff --color-words:

enter image description here


enter image description here

Arrays in cookies PHP

Using serialize and unserialize on cookies is a security risk. Users (or attackers) can alter cookie data, then when you unserialize it, it could run PHP code on your server. Cookie data should not be trusted. Use JSON instead!

From PHP's site:

Do not pass untrusted user input to unserialize() regardless of the options value of allowed_classes. Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. Use a safe, standard data interchange format such as JSON (via json_decode() and json_encode()) if you need to pass serialized data to the user.

AngularJS : automatically detect change in model

In views with {{}} and/or ng-model, Angular is setting up $watch()es for you behind the scenes.

By default $watch compares by reference. If you set the third parameter to $watch to true, Angular will instead "shallow" watch the object for changes. For arrays this means comparing the array items, for object maps this means watching the properties. So this should do what you want:

$scope.$watch('myModel', function() { ... }, true);

Update: Angular v1.2 added a new method for this, `$watchCollection():

$scope.$watchCollection('myModel', function() { ... });

Note that the word "shallow" is used to describe the comparison rather than "deep" because references are not followed -- e.g., if the watched object contains a property value that is a reference to another object, that reference is not followed to compare the other object.

Could not resolve placeholder in string value

In your configuration you have 2 PropertySourcesPlaceholderConfigurer instances.

applicationContext.xml

<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="environment">
        <bean class="org.springframework.web.context.support.StandardServletEnvironment"/>
    </property>
</bean>

infraContext.xml

<context:property-placeholder location="classpath:context-core.properties"/>

By default a PlaceholderConfigurer is going to fail-fast, so if a placeholder cannot be resolved it will throw an exception. The instance from the applicationContext.xml file has no properties and as such will fail on all placeholders.

Solution: Remove the one from applicationContext.xml as it doesn't add anything it only breaks things.

Warning: mysqli_error() expects exactly 1 parameter, 0 given error

At first, the problem is because you did't put any parameter for mysqli_error. I can see that it has been solved based on the post here. Most probably, the next problem is cause by wrong file path for the included file.. .

Are you sure this code

$myConnection = mysqli_connect("$db_host","$db_username","$db_pass","$db_name") or die ("could not connect to mysql");

is in the 'scripts' folder and your main code file is on the same level as the script folder?

How to Sort a List<T> by a property in the object

Doing it without Linq as you said:

public class Order : IComparable
{
    public DateTime OrderDate { get; set; }
    public int OrderId { get; set; }

    public int CompareTo(object obj)
    {
        Order orderToCompare = obj as Order;
        if (orderToCompare.OrderDate < OrderDate || orderToCompare.OrderId < OrderId)
        {
            return 1;
        }
        if (orderToCompare.OrderDate > OrderDate || orderToCompare.OrderId > OrderId)
        {
            return -1;
        }

        // The orders are equivalent.
        return 0;
    }
}

Then just call .sort() on your list of Orders

git: fatal: Could not read from remote repository

For my case, I am using Corporate network (without internet connection) in office. In order to pull code from github, I set https proxy in gitbash and then use https instead of ssh to pull code,it works fine. However when comes to push code, the https proxy won't work. So either switch to Internet network (with internet connection) or set ssh proxy can solve the problem.

How to convert a list of numbers to jsonarray in Python

Use the json module to produce JSON output:

import json

with open(outputfilename, 'wb') as outfile:
    json.dump(row, outfile)

This writes the JSON result directly to the file (replacing any previous content if the file already existed).

If you need the JSON result string in Python itself, use json.dumps() (added s, for 'string'):

json_string = json.dumps(row)

The L is just Python syntax for a long integer value; the json library knows how to handle those values, no L will be written.

Demo string output:

>>> import json
>>> row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
>>> json.dumps(row)
'[1, [0.1, 0.2], [[1234, 1], [134, 2]]]'

How to check if a specified key exists in a given S3 bucket using Java

Using the AWS SDK use the getObjectMetadata method. The method will throw an AmazonServiceException if the key doesn't exist.

private AmazonS3 s3;
...
public boolean exists(String path, String name) {
    try {
        s3.getObjectMetadata(bucket, getS3Path(path) + name); 
    } catch(AmazonServiceException e) {
        return false;
    }
    return true;
}

How to set image on QPushButton?

I don't think you can set arbitrarily sized images on any of the existing button classes. If you want a simple image behaving like a button, you can write your own QAbstractButton-subclass, something like:

class ImageButton : public QAbstractButton {
Q_OBJECT
public:
...
    void setPixmap( const QPixmap& pm ) { m_pixmap = pm; update(); }
    QSize sizeHint() const { return m_pixmap.size(); }
protected:
    void paintEvent( QPaintEvent* e ) {
        QPainter p( this );
        p.drawPixmap( 0, 0, m_pixmap );
    }
};

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

I think your problem is that you assume that the bytes that represent the utf8 string will result in the same string when interpreted as something else (iso-8859-1). And that is simply just not the case. I recommend that you read this excellent article by Joel spolsky.

mailto using javascript

I've simply used this javascript code (using jquery but it's not strictly necessary) :

    $( "#button" ).on( "click", function(event) {
         $(this).attr('href', 'mailto:[email protected]?subject=hello');
    });

When users click on the link, we replace the href attribute of the clicked element.

Be careful don't prevent the default comportment (event.preventDefault), we must let do it because we have just replaced the href where to go

I think robots can't see it, the address is protected from spams.

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

This question and answer helped me solve a specific problem with signing up new users in Parse.

Because the signUp( attrs, options ) function uses local storage to persist the session, if a user is in private browsing mode it throws the "QuotaExceededError: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota." exception and the success/error functions are never called.

In my case, because the error function is never called it initially appeared to be an issue with firing the click event on the submit or the redirect defined on success of sign up.

Including a warning for users resolved the issue.

Parse Javascript SDK Reference https://parse.com/docs/js/api/classes/Parse.User.html#methods_signUp

Signs up a new user with a username (or email) and password. This will create a new Parse.User on the server, and also persist the session in localStorage so that you can access the user using {@link #current}.

What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?

The first, curly braces. Otherwise, you run into consistency issues with keys that have odd characters in them, like =.

# Works fine.
a = {
    'a': 'value',
    'b=c': 'value',
}

# Eeep! Breaks if trying to be consistent.
b = dict( 
    a='value',
    b=c='value',
)

Is there a way to word-wrap long words in a div?

Aaron Bennet's solution is working perfectly for me, but i had to remove this line from his code --> white-space: -pre-wrap; beacause it was giving an error, so the final working code is the following:

.wordwrap { 
   white-space: pre-wrap;      /* CSS3 */   
   white-space: -moz-pre-wrap; /* Firefox */   
   white-space: -o-pre-wrap;   /* Opera 7 */    
   word-wrap: break-word;      /* IE */
}

thank you very much

How can I return the difference between two lists?

You can convert them to Set collections, and perform a set difference operation on them.

Like this:

Set<Date> ad = new HashSet<Date>(a);
Set<Date> bd = new HashSet<Date>(b);
ad.removeAll(bd);

How can you remove all documents from a collection with Mongoose?

.remove() is deprecated. instead we can use deleteMany

DateTime.deleteMany({}, callback).

How to configure static content cache per folder and extension in IIS7?

You can do it on a per file basis. Use the path attribute to include the filename

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <location path="YourFileNameHere.xml">
        <system.webServer>
            <staticContent>
                <clientCache cacheControlMode="DisableCache" />
            </staticContent>
        </system.webServer>
    </location>
</configuration>

How to convert FormData (HTML5 object) to JSON

If you have multiple entries with the same name, for example if you use <SELECT multiple> or have multiple <INPUT type="checkbox"> with the same name, you need to take care of that and make an array of the value. Otherwise you only get the last selected value.

Here is the modern ES6-variant:

function formToJSON( elem ) {
  let output = {};
  new FormData( elem ).forEach(
    ( value, key ) => {
      // Check if property already exist
      if ( Object.prototype.hasOwnProperty.call( output, key ) ) {
        let current = output[ key ];
        if ( !Array.isArray( current ) ) {
          // If it's not an array, convert it to an array.
          current = output[ key ] = [ current ];
        }
        current.push( value ); // Add the new value to the array.
      } else {
        output[ key ] = value;
      }
    }
  );
  return JSON.stringify( output );
}

Slightly older code (but still not supported by IE11, since it doesn't support ForEach or entries on FormData)

function formToJSON( elem ) {
  var current, entries, item, key, output, value;
  output = {};
  entries = new FormData( elem ).entries();
  // Iterate over values, and assign to item.
  while ( item = entries.next().value )
    {
      // assign to variables to make the code more readable.
      key = item[0];
      value = item[1];
      // Check if key already exist
      if (Object.prototype.hasOwnProperty.call( output, key)) {
        current = output[ key ];
        if ( !Array.isArray( current ) ) {
          // If it's not an array, convert it to an array.
          current = output[ key ] = [ current ];
        }
        current.push( value ); // Add the new value to the array.
      } else {
        output[ key ] = value;
      }
    }
    return JSON.stringify( output );
  }

How to skip a iteration/loop in while-loop

Try to add continue; where you want to skip 1 iteration.

Unlike the break keyword, continue does not terminate a loop. Rather, it skips to the next iteration of the loop, and stops executing any further statements in this iteration. This allows us to bypass the rest of the statements in the current sequence, without stopping the next iteration through the loop.

http://www.javacoffeebreak.com/articles/loopyjava/index.html

What is syntax for selector in CSS for next element?

Not exactly. The h1.hc-reform > p means "any p exactly one level underneath h1.hc-reform".

What you want is h1.hc-reform + p. Of course, that might cause some issues in older versions of Internet Explorer; if you want to make the page compatible with older IEs, you'll be stuck with either adding a class manually to the paragraphs or using some JavaScript (in jQuery, for example, you could do something like $('h1.hc-reform').next('p').addClass('first-paragraph')).

More info: http://www.w3.org/TR/CSS2/selector.html or http://css-tricks.com/child-and-sibling-selectors/

Register 32 bit COM DLL to 64 bit Windows 7

If problem not resolved, when using SysWoW64 version of regsvr32, make sure all library dependencies have same archetecture. For example, when

regsvr32 lib_x86.dll fails to register library, and %SystemRoot%\SysWow64\regsvr32 lib_x86 also fails, try to load lib_x86 to Dependency Walker application to see whole list of dependencies. If any item have 64-bit archetecture, here is the reason, why regsvr32 fails to load 32-bit library.

Difference between res.send and res.json in Express.js

https://github.com/visionmedia/express/blob/ee228f7aea6448cf85cc052697f8d831dce785d5/lib/response.js#L174

res.json eventually calls res.send, but before that it:

  • respects the json spaces and json replacer app settings
  • ensures the response will have utf8 charset and application/json content-type

How to save the output of a console.log(object) to a file?

There is another open-source tool that allows you to save all console.log output in a file on your server - JS LogFlush (plug!).

JS LogFlush is an integrated JavaScript logging solution which include:

  • cross-browser UI-less replacement of console.log - on client side.
  • log storage system - on server side.

Demo

How can I delete a service in Windows?

Click Start | Run and type regedit in the Open: line. Click OK.

Navigate to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services

Scroll down the left pane, locate the service name, right click it and select Delete.

Reboot the system.

Disable sorting on last column when using jQuery DataTables

use this link http://datatables.net/ref#bSortable

$(document).ready( function() {
   $('#example').dataTable( {
      "aoColumnDefs": [{ "bSortable": false, "aTargets": [ 0 ] }]
    } );
} );

Is there an easy way to check the .NET Framework version?

public class DA {
  public static class VersionNetFramework {
    public static string Get45or451FromRegistry()
    {//https://msdn.microsoft.com/en-us/library/hh925568(v=vs.110).aspx
        using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\"))
        {
            int releaseKey = Convert.ToInt32(ndpKey.GetValue("Release"));
            if (true)
            {
                return (@"Version: " + CheckFor45DotVersion(releaseKey));
            }
        }
    }
    // Checking the version using >= will enable forward compatibility, 
    // however you should always compile your code on newer versions of
    // the framework to ensure your app works the same.
    private static string CheckFor45DotVersion(int releaseKey)
    {//https://msdn.microsoft.com/en-us/library/hh925568(v=vs.110).aspx
        if (releaseKey >= 394271)
            return "4.6.1 installed on all other Windows OS versions or later";
        if (releaseKey >= 394254)
            return "4.6.1 installed on Windows 10 or later";
        if (releaseKey >= 393297)
            return "4.6 installed on all other Windows OS versions or later";
        if (releaseKey >= 393295)
            return "4.6 installed with Windows 10 or later";
        if (releaseKey >= 379893)
            return "4.5.2 or later";
        if (releaseKey >= 378758)
            return "4.5.1 installed on Windows 8, Windows 7 SP1, or Windows Vista SP2 or later";
        if (releaseKey >= 378675)
            return "4.5.1 installed with Windows 8.1 or later";
        if (releaseKey >= 378389)
            return "4.5 or later";

        return "No 4.5 or later version detected";
    }
    public static string GetVersionFromRegistry()
    {//https://msdn.microsoft.com/en-us/library/hh925568(v=vs.110).aspx
        string res = @"";
        // Opens the registry key for the .NET Framework entry.
        using (RegistryKey ndpKey =
            RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "").
            OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\"))
        {
            // As an alternative, if you know the computers you will query are running .NET Framework 4.5 
            // or later, you can use:
            // using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, 
            // RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\"))
            foreach (string versionKeyName in ndpKey.GetSubKeyNames())
            {
                if (versionKeyName.StartsWith("v"))
                {

                    RegistryKey versionKey = ndpKey.OpenSubKey(versionKeyName);
                    string name = (string)versionKey.GetValue("Version", "");
                    string sp = versionKey.GetValue("SP", "").ToString();
                    string install = versionKey.GetValue("Install", "").ToString();
                    if (install == "") //no install info, must be later.
                        res += (versionKeyName + "  " + name) + Environment.NewLine;
                    else
                    {
                        if (sp != "" && install == "1")
                        {
                            res += (versionKeyName + "  " + name + "  SP" + sp) + Environment.NewLine;
                        }

                    }
                    if (name != "")
                    {
                        continue;
                    }
                    foreach (string subKeyName in versionKey.GetSubKeyNames())
                    {
                        RegistryKey subKey = versionKey.OpenSubKey(subKeyName);
                        name = (string)subKey.GetValue("Version", "");
                        if (name != "")
                            sp = subKey.GetValue("SP", "").ToString();
                        install = subKey.GetValue("Install", "").ToString();
                        if (install == "") //no install info, must be later.
                            res += (versionKeyName + "  " + name) + Environment.NewLine;
                        else
                        {
                            if (sp != "" && install == "1")
                            {
                                res += ("  " + subKeyName + "  " + name + "  SP" + sp) + Environment.NewLine;
                            }
                            else if (install == "1")
                            {
                                res += ("  " + subKeyName + "  " + name) + Environment.NewLine;
                            }
                        }
                    }
                }
            }
        }
        return res;
    }
    public static string GetUpdateHistory()
    {//https://msdn.microsoft.com/en-us/library/hh925567(v=vs.110).aspx
        string res=@"";
        using (RegistryKey baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\Updates"))
        {
            foreach (string baseKeyName in baseKey.GetSubKeyNames())
            {
                if (baseKeyName.Contains(".NET Framework") || baseKeyName.StartsWith("KB") || baseKeyName.Contains(".NETFramework"))
                {

                    using (RegistryKey updateKey = baseKey.OpenSubKey(baseKeyName))
                    {
                        string name = (string)updateKey.GetValue("PackageName", "");
                        res += baseKeyName + "  " + name + Environment.NewLine;
                        foreach (string kbKeyName in updateKey.GetSubKeyNames())
                        {
                            using (RegistryKey kbKey = updateKey.OpenSubKey(kbKeyName))
                            {
                                name = (string)kbKey.GetValue("PackageName", "");
                                res += ("  " + kbKeyName + "  " + name) + Environment.NewLine;

                                if (kbKey.SubKeyCount > 0)
                                {
                                    foreach (string sbKeyName in kbKey.GetSubKeyNames())
                                    {
                                        using (RegistryKey sbSubKey = kbKey.OpenSubKey(sbKeyName))
                                        {
                                            name = (string)sbSubKey.GetValue("PackageName", "");
                                            if (name == "")
                                                name = (string)sbSubKey.GetValue("Description", "");
                                            res += ("    " + sbKeyName + "  " + name) + Environment.NewLine;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return res;
    }
}

using class DA.VersionNetFramework

private void Form1_Shown(object sender, EventArgs e)
{
    //
    // Current OS Information
    //
    richTextBox1.Text = @"Current OS Information:";
    richTextBox1.AppendText(Environment.NewLine +
                            "Machine Name: " + Environment.MachineName);
    richTextBox1.AppendText(Environment.NewLine +
                            "Platform: " + Environment.OSVersion.Platform.ToString());
    richTextBox1.AppendText(Environment.NewLine +
                            Environment.OSVersion);
    //
    // .NET Framework Environment Information
    //
    richTextBox1.AppendText(Environment.NewLine + Environment.NewLine +
                                       ".NET Framework Environment Information:");
    richTextBox1.AppendText(Environment.NewLine +
                            "Environment.Version " + Environment.Version);
    richTextBox1.AppendText(Environment.NewLine + 
                            DA.VersionNetFramework.GetVersionDicription());
    //
    // .NET Framework Information From Registry
    //
    richTextBox1.AppendText(Environment.NewLine + Environment.NewLine +
                                       ".NET Framework Information From Registry:");
    richTextBox1.AppendText(Environment.NewLine +
                            DA.VersionNetFramework.GetVersionFromRegistry());
    //
    // .NET Framework 4.5 or later Information From Registry
    //
    richTextBox1.AppendText(Environment.NewLine + 
                                       ".NET Framework 4.5 or later Information From Registry:");
    richTextBox1.AppendText(Environment.NewLine +
                            DA.VersionNetFramework.Get45or451FromRegistry());
    //
    // Update History
    //
    richTextBox1.AppendText(Environment.NewLine + Environment.NewLine +
                            "Update History");
    richTextBox1.AppendText(Environment.NewLine + 
                            DA.VersionNetFramework.GetUpdateHistory());
    //
    // Setting Cursor to first character of textbox
    //
    if (!richTextBox1.Text.Equals(""))
    {
        richTextBox1.SelectionStart = 1;
    }
}

Result:

Current OS Information: Machine Name: D1 Platform: Win32NT Microsoft Windows NT 6.2.9200.0

.NET Framework Environment Information: Environment.Version 4.0.30319.42000 .NET 4.6 on Windows 8.1 64 - bit or later

.NET Framework Information From Registry: v2.0.50727 2.0.50727.4927 SP2 v3.0 3.0.30729.4926 SP2 v3.5 3.5.30729.4926 SP1

v4
Client 4.6.00079 Full 4.6.00079 v4.0
Client 4.0.0.0

.NET Framework 4.5 or later Information From Registry: Version: 4.6 installed with Windows 10 or later

Update History Microsoft .NET Framework 4 Client Profile
KB2468871
KB2468871v2
KB2478063
KB2533523
KB2544514
KB2600211
KB2600217
Microsoft .NET Framework 4 Extended
KB2468871
KB2468871v2
KB2478063
KB2533523
KB2544514
KB2600211
KB2600217
Microsoft .NET Framework 4 Multi-Targeting Pack
KB2504637 Update for (KB2504637)

Fine control over the font size in Seaborn plots for academic papers

You are right. This is a badly documented issue. But you can change the font size parameter (by opposition to font scale) directly after building the plot. Check the following example:

import seaborn as sns
tips = sns.load_dataset("tips")

b = sns.boxplot(x=tips["total_bill"])
b.axes.set_title("Title",fontsize=50)
b.set_xlabel("X Label",fontsize=30)
b.set_ylabel("Y Label",fontsize=20)
b.tick_params(labelsize=5)
sns.plt.show()

, which results in this:

Different font sizes for different labels

To make it consistent in between plots I think you just need to make sure the DPI is the same. By the way it' also a possibility to customize a bit the rc dictionaries since "font.size" parameter exists but I'm not too sure how to do that.

NOTE: And also I don't really understand why they changed the name of the font size variables for axis labels and ticks. Seems a bit un-intuitive.

cor shows only NA or 1 for correlations - Why?

NAs also appear if there are attributes with zero variance (with all elements equal); see for instance:

cor(cbind(a=runif(10),b=rep(1,10)))

which returns:

   a  b
a  1 NA
b NA  1
Warning message:
In cor(cbind(a = runif(10), b = rep(1, 10))) :
  the standard deviation is zero

Alter column in SQL Server

I think you want this syntax:

ALTER TABLE tb_TableName  
add constraint cnt_Record_Status Default '' for Record_Status

Based on some of your comments, I am going to guess that you might already have null values in your table which is causing the alter of the column to not null to fail. If that is the case, then you should run an UPDATE first. Your script will be:

update tb_TableName
set Record_Status  = ''
where Record_Status is null

ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL

ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status

See SQL Fiddle with demo

Bootstrap 3.0 Popovers and tooltips

You have a syntax error in your script and, as noted by xXPhenom22Xx, you must instantiate the tooltip.

<script type="text/javascript">

    $(document).ready(function() {

        $('.btn-danger').tooltip();

    }); //END $(document).ready()

</script>

Note that I used your class "btn-danger". You can create a different class, or use an id="someidthatimakeup".

How to print binary tree diagram?

I found VasyaNovikov's answer very useful for printing a large general tree, and modified it for a binary tree

Code:

class TreeNode {
    Integer data = null;
    TreeNode left = null;
    TreeNode right = null;

    TreeNode(Integer data) {this.data = data;}

    public void print() {
        print("", this, false);
    }

    public void print(String prefix, TreeNode n, boolean isLeft) {
        if (n != null) {
            System.out.println (prefix + (isLeft ? "|-- " : "\\-- ") + n.data);
            print(prefix + (isLeft ? "|   " : "    "), n.left, true);
            print(prefix + (isLeft ? "|   " : "    "), n.right, false);
        }
    }
}

Sample output:

\-- 7
    |-- 3
    |   |-- 1
    |   |   \-- 2
    |   \-- 5
    |       |-- 4
    |       \-- 6
    \-- 11
        |-- 9
        |   |-- 8
        |   \-- 10
        \-- 13
            |-- 12
            \-- 14

Javascript wait() function

You shouldn't edit it, you should completely scrap it.

Any attempt to make execution stop for a certain amount of time will lock up the browser and switch it to a Not Responding state. The only thing you can do is use setTimeout correctly.

Oracle date "Between" Query

Following query also can be used:

select * 
  from t23
 where trunc(start_date) between trunc(to_date('01/15/2010','mm/dd/yyyy')) and trunc(to_date('01/17/2010','mm/dd/yyyy'))

Base64 decode snippet in C++

Here is one written by me which uses unions and bit fields for maximum efficiency and readibility.

const char PADDING_CHAR = '=';
const char* ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const uint8_t DECODED_ALPHBET[128]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,62,0,0,0,63,52,53,54,55,56,57,58,59,60,61,0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,0,0,0,0,0,0,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,0,0,0,0,0};

/**
 * Given a string, this function will encode it in 64b (with padding)
 */
std::string encodeBase64(const std::string& binaryText)
{
    std::string encoded((binaryText.size()/3 + (binaryText.size()%3 > 0)) << 2, PADDING_CHAR);

    const char* bytes = binaryText.data();
    union
    {
        uint32_t temp = 0;
        struct
        {
            uint32_t first : 6, second : 6, third : 6, fourth : 6;
        } tempBytes;
    };
    std::string::iterator currEncoding = encoded.begin();

    for(uint32_t i = 0, lim = binaryText.size() / 3; i < lim; ++i, bytes+=3)
    {
        temp = bytes[0] << 16 | bytes[1] << 8 | bytes[2];
        (*currEncoding++) = ALPHABET[tempBytes.fourth];
        (*currEncoding++) = ALPHABET[tempBytes.third];
        (*currEncoding++) = ALPHABET[tempBytes.second];
        (*currEncoding++) = ALPHABET[tempBytes.first];
    }

    switch(binaryText.size() % 3)
    {
    case 1:
        temp = bytes[0] << 16;
        (*currEncoding++) = ALPHABET[tempBytes.fourth];
        (*currEncoding++) = ALPHABET[tempBytes.third];
        break;
    case 2:
        temp = bytes[0] << 16 | bytes[1] << 8;
        (*currEncoding++) = ALPHABET[tempBytes.fourth];
        (*currEncoding++) = ALPHABET[tempBytes.third];
        (*currEncoding++) = ALPHABET[tempBytes.second];
        break;
    }

    return encoded;
}

/**
 * Given a 64b padding-encoded string, this function will decode it.
 */
std::string decodeBase64(const std::string& base64Text)
{
    if( base64Text.empty() )
        return "";

    assert((base64Text.size()&3) == 0 && "The base64 text to be decoded must have a length devisible by 4!");

    uint32_t numPadding =  (*std::prev(base64Text.end(),1) == PADDING_CHAR) + (*std::prev(base64Text.end(),2) == PADDING_CHAR);

    std::string decoded((base64Text.size()*3>>2) - numPadding, '.');

    union
    {
        uint32_t temp;
        char tempBytes[4];
    };
    const uint8_t* bytes = reinterpret_cast<const uint8_t*>(base64Text.data());

    std::string::iterator currDecoding = decoded.begin();

    for(uint32_t i = 0, lim = (base64Text.size() >> 2) - (numPadding!=0); i < lim; ++i, bytes+=4)
    {
        temp = DECODED_ALPHBET[bytes[0]] << 18 | DECODED_ALPHBET[bytes[1]] << 12 | DECODED_ALPHBET[bytes[2]] << 6 | DECODED_ALPHBET[bytes[3]];
        (*currDecoding++) = tempBytes[2];
        (*currDecoding++) = tempBytes[1];
        (*currDecoding++) = tempBytes[0];
    }

    switch (numPadding)
    {
    case 2:
        temp = DECODED_ALPHBET[bytes[0]] << 18 | DECODED_ALPHBET[bytes[1]] << 12;
        (*currDecoding++) = tempBytes[2];
        break;
    
    case 1:
        temp = DECODED_ALPHBET[bytes[0]] << 18 | DECODED_ALPHBET[bytes[1]] << 12 | DECODED_ALPHBET[bytes[2]] << 6;
        (*currDecoding++) = tempBytes[2];
        (*currDecoding++) = tempBytes[1];
        break;
    }

    return decoded;
}

How do I show the number keyboard on an EditText in android?

You can configure an inputType for your EditText:

<EditText android:inputType="number" ... />

null terminating a string

Be very careful: NULL is a macro used mainly for pointers. The standard way of terminating a string is:

char *buffer;
...
buffer[end_position] = '\0';

This (below) works also but it is not a big difference between assigning an integer value to a int/short/long array and assigning a character value. This is why the first version is preferred and personally I like it better.

buffer[end_position] = 0; 

How to serialize object to CSV file?

First, serialization is writing the object to a file 'as it is'. AFAIK, you cannot choose file formats and all. The serialized object (in a file) has its own 'file format'

If you want to write the contents of an object (or a list of objects) to a CSV file, you can do it yourself, it should not be complex.

Looks like Java CSV Library can do this, but I have not tried this myself.

EDIT: See following sample. This is by no way foolproof, but you can build on this.

    //European countries use ";" as 
    //CSV separator because "," is their digit separator
    private static final String CSV_SEPARATOR = ",";
    private static void writeToCSV(ArrayList<Product> productList)
    {
        try
        {
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("products.csv"), "UTF-8"));
            for (Product product : productList)
            {
                StringBuffer oneLine = new StringBuffer();
                oneLine.append(product.getId() <=0 ? "" : product.getId());
                oneLine.append(CSV_SEPARATOR);
                oneLine.append(product.getName().trim().length() == 0? "" : product.getName());
                oneLine.append(CSV_SEPARATOR);
                oneLine.append(product.getCostPrice() < 0 ? "" : product.getCostPrice());
                oneLine.append(CSV_SEPARATOR);
                oneLine.append(product.isVatApplicable() ? "Yes" : "No");
                bw.write(oneLine.toString());
                bw.newLine();
            }
            bw.flush();
            bw.close();
        }
        catch (UnsupportedEncodingException e) {}
        catch (FileNotFoundException e){}
        catch (IOException e){}
    }

This is product (getters and setters hidden for readability):

class Product
{
    private long id;
    private String name;
    private double costPrice;
    private boolean vatApplicable;
}

And this is how I tested:

public static void main(String[] args)
{
    ArrayList<Product> productList = new ArrayList<Product>();
    productList.add(new Product(1, "Pen", 2.00, false));
    productList.add(new Product(2, "TV", 300, true));
    productList.add(new Product(3, "iPhone", 500, true));
    writeToCSV(productList);
}

Hope this helps.

Cheers.

Detect and exclude outliers in Pandas data frame

My function for dropping outliers

def drop_outliers(df, field_name):
    distance = 1.5 * (np.percentile(df[field_name], 75) - np.percentile(df[field_name], 25))
    df.drop(df[df[field_name] > distance + np.percentile(df[field_name], 75)].index, inplace=True)
    df.drop(df[df[field_name] < np.percentile(df[field_name], 25) - distance].index, inplace=True)

How can I wrap text in a label using WPF?

To wrap text in the label control, change the the template of label as follows:

<Style x:Key="ErrorBoxStyle" TargetType="{x:Type Label}">
    <Setter Property="BorderBrush" Value="#FFF08A73"/>
    <Setter Property="BorderThickness" Value="1"/>
    <Setter Property="Foreground" Value="Red"/>
    <Setter Property="Background" Value="#FFFFE3DF"/>
    <Setter Property="FontWeight" Value="Bold"/>
    <Setter Property="Padding" Value="5"/>
    <Setter Property="HorizontalContentAlignment" Value="Left"/>
    <Setter Property="VerticalContentAlignment" Value="Top"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Label}">
                <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true" CornerRadius="5" HorizontalAlignment="Stretch">
                     
                    <TextBlock TextWrapping="Wrap" Text="{TemplateBinding Content}"/>
                </Border>
                    
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Setting an image for a UIButton in code

Swift 3 version (butt_img must be an Image Set into Assets.xcassets or Images.xcassets folder in Xcode):

btnTwo.setBackgroundImage(UIImage(named: "butt_img"), for: .normal)
btnTwo.setTitle("My title", for: .normal)

Anyway, if you want the image to be scaled to fill the button's size, you may add a UIImageView over it and assign it your image:

let img = UIImageView()
img.frame = btnTwo.frame
img.contentMode = .scaleAspectFill
img.clipsToBounds = true
img.image = UIImage(named: "butt_img")
btnTwo.addSubview(img)

How to get response status code from jQuery.ajax?

You can check your respone content, just console.log it and you will see whitch property have a status code. If you do not understand jsons, please refer to the video: https://www.youtube.com/watch?v=Bv_5Zv5c-Ts

It explains very basic knowledge that let you feel more comfortable with javascript.

You can do it with shorter version of ajax request, please see code above:

$.get("example.url.com", function(data) {
                console.log(data);
            }).done(function() {
               // TO DO ON DONE
            }).fail(function(data, textStatus, xhr) {
                 //This shows status code eg. 403
                 console.log("error", data.status);
                 //This shows status message eg. Forbidden
                 console.log("STATUS: "+xhr);
            }).always(function() {
                 //TO-DO after fail/done request.
                 console.log("ended");
            });

Example console output:

error 403 
STATUS: Forbidden 
ended

Java 8: merge lists with stream API

I think flatMap() is what you're looking for.

For example:

 List<AClass> allTheObjects = map.values()
         .stream()
         .flatMap(listContainer -> listContainer.lst.stream())
         .collect(Collectors.toList());

How do I move an existing Git submodule within a Git repository?

The string in quotes after "[submodule" doesn't matter. You can change it to "foobar" if you want. It's used to find the matching entry in ".git/config".

Therefore, if you make the change before you run "git submodule init", it'll work fine. If you make the change (or pick up the change through a merge), you'll need to either manually edit .git/config or run "git submodule init" again. If you do the latter, you'll be left with a harmless "stranded" entry with the old name in .git/config.

Is an HTTPS query string secure?

Yes, it is. But using GET for sensitive data is a bad idea for several reasons:

  • Mostly HTTP referrer leakage (an external image in the target page might leak the password[1])
  • Password will be stored in server logs (which is obviously bad)
  • History caches in browsers

Therefore, even though Querystring is secured it's not recommended to transfer sensitive data over querystring.

[1] Although I need to note that RFC states that browser should not send referrers from HTTPS to HTTP. But that doesn't mean a bad 3rd party browser toolbar or an external image/flash from an HTTPS site won't leak it.

C# delete a folder and all files and folders within that folder

Err, what about just calling Directory.Delete(path, true); ?

How to get all privileges back to the root user in MySQL?

If you facing grant permission access denied problem, you can try mysql_upgrade to fix the problem:

/usr/bin/mysql_upgrade -u root -p

Login as root:

mysql -u root -p

Run this commands:

mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
mysql> FLUSH PRIVILEGES;

Basic authentication for REST API using spring restTemplate

As of Spring 5.1 you can use HttpHeaders.setBasicAuth

Create Basic Authorization header:

String username = "willie";
String password = ":p@ssword";
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(username, password);
...other headers goes here...

Pass the headers to the RestTemplate:

HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<Account> response = restTemplate.exchange(url, HttpMethod.GET, request, Account.class);
Account account = response.getBody();

Documentation: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/HttpHeaders.html#setBasicAuth-java.lang.String-java.lang.String-

How to select a value in dropdown javascript?

I realize that this is an old question, but I'll post the solution for my use case, in case others run into the same situation I did when implementing James Hill's answer (above).

I found this question while trying to solve the same issue. James' answer got me 90% there. However, for my use case, selecting the item from the dropdown also triggered an action on the page from dropdown's onchange event. James' code as written did not trigger this event (at least in Firefox, which I was testing in). As a result, I made the following minor change:

function setSelectedValue(object, value) {
    for (var i = 0; i < object.options.length; i++) {
        if (object.options[i].text === value) {
            object.options[i].selected = true;
            object.onchange();
            return;
        }
    }

    // Throw exception if option `value` not found.
    var tag = object.nodeName;
    var str = "Option '" + value + "' not found";

    if (object.id != '') {
        str = str + " in //" + object.nodeName.toLowerCase()
              + "[@id='" + object.id + "']."
    }

    else if (object.name != '') {
        str = str + " in //" + object.nodeName.toLowerCase()
              + "[@name='" + object.name + "']."
    }

    else {
        str += "."
    }

    throw str;
}

Note the object.onchange() call, which I added to the original solution. This calls the handler to make certain that the action on the page occurs.

Edit

Added code to throw an exception if option value is not found; this is needed for my use case.

Shift elements in a numpy array

There is no single function that does what you want. Your definition of shift is slightly different than what most people are doing. The ways to shift an array are more commonly looped:

>>>xs=np.array([1,2,3,4,5])
>>>shift(xs,3)
array([3,4,5,1,2])

However, you can do what you want with two functions.
Consider a=np.array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]):

def shift2(arr,num):
    arr=np.roll(arr,num)
    if num<0:
         np.put(arr,range(len(arr)+num,len(arr)),np.nan)
    elif num > 0:
         np.put(arr,range(num),np.nan)
    return arr
>>>shift2(a,3)
[ nan  nan  nan   0.   1.   2.   3.   4.   5.   6.]
>>>shift2(a,-3)
[  3.   4.   5.   6.   7.   8.   9.  nan  nan  nan]

After running cProfile on your given function and the above code you provided, I found that the code you provided makes 42 function calls while shift2 made 14 calls when arr is positive and 16 when it is negative. I will be experimenting with timing to see how each performs with real data.

List of special characters for SQL LIKE clause

ANSI SQL92:

  • %
  • _
  • an ESCAPE character only if specified.

It is disappointing that many databases do not stick to the standard rules and add extra characters, or incorrectly enable ESCAPE with a default value of ‘\’ when it is missing. Like we don't already have enough trouble with ‘\’!

It's impossible to write DBMS-independent code here, because you don't know what characters you're going to have to escape, and the standard says you can't escape things that don't need to be escaped. (See section 8.5/General Rules/3.a.ii.)

Thank you SQL! gnnn

Getting path of captured image in Android using camera intent

Here I updated the sample code in Kotlin. Please note on Nougat and above version Uri.fromFile(file) is not working and it crashes the app for that need to implement FileProvider which is safest way to send files from intent. For implementing this refer this answer or this article

private fun takePhotoFromCamera() {
        val isDeviceSupportCamera: Boolean = this.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)
        if (isDeviceSupportCamera) {
            val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)

            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                file = File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS + "/attachments")!!.path,
                        System.currentTimeMillis().toString() + ".jpg")
//            fileUri = Uri.fromFile(file)
                fileUri = FileProvider.getUriForFile(this, this.applicationContext.packageName + ".provider", file!!)
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri)
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
                    takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                }
                startActivityForResult(takePictureIntent, Constants.REQUEST_CODE_IMAGE_CAPTURE)
            }

        } else {
            Toast.makeText(this, this.getString(R.string.camera_not_supported), Toast.LENGTH_SHORT).show()
        }
    }

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
             if(requestCode == Constants.REQUEST_CODE_IMAGE_CAPTURE) {
                realPath = file?.path
                 //do what ever you want to do
            }
    }
}

sql server Get the FULL month name from a date

SELECT DATENAME(MONTH, GETDATE()) 
         + RIGHT(CONVERT(VARCHAR(12), GETDATE(), 107), 9) AS [Month DD, YYYY]

OR Date without Comma Between date and year, you can use the following

SELECT DATENAME(MONTH, GETDATE()) + ' ' + CAST(DAY(GETDATE()) AS VARCHAR(2))
           + ' ' + CAST(YEAR(GETDATE()) AS VARCHAR(4)) AS [Month DD YYYY]

How to query GROUP BY Month in a Year

I would be inclined to include the year in the output. One way:

select to_char(DATE_CREATED, 'YYYY-MM'), sum(Num_of_Pictures)
from pictures_table
group by to_char(DATE_CREATED, 'YYYY-MM')
order by 1

Another way (more standard SQL):

select extract(year from date_created) as yr, extract(month from date_created) as mon,
       sum(Num_of_Pictures)
from pictures_table
group by extract(year from date_created), extract(month from date_created)
order by yr, mon;

Remember the order by, since you presumably want these in order, and there is no guarantee about the order that rows are returned in after a group by.

How to select from subquery using Laravel Query Builder?

The solution of @JarekTkaczyk it is exactly what I was looking for. The only thing I miss is how to do it when you are using DB::table() queries. In this case, this is how I do it:

$other = DB::table( DB::raw("({$sub->toSql()}) as sub") )->select(
    'something', 
    DB::raw('sum( qty ) as qty'), 
    'foo', 
    'bar'
);
$other->mergeBindings( $sub );
$other->groupBy('something');
$other->groupBy('foo');
$other->groupBy('bar');
print $other->toSql();
$other->get();

Special atention how to make the mergeBindings without using the getQuery() method

Where to place and how to read configuration resource files in servlet based application?

Ex: In web.xml file the tag

<context-param>
        <param-name>chatpropertyfile</param-name>
        <!--  Name of the chat properties file. It contains the name and description                   of rooms.-->     
        <param-value>chat.properties</param-value>
    </context-param>

And chat.properties you can declare your properties like this

For Ex :

Jsp = Discussion about JSP can be made here.
Java = Talk about java and related technologies like J2EE.
ASP = Discuss about Active Server Pages related technologies like VBScript and JScript etc.
Web_Designing = Any discussion related to HTML, JavaScript, DHTML etc.
StartUp = Startup chat room. Chatter is added to this after he logs in.

Android transparent status bar and actionbar

I'm developing an app that needs to look similar in all devices with >= API14 when it comes to actionbar and statusbar customization. I've finally found a solution and since it took a bit of my time I'll share it to save some of yours. We start by using an appcompat-21 dependency.

Transparent Actionbar:

values/styles.xml:

<style name="AppTheme" parent="Theme.AppCompat.Light">
...
</style>

<style name="AppTheme.ActionBar.Transparent" parent="AppTheme">
    <item name="android:windowContentOverlay">@null</item>
    <item name="windowActionBarOverlay">true</item>
    <item name="colorPrimary">@android:color/transparent</item>
</style>

<style name="AppTheme.ActionBar" parent="AppTheme">
    <item name="windowActionBarOverlay">false</item>
    <item name="colorPrimary">@color/default_yellow</item>
</style>


values-v21/styles.xml:

<style name="AppTheme" parent="Theme.AppCompat.Light">
    ...
</style>

<style name="AppTheme.ActionBar.Transparent" parent="AppTheme">
    <item name="colorPrimary">@android:color/transparent</item>
</style>

<style name="AppTheme.ActionBar" parent="AppTheme">
    <item name="colorPrimaryDark">@color/bg_colorPrimaryDark</item>
    <item name="colorPrimary">@color/default_yellow</item>
</style>

Now you can use these themes in your AndroidManifest.xml to specify which activities will have a transparent or colored ActionBar:

    <activity
            android:name=".MyTransparentActionbarActivity"
            android:theme="@style/AppTheme.ActionBar.Transparent"/>

    <activity
            android:name=".MyColoredActionbarActivity"
            android:theme="@style/AppTheme.ActionBar"/>

enter image description here enter image description here enter image description here enter image description here enter image description here

Note: in API>=21 to get the Actionbar transparent you need to get the Statusbar transparent too, otherwise will not respect your colour styles and will stay light-grey.



Transparent Statusbar (only works with API>=19):
This one it's pretty simple just use the following code:

protected void setStatusBarTranslucent(boolean makeTranslucent) {
        if (makeTranslucent) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

But you'll notice a funky result: enter image description here

This happens because when the Statusbar is transparent the layout will use its height. To prevent this we just need to:

SOLUTION ONE:
Add this line android:fitsSystemWindows="true" in your layout view container of whatever you want to be placed bellow the Actionbar:

    ...
        <LinearLayout
                android:fitsSystemWindows="true"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
            ...
        </LinearLayout>
    ...

SOLUTION TWO:
Add a few lines to our previous method:

protected void setStatusBarTranslucent(boolean makeTranslucent) {
        View v = findViewById(R.id.bellow_actionbar);
        if (v != null) {
            int paddingTop = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? MyScreenUtils.getStatusBarHeight(this) : 0;
            TypedValue tv = new TypedValue();
            getTheme().resolveAttribute(android.support.v7.appcompat.R.attr.actionBarSize, tv, true);
            paddingTop += TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
            v.setPadding(0, makeTranslucent ? paddingTop : 0, 0, 0);
        }

        if (makeTranslucent) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

Where R.id.bellow_actionbar will be the layout container view id of whatever we want to be placed bellow the Actionbar:

...
    <LinearLayout
            android:id="@+id/bellow_actionbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        ...
    </LinearLayout>
...

enter image description here

So this is it, it think I'm not forgetting something. In this example I didn't use a Toolbar but I think it'll have the same result. This is how I customize my Actionbar:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        View vg = getActionBarView();
        getWindow().requestFeature(vg != null ? Window.FEATURE_ACTION_BAR : Window.FEATURE_NO_TITLE);

        super.onCreate(savedInstanceState);
        setContentView(getContentView());

        if (vg != null) {
            getSupportActionBar().setCustomView(vg, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            getSupportActionBar().setDisplayShowCustomEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(false);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
            getSupportActionBar().setDisplayUseLogoEnabled(false);
        }
        setStatusBarTranslucent(true);
    }

Note: this is an abstract class that extends ActionBarActivity
Hope it helps!

Kotlin - Property initialization using "by lazy" vs. "lateinit"

If you are using Spring container and you want to initialize non-nullable bean field, lateinit is better suited.

    @Autowired
    lateinit var myBean: MyBean

JOIN two SELECT statement results

you can use the UNION ALL keyword for this.

Here is the MSDN doc to do it in T-SQL http://msdn.microsoft.com/en-us/library/ms180026.aspx

UNION ALL - combines the result set

UNION- Does something like a Set Union and doesnt output duplicate values

For the difference with an example: http://sql-plsql.blogspot.in/2010/05/difference-between-union-union-all.html

Asynchronous Function Call in PHP

I think some code about the cURL solution is needed here, so I will share mine (it was written mixing several sources as the PHP Manual and comments).

It does some parallel HTTP requests (domains in $aURLs) and print the responses once each one is completed (and stored them in $done for other possible uses).

The code is longer than needed because the realtime print part and the excess of comments, but feel free to edit the answer to improve it:

<?php
/* Strategies to avoid output buffering, ignore the block if you don't want to print the responses before every cURL is completed */
ini_set('output_buffering', 'off'); // Turn off output buffering
ini_set('zlib.output_compression', false); // Turn off PHP output compression       
//Flush (send) the output buffer and turn off output buffering
ob_end_flush(); while (@ob_end_flush());        
apache_setenv('no-gzip', true); //prevent apache from buffering it for deflate/gzip
ini_set('zlib.output_compression', false);
header("Content-type: text/plain"); //Remove to use HTML
ini_set('implicit_flush', true); // Implicitly flush the buffer(s)
ob_implicit_flush(true);
header('Cache-Control: no-cache'); // recommended to prevent caching of event data.
$string=''; for($i=0;$i<1000;++$i){$string.=' ';} output($string); //Safari and Internet Explorer have an internal 1K buffer.
//Here starts the program output

function output($string){
    ob_start();
    echo $string;
    if(ob_get_level()>0) ob_flush();
    ob_end_clean();  // clears buffer and closes buffering
    flush();
}

function multiprint($aCurlHandles,$print=true){
    global $done;
    // iterate through the handles and get your content
    foreach($aCurlHandles as $url=>$ch){
        if(!isset($done[$url])){ //only check for unready responses
            $html = curl_multi_getcontent($ch); //get the content           
            if($html){
                $done[$url]=$html;
                if($print) output("$html".PHP_EOL);
            }           
        }
    }
};

function full_curl_multi_exec($mh, &$still_running) {
    do {
      $rv = curl_multi_exec($mh, $still_running); //execute the handles 
    } while ($rv == CURLM_CALL_MULTI_PERFORM); //CURLM_CALL_MULTI_PERFORM means you should call curl_multi_exec() again because there is still data available for processing
    return $rv;
} 

set_time_limit(60); //Max execution time 1 minute

$aURLs = array("http://domain/script1.php","http://domain/script2.php");  // array of URLs

$done=array();  //Responses of each URL

    //Initialization
    $aCurlHandles = array(); // create an array for the individual curl handles
    $mh = curl_multi_init(); // init the curl Multi and returns a new cURL multi handle
    foreach ($aURLs as $id=>$url) { //add the handles for each url        
        $ch = curl_init(); // init curl, and then setup your options
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // returns the result - very important
        curl_setopt($ch, CURLOPT_HEADER, 0); // no headers in the output
        $aCurlHandles[$url] = $ch;
        curl_multi_add_handle($mh,$ch);
    }

    //Process
    $active = null; //the number of individual handles it is currently working with
    $mrc=full_curl_multi_exec($mh, $active); 
    //As long as there are active connections and everything looks OK…
    while($active && $mrc == CURLM_OK) { //CURLM_OK means is that there is more data available, but it hasn't arrived yet.  
        // Wait for activity on any curl-connection and if the network socket has some data…
        if($descriptions=curl_multi_select($mh,1) != -1) {//If waiting for activity on any curl_multi connection has no failures (1 second timeout)     
            usleep(500); //Adjust this wait to your needs               
            //Process the data for as long as the system tells us to keep getting it
            $mrc=full_curl_multi_exec($mh, $active);        
            //output("Still active processes: $active".PHP_EOL);        
            //Printing each response once it is ready
            multiprint($aCurlHandles);  
        }
    }

    //Printing all the responses at the end
    //multiprint($aCurlHandles,false);      

    //Finalize
    foreach ($aCurlHandles as $url=>$ch) {
        curl_multi_remove_handle($mh, $ch); // remove the handle (assuming  you are done with it);
    }
    curl_multi_close($mh); // close the curl multi handler
?>

How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"

Got a same error and this solved my error. Thanks! python 2 and python 3 differing in unicode handling is making pickled files quite incompatible to load. So Use python pickle's encoding argument. Link below helped me solve the similar problem when I was trying to open pickled data from my python 3.7, while my file was saved originally in python 2.x version. https://blog.modest-destiny.com/posts/python-2-and-3-compatible-pickle-save-and-load/ I copy the load_pickle function in my script and called the load_pickle(pickle_file) while loading my input_data like this:

input_data = load_pickle("my_dataset.pkl")

The load_pickle function is here:

def load_pickle(pickle_file):
    try:
        with open(pickle_file, 'rb') as f:
            pickle_data = pickle.load(f)
    except UnicodeDecodeError as e:
        with open(pickle_file, 'rb') as f:
            pickle_data = pickle.load(f, encoding='latin1')
    except Exception as e:
        print('Unable to load data ', pickle_file, ':', e)
        raise
    return pickle_data

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

Yes, you SHOULD:

  1. commit the package-lock.json.
  2. use npm ci instead of npm install when building your applications both on your CI and your local development machine

The npm ci workflow requires the existence of a package-lock.json.


A big downside of npm install command is its unexpected behavior that it may mutate the package-lock.json, whereas npm ci only uses the versions specified in the lockfile and produces an error

  • if the package-lock.json and package.json are out of sync
  • if a package-lock.json is missing.

Hence, running npm install locally, esp. in larger teams with multiple developers, may lead to lots of conflicts within the package-lock.json and developers to decide to completely delete the package-lock.json instead.

Yet there is a strong use-case for being able to trust that the project's dependencies resolve repeatably in a reliable way across different machines.

From a package-lock.json you get exactly that: a known-to-work state.

In the past, I had projects without package-lock.json / npm-shrinkwrap.json / yarn.lock files whose build would fail one day because a random dependency got a breaking update.

Those issue are hard to resolve as you sometimes have to guess what the last working version was.

If you want to add a new dependency, you still run npm install {dependency}. If you want to upgrade, use either npm update {dependency} or npm install ${dependendency}@{version} and commit the changed package-lock.json.

If an upgrade fails, you can revert to the last known working package-lock.json.


To quote npm doc:

It is highly recommended you commit the generated package lock to source control: this will allow anyone else on your team, your deployments, your CI/continuous integration, and anyone else who runs npm install in your package source to get the exact same dependency tree that you were developing on. Additionally, the diffs from these changes are human-readable and will inform you of any changes npm has made to your node_modules, so you can notice if any transitive dependencies were updated, hoisted, etc.

And in regards to the difference between npm ci vs npm install:

  • The project must have an existing package-lock.json or npm-shrinkwrap.json.
  • If dependencies in the package lock do not match those in package.json, npm ci will exit with an error, instead of updating the package lock.
  • npm ci can only install entire projects at a time: individual dependencies cannot be added with this command.
  • If a node_modules is already present, it will be automatically removed before npm ci begins its install.
  • It will never write to package.json or any of the package-locks: installs are essentially frozen.

Note: I posted a similar answer here

Pretty printing JSON from Jackson 2.2's ObjectMapper

You can enable pretty-printing by setting the SerializationFeature.INDENT_OUTPUT on your ObjectMapper like so:

mapper.enable(SerializationFeature.INDENT_OUTPUT);

Easy way to convert a unicode list to a list containing python strings?

[str(x) for x in EmployeeList] would do a conversion, but it would fail if the unicode string characters do not lie in the ascii range.

>>> EmployeeList = [u'1001', u'Karick', u'14-12-2020', u'1$']
>>> [str(x) for x in EmployeeList]
['1001', 'Karick', '14-12-2020', '1$']


>>> EmployeeList = [u'1001', u'????', u'14-12-2020', u'1$']
>>> [str(x) for x in EmployeeList]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

Avoid browser popup blockers

from Google's oauth JavaScript API:

http://code.google.com/p/google-api-javascript-client/wiki/Authentication

See the area where it reads:

Setting up Authentication

The client's implementation of OAuth 2.0 uses a popup window to prompt the user to sign-in and approve the application. The first call to gapi.auth.authorize can trigger popup blockers, as it opens the popup window indirectly. To prevent the popup blocker from triggering on auth calls, call gapi.auth.init(callback) when the client loads. The supplied callback will be executed when the library is ready to make auth calls.

I would guess its relating to the real answer above in how it explains if there is an immediate response, it won't trip the popup alarm. The "gapi.auth.init" is making it so the api happens immediately.

Practical Application

I made an open source authentication microservice using node passport on npm and the various passport packages for each provider. I used a standard redirect approach to the 3rd party giving it a redirect URL to come back to. This was programmatic so I could have different places to redirect back to if login/signup and on particular pages.

github.com/sebringj/athu

passportjs.org

When to use in vs ref vs out

Use out to denote that the parameter is not being used, only set. This helps the caller understand that you're always initializing the parameter.

Also, ref and out are not just for value types. They also let you reset the object that a reference type is referencing from within a method.

T-SQL: How to Select Values in Value List that are NOT IN the Table?

You need to somehow create a table with these values and then use NOT IN. This can be done with a temporary table, a CTE (Common Table Expression) or a Table Values Constructor (available in SQL-Server 2008):

SELECT email
FROM
    ( VALUES 
        ('email1')
      , ('email2')
      , ('email3')
    ) AS Checking (email)
WHERE email NOT IN 
      ( SELECT email 
        FROM Users
      ) 

The second result can be found with a LEFT JOIN or an EXISTS subquery:

SELECT email
     , CASE WHEN EXISTS ( SELECT * 
                          FROM Users u
                          WHERE u.email = Checking.email
                        ) 
            THEN 'Exists'
            ELSE 'Not exists'
       END AS status 
FROM
    ( VALUES 
        ('email1')
      , ('email2')
      , ('email3')
    ) AS Checking (email)

Renaming a directory in C#

There is no difference between moving and renaming; you should simply call Directory.Move.

In general, if you're only doing a single operation, you should use the static methods in the File and Directory classes instead of creating FileInfo and DirectoryInfo objects.

For more advice when working with files and directories, see here.

How to retrieve GET parameters from JavaScript

This solution handles URL decoding:

var params = function() {
    function urldecode(str) {
        return decodeURIComponent((str+'').replace(/\+/g, '%20'));
    }

    function transformToAssocArray( prmstr ) {
        var params = {};
        var prmarr = prmstr.split("&");
        for ( var i = 0; i < prmarr.length; i++) {
            var tmparr = prmarr[i].split("=");
            params[tmparr[0]] = urldecode(tmparr[1]);
        }
        return params;
    }

    var prmstr = window.location.search.substr(1);
    return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}();

Usage:

console.log('someParam GET value is', params['someParam']);

How to listen state changes in react.js?

The following lifecycle methods will be called when state changes. You can use the provided arguments and the current state to determine if something meaningful changed.

componentWillUpdate(object nextProps, object nextState)
componentDidUpdate(object prevProps, object prevState)

How to get the values of a ConfigurationSection of type NameValueSectionHandler

Try this;

Credit: https://www.limilabs.com/blog/read-system-net-mailsettings-smtp-settings-web-config

SmtpSection section = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");

string from = section.From;
string host = section.Network.Host;
int port = section.Network.Port;
bool enableSsl = section.Network.EnableSsl;
string user = section.Network.UserName;
string password = section.Network.Password;

Mockito : doAnswer Vs thenReturn

doAnswer and thenReturn do the same thing if:

  1. You are using Mock, not Spy
  2. The method you're stubbing is returning a value, not a void method.

Let's mock this BookService

public interface BookService {
    String getAuthor();
    void queryBookTitle(BookServiceCallback callback);
}

You can stub getAuthor() using doAnswer and thenReturn.

BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        return "Joshua";
    }
}).when(service).getAuthor();

Note that when using doAnswer, you can't pass a method on when.

// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());

So, when would you use doAnswer instead of thenReturn? I can think of two use cases:

  1. When you want to "stub" void method.

Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.

BookServiceCallback callback = new BookServiceCallback() {
    @Override
    public void onSuccess(String bookTitle) {
        assertEquals("Effective Java", bookTitle);
    }
};
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
        callback.onSuccess("Effective Java");
        // return null because queryBookTitle is void
        return null;
    }
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
  1. When you are using Spy instead of Mock

When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:

List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));

Using doAnswer we can stub it safely.

List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));

Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn.

List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));

What is N-Tier architecture?

It's my understanding that N-Tier separates business logic, client access and data from each other using separate physical machines. The theory is that one of them can be updated independently of the others.

Changing permissions via chmod at runtime errors with "Operation not permitted"

In order to perform chmod, you need to be owner of the file you are trying to modify, or the root user.

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

Here are few suggestions:

  1. Try restarting your Docker service.
  2. Check your network connections. For example by the following shell commands:

    </dev/tcp/registry-1.docker.io/443 && echo Works || echo Problem
    curl https://registry-1.docker.io/v2/ && echo Works || echo Problem
    
  3. Check your proxy settings (e.g. in /etc/default/docker).

If above won't help, this could be a temporary issue with the Docker services (as per Service Unavailable).

Related: GH-842 - 503 Service Unavailable at http://hub.docker.com.

I had this problem for past days, it just worked after that.

You can consider raising the issue at docker/hub-feedback repo, check at, Docker Community Forums, or contact Docker Support directly.

Cannot connect to repo with TortoiseSVN

Once I faced the same issue. I was trying to take svn checkout using repository URL consisting of DOMAIN NAME. I tried to connect using IP address in place of DOMAIN NAME and I was able to take checkout

How to determine if OpenSSL and mod_ssl are installed on Apache2

Usually, when you compile your apache2 server (or install it by packages facility stuff), you can check any directive that're available to be used by tapping this command:

~# $(which httpd) -L | grep SSL # on RHEL/CentOS/Fedora
~# $(which apache2) -L | grep SSL # on Ubuntu/Debian

If you don't see any SSL* directive, it means that you don't have apache2 with mod_ssl compiled.

Hopes it helps ;)

AngularJS : Difference between the $observe and $watch methods

If I understand your question right you are asking what is difference if you register listener callback with $watch or if you do it with $observe.

Callback registerd with $watch is fired when $digest is executed.

Callback registered with $observe are called when value changes of attributes that contain interpolation (e.g. attr="{{notJetInterpolated}}").


Inside directive you can use both of them on very similar way:

    attrs.$observe('attrYouWatch', function() {
         // body
    });

or

    scope.$watch(attrs['attrYouWatch'], function() {
         // body
    });

SQL grouping by all the columns

Short answer: no. GROUP BY clauses intrinsically require order to the way they arrange your results. A different order of field groupings would lead to different results.

Specifying a wildcard would leave the statement open to interpretation and unpredictable behaviour.

Removing padding gutter from grid columns in Bootstrap 4

Need an edge-to-edge design? Drop the parent .container or .container-fluid.

Still if you need to remove padding from .row and immediate child columns you have to add the class .no-gutters with the code from @Brian above to your own CSS file, actually it's Not 'right out of the box', check here for official details on the final Bootstrap 4 release: https://getbootstrap.com/docs/4.0/layout/grid/#no-gutters

Android Button Onclick

Use Layout inflater method in your button click. it will change your current .xml to targeted .xml file. Google for layout inflater code.

bower command not found

I am using node version manager. I was getting this error message because I had switched to a different version of node. When I switched back to the version of node where I installed bower, this error went away. In my case, the command was nvm use stable

Allow click on twitter bootstrap dropdown toggle link?

Since there is not really an answer that works (selected answer disables dropdown), or overrides using javascript, here goes.

This is all html and css fix (uses two <a> tags):

<ul class="nav">
 <li class="dropdown dropdown-li">
    <a class="dropdown-link" href="http://google.com">Dropdown</a>
    <a class="dropdown-caret dropdown-toggle"><b class="caret"></b></a>
    <ul class="dropdown-menu">
        <li><a href="#">Link 1</a></li>
        <li><a href="#">Link 2</a></li>
    </ul>
 </li>
</ul>

Now here's the CSS you need.

.dropdown-li {
    display:inline-block !important;
}
.dropdown-link {
    display:inline-block !important; 
    padding-right:4px !important;
}
.dropdown-caret {
    display:inline-block !important; 
    padding-left:4px !important;
}

Assuming you will want the both <a> tags to highlight on hover of either one, you will also need to override bootstrap, you might play around with the following:

.nav > li:hover {
    background-color: #f67a47; /*hover background color*/
}
.nav > li:hover > a {
    color: white; /*hover text color*/
}
.nav > li:hover > ul > a {
    color: black; /*dropdown item text color*/
}

Selected tab's color in Bottom Navigation View

BottomNavigationView uses colorPrimary from the theme applied for the selected tab and it uses android:textColorSecondary for the inactive tab icon tint.

So you can create a style with the prefered primary color and set it as a theme to your BottomNavigationView in an xml layout file.

styles.xml:

 <style name="BottomNavigationTheme" parent="Theme.AppCompat.Light">
        <item name="colorPrimary">@color/active_tab_color</item>
        <item name="android:textColorSecondary">@color/inactive_tab_color</item>
 </style>

your_layout.xml:

<android.support.design.widget.BottomNavigationView
            android:id="@+id/navigation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?android:attr/windowBackground"
            android:theme="@style/BottomNavigationTheme"
            app:menu="@menu/navigation" />

Responsively change div size keeping aspect ratio

(function( $ ) {
  $.fn.keepRatio = function(which) {
      var $this = $(this);
      var w = $this.width();
      var h = $this.height();
      var ratio = w/h;
      $(window).resize(function() {
          switch(which) {
              case 'width':
                  var nh = $this.width() / ratio;
                  $this.css('height', nh + 'px');
                  break;
              case 'height':
                  var nw = $this.height() * ratio;
                  $this.css('width', nw + 'px');
                  break;
          }
      });

  }
})( jQuery );      

$(document).ready(function(){
    $('#foo').keepRatio('width');
});

Working example: http://jsfiddle.net/QtftX/1/

What does it mean "No Launcher activity found!"

You missed in specifying the intent filter elements in your manifest file.Manifest file is:

<application android:label="@string/app_name" android:icon="@drawable/icon">
    <activity android:name="Your Activity Name"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Add and check this correctly. Hope this will help..

jquery validate check at least one checkbox

sir_neanderthal has already posted a nice answer.

I just want to point out that if you would like to use different names for your inputs you can also use (or just copy the method) require_from_group method from official jQuery Validation additional-methods.js (link to CDN for version 1.13.1).

Programmatically set TextBlock Foreground Color

To get the Color from Hex.

using System.Windows.Media;

Color color = (Color)ColorConverter.ConvertFromString("#FFDFD991");

and then set the foreground

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(color); 

Access Https Rest Service using Spring RestTemplate

This is a solution with no deprecated class or method : (Java 8 approved)

CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();

HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);

RestTemplate restTemplate = new RestTemplate(requestFactory);

Important information : Using NoopHostnameVerifier is a security risk

SQL select only rows with max value on a column

Another manner to do the job is using MAX() analytic function in OVER PARTITION clause

SELECT t.*
  FROM
    (
    SELECT id
          ,rev
          ,contents
          ,MAX(rev) OVER (PARTITION BY id) as max_rev
      FROM YourTable
    ) t
  WHERE t.rev = t.max_rev 

The other ROW_NUMBER() OVER PARTITION solution already documented in this post is

SELECT t.*
  FROM
    (
    SELECT id
          ,rev
          ,contents
          ,ROW_NUMBER() OVER (PARTITION BY id ORDER BY rev DESC) rank
      FROM YourTable
    ) t
  WHERE t.rank = 1 

This 2 SELECT work well on Oracle 10g.

MAX() solution runs certainly FASTER that ROW_NUMBER() solution because MAX() complexity is O(n) while ROW_NUMBER() complexity is at minimum O(n.log(n)) where n represent the number of records in table !

How do I test a single file using Jest?

To run an individual test:

npm test -t ValidationUtil # `ValidationUtil` is my module `ValidationUtil.spec.js`

-t - after it, put a regular expression containing the test name.

What is {this.props.children} and when you should use it?

props.children represents the content between the opening and the closing tags when invoking/rendering a component:

const Foo = props => (
  <div>
    <p>I'm {Foo.name}</p>
    <p>abc is: {props.abc}</p>

    <p>I have {props.children.length} children.</p>
    <p>They are: {props.children}.</p>
    <p>{Array.isArray(props.children) ? 'My kids are an array.' : ''}</p>
  </div>
);

const Baz = () => <span>{Baz.name} and</span>;
const Bar = () => <span> {Bar.name}</span>;

invoke/call/render Foo:

<Foo abc={123}>
  <Baz />
  <Bar />
</Foo>

props and props.children

python inserting variable string as file name

you can do something like

filename = "%s.csv" % name
f = open(filename , 'wb')

or f = open('%s.csv' % name, 'wb')

How do I wrap text in a span?

I've got a solution that should work in IE6 (and definitely works in 7+ & FireFox/Chrome).
You were on the right track using a span, but the use of a ul was wrong and the css wasn't right.

Try this

<a class="htooltip" href="#">
    Notes

    <span>
        Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci.
    </span>
</a>
.htooltip, .htooltip:visited, .tooltip:active {
    color: #0077AA;
    text-decoration: none;
}

.htooltip:hover {
    color: #0099CC;
}

.htooltip span {
    display : none;
    position: absolute;
    background-color: black;
    color: #fff;
    padding: 5px 10px 5px 40px;
    text-decoration: none;
    width: 350px;
    z-index: 10;
}

.htooltip:hover span {
    display: block;
}

Everyone was going about this the wrong way. The code isn't valid, ul's cant go in a's, p's can't go in a's, div's cant go in a's, just use a span (remembering to make it display as a block so it will wrap as if it were a div/p etc).

Vue.js get selected option on @change

You can save your @change="onChange()" an use watchers. Vue computes and watches, it´s designed for that. In case you only need the value and not other complex Event atributes.

Something like:

  ...
  watch: {
    leaveType () {
      this.whateverMethod(this.leaveType)
    }
  },
  methods: {
     onChange() {
         console.log('The new value is: ', this.leaveType)
     }
  }

Is it possible to clone html element objects in JavaScript / JQuery?

It's actually very easy in jQuery:

$("#ddl_1").clone().attr("id",newId).appendTo("body");

Change .appendTo() of course...

Finding duplicate rows in SQL Server

You can do it like this:

SELECT
    o.id, o.orgName, d.intCount
FROM (
     SELECT orgName, COUNT(*) as intCount
     FROM organizations
     GROUP BY orgName
     HAVING COUNT(*) > 1
) AS d
    INNER JOIN organizations o ON o.orgName = d.orgName

If you want to return just the records that can be deleted (leaving one of each), you can use:

SELECT
    id, orgName
FROM (
     SELECT 
         orgName, id,
         ROW_NUMBER() OVER (PARTITION BY orgName ORDER BY id) AS intRow
     FROM organizations
) AS d
WHERE intRow != 1

Edit: SQL Server 2000 doesn't have the ROW_NUMBER() function. Instead, you can use:

SELECT
    o.id, o.orgName, d.intCount
FROM (
     SELECT orgName, COUNT(*) as intCount, MIN(id) AS minId
     FROM organizations
     GROUP BY orgName
     HAVING COUNT(*) > 1
) AS d
    INNER JOIN organizations o ON o.orgName = d.orgName
WHERE d.minId != o.id

Pandas dataframe get first row of each group

This will give you the second row of each group (zero indexed, nth(0) is the same as first()):

df.groupby('id').nth(1) 

Documentation: http://pandas.pydata.org/pandas-docs/stable/groupby.html#taking-the-nth-row-of-each-group

Python read in string from file and split it into values

Something like this - for each line read into string variable a:

>>> a = "123,456"
>>> b = a.split(",")
>>> b
['123', '456']
>>> c = [int(e) for e in b]
>>> c
[123, 456]
>>> x, y = c
>>> x
123
>>> y
456

Now you can do what is necessary with x and y as assigned, which are integers.

JPA and Hibernate - Criteria vs. JPQL or HQL

I mostly prefer Criteria Queries for dynamic queries. For example it is much easier to add some ordering dynamically or leave some parts (e.g. restrictions) out depending on some parameter.

On the other hand I'm using HQL for static and complex queries, because it's much easier to understand/read HQL. Also, HQL is a bit more powerful, I think, e.g. for different join types.

UIButton action in table view cell

We can create a closure for the button and use that in cellForRowAtIndexPath

class ClosureSleeve {
  let closure: () -> ()

  init(attachTo: AnyObject, closure: @escaping () -> ()) {
    self.closure = closure
    objc_setAssociatedObject(attachTo, "[\(arc4random())]", self,.OBJC_ASSOCIATION_RETAIN)
}

@objc func invoke() {
   closure()
 }
}

extension UIControl {
func addAction(for controlEvents: UIControlEvents = .primaryActionTriggered, action: @escaping () -> ()) {
  let sleeve = ClosureSleeve(attachTo: self, closure: action)
 addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents)
 }
}

And then in cellForRowAtIndexPath

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell = youtableview.dequeueReusableCellWithIdentifier(identifier) as? youCell
    cell?.selectionStyle = UITableViewCell.SelectionStyle.none//swift 4 style

      button.addAction {
       //Do whatever you want to do when the button is tapped here
        print("button pressed")
      }

    return cell
 }

The type java.io.ObjectInputStream cannot be resolved. It is indirectly referenced from required .class files

You simply need to upgrade your Tomcat version, to Tomcat 8.0.xx. Java8 <-> Tomcat8

This is the configuration that I have been using and it has always worked out well JDK version Tomcat versions

Return a value if no rows are found in Microsoft tSQL

This is similar to Adam Robinson's, but uses ISNULL instead of COUNT.

SELECT ISNULL(
(SELECT 1 FROM Sites S
WHERE S.Id = @SiteId and S.Status = 1 AND 
      (S.WebUserId = @WebUserId OR S.AllowUploads = 1)), 0)

If the inner query has a matching row, then 1 is returned. The outer query (with ISNULL) then returns this value of 1. If the inner query has no matching row, then it doesn't return anything. The outer query treats this like a NULL, and so the ISNULL ends up returning 0.

Calculate difference in keys contained in two Python dictionaries

here's a solution that can compare more than two dicts:

def diff_dict(dicts, default=None):
    diff_dict = {}
    # add 'list()' around 'd.keys()' for python 3 compatibility
    for k in set(sum([d.keys() for d in dicts], [])):
        # we can just use "values = [d.get(k, default) ..." below if 
        # we don't care that d1[k]=default and d2[k]=missing will
        # be treated as equal
        if any(k not in d for d in dicts):
            diff_dict[k] = [d.get(k, default) for d in dicts]
        else:
            values = [d[k] for d in dicts]
            if any(v != values[0] for v in values):
                diff_dict[k] = values
    return diff_dict

usage example:

import matplotlib.pyplot as plt
diff_dict([plt.rcParams, plt.rcParamsDefault, plt.matplotlib.rcParamsOrig])

Assert that a WebElement is not present using Selenium WebDriver with java

The way that I have found best - and also to show in Allure report as fail - is to try-catch the findelement and in the catch block, set the assertTrue to false, like this:

    try {
        element = driver.findElement(By.linkText("Test Search"));
    }catch(Exception e) {
        assertTrue(false, "Test Search link was not displayed");
    }

What's the difference between UTF-8 and UTF-8 without BOM?

BOM tends to boom (no pun intended (sic)) somewhere, someplace. And when it booms (for example, doesn't get recognized by browsers, editors, etc.), it shows up as the weird characters  at the start of the document (for example, HTML file, JSON response, RSS, etc.) and causes the kind of embarrassments like the recent encoding issue experienced during the talk of Obama on Twitter.

It's very annoying when it shows up at places hard to debug or when testing is neglected. So it's best to avoid it unless you must use it.

Merge (Concat) Multiple JSONObjects in Java

It's a while from the question but now JSONObject implements "toMap" method so you can try this way:

Map<String, Object> map = Obj1.toMap();      //making an HashMap from obj1
map.putAll(Obj2.toMap());                    //moving all the stuff from obj2 to map
JSONObject combined = new JSONObject( map ); //new json from map

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

The mutable keyword is very useful when creating stubs for class test purposes. You can stub a const function and still be able to increase (mutable) counters or whatever test functionality you have added to your stub. This keeps the interface of the stubbed class intact.

Fixed width buttons with Bootstrap

If you place your buttons inside a div with class "btn-group" the buttons inside will stretch to the same size as the largest button.

eg:

<div class="btn-group">
  <button type="button" class="btn btn-default">Left</button>
  <button type="button" class="btn btn-default">Middle</button>
  <button type="button" class="btn btn-default">Right</button>
</div> 

Bootstrap Button Groups