Programs & Examples On #Coverity prevent

Coverity Prevent is a commercial static source code analyzer that looks for errors such as inconsistent NULL checks, dead code, unused return values, missing break statement, etc.

What does character set and collation mean exactly?

From MySQL docs:

A character set is a set of symbols and encodings. A collation is a set of rules for comparing characters in a character set. Let's make the distinction clear with an example of an imaginary character set.

Suppose that we have an alphabet with four letters: 'A', 'B', 'a', 'b'. We give each letter a number: 'A' = 0, 'B' = 1, 'a' = 2, 'b' = 3. The letter 'A' is a symbol, the number 0 is the encoding for 'A', and the combination of all four letters and their encodings is a character set.

Now, suppose that we want to compare two string values, 'A' and 'B'. The simplest way to do this is to look at the encodings: 0 for 'A' and 1 for 'B'. Because 0 is less than 1, we say 'A' is less than 'B'. Now, what we've just done is apply a collation to our character set. The collation is a set of rules (only one rule in this case): "compare the encodings." We call this simplest of all possible collations a binary collation.

But what if we want to say that the lowercase and uppercase letters are equivalent? Then we would have at least two rules: (1) treat the lowercase letters 'a' and 'b' as equivalent to 'A' and 'B'; (2) then compare the encodings. We call this a case-insensitive collation. It's a little more complex than a binary collation.

In real life, most character sets have many characters: not just 'A' and 'B' but whole alphabets, sometimes multiple alphabets or eastern writing systems with thousands of characters, along with many special symbols and punctuation marks. Also in real life, most collations have many rules: not just case insensitivity but also accent insensitivity (an "accent" is a mark attached to a character as in German 'ö') and multiple-character mappings (such as the rule that 'ö' = 'OE' in one of the two German collations).

Error 1046 No database Selected, how to resolve?

If you're trying to do this via the command line...

If you're trying to run the CREATE TABLE statement from the command line interface, you need to specify the database you're working in before executing the query:

USE your_database;

Here's the documentation.

If you're trying to do this via MySQL Workbench...

...you need to select the appropriate database/catalog in the drop down menu found above the :Object Browser: tab. You can specify the default schema/database/catalog for the connection - click the "Manage Connections" options under the SQL Development heading of the Workbench splash screen.

Addendum

This all assumes there's a database you want to create the table inside of - if not, you need to create the database before anything else:

CREATE DATABASE your_database;

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will coerce any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.


In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all

How do I call a function inside of another function?

_x000D_
_x000D_
function function_one()_x000D_
{_x000D_
    alert("The function called 'function_one' has been called.")_x000D_
    //Here u would like to call function_two._x000D_
    function_two(); _x000D_
}_x000D_
_x000D_
function function_two()_x000D_
{_x000D_
    alert("The function called 'function_two' has been called.")_x000D_
}
_x000D_
_x000D_
_x000D_

Detecting an undefined object property

Despite being vehemently recommended by many other answers here, typeof is a bad choice. It should never be used for checking whether variables have the value undefined, because it acts as a combined check for the value undefined and for whether a variable exists. In the vast majority of cases, you know when a variable exists, and typeof will just introduce the potential for a silent failure if you make a typo in the variable name or in the string literal 'undefined'.

var snapshot = …;

if (typeof snaposhot === 'undefined') {
    //         ^
    // misspelled¹ – this will never run, but it won’t throw an error!
}
var foo = …;

if (typeof foo === 'undefned') {
    //                   ^
    // misspelled – this will never run, but it won’t throw an error!
}

So unless you’re doing feature detection², where there’s uncertainty whether a given name will be in scope (like checking typeof module !== 'undefined' as a step in code specific to a CommonJS environment), typeof is a harmful choice when used on a variable, and the correct option is to compare the value directly:

var foo = …;

if (foo === undefined) {
    ?
}

Some common misconceptions about this include:

  • that reading an “uninitialized” variable (var foo) or parameter (function bar(foo) { … }, called as bar()) will fail. This is simply not true – variables without explicit initialization and parameters that weren’t given values always become undefined, and are always in scope.

  • that undefined can be overwritten. It’s true that undefined isn’t a keyword, but it is read-only and non-configurable. There are other built-ins you probably don’t avoid despite their non-keyword status (Object, Math, NaN…) and practical code usually isn’t written in an actively malicious environment, so this isn’t a good reason to be worried about undefined. (But if you are writing a code generator, feel free to use void 0.)

With how variables work out of the way, it’s time to address the actual question: object properties. There is no reason to ever use typeof for object properties. The earlier exception regarding feature detection doesn’t apply here – typeof only has special behaviour on variables, and expressions that reference object properties are not variables.

This:

if (typeof foo.bar === 'undefined') {
    ?
}

is always exactly equivalent to this³:

if (foo.bar === undefined) {
    ?
}

and taking into account the advice above, to avoid confusing readers as to why you’re using typeof, because it makes the most sense to use === to check for equality, because it could be refactored to checking a variable’s value later, and because it just plain looks better, you should always use === undefined³ here as well.

Something else to consider when it comes to object properties is whether you really want to check for undefined at all. A given property name can be absent on an object (producing the value undefined when read), present on the object itself with the value undefined, present on the object’s prototype with the value undefined, or present on either of those with a non-undefined value. 'key' in obj will tell you whether a key is anywhere on an object’s prototype chain, and Object.prototype.hasOwnProperty.call(obj, 'key') will tell you whether it’s directly on the object. I won’t go into detail in this answer about prototypes and using objects as string-keyed maps, though, because it’s mostly intended to counter all the bad advice in other answers irrespective of the possible interpretations of the original question. Read up on object prototypes on MDN for more!

¹ unusual choice of example variable name? this is real dead code from the NoScript extension for Firefox.
² don’t assume that not knowing what’s in scope is okay in general, though. bonus vulnerability caused by abuse of dynamic scope: Project Zero 1225
³ once again assuming an ES5+ environment and that undefined refers to the undefined property of the global object.

Field 'browser' doesn't contain a valid alias configuration

I had the same issue, but mine was because of wrong casing in path:

// Wrong - uppercase C in /pathCoordinate/
./path/pathCoordinate/pathCoordinateForm.component

// Correct - lowercase c in /pathcoordinate/
./path/pathcoordinate/pathCoordinateForm.component

Downloading a file from spring controllers

With Spring 3.0 you can use the HttpEntity return object. If you use this, then your controller does not need a HttpServletResponse object, and therefore it is easier to test. Except this, this answer is relative equals to the one of Infeligo.

If the return value of your pdf framework is an byte array (read the second part of my answer for other return values) :

@RequestMapping(value = "/files/{fileName}", method = RequestMethod.GET)
public HttpEntity<byte[]> createPdf(
                 @PathVariable("fileName") String fileName) throws IOException {

    byte[] documentBody = this.pdfFramework.createPdf(filename);

    HttpHeaders header = new HttpHeaders();
    header.setContentType(MediaType.APPLICATION_PDF);
    header.set(HttpHeaders.CONTENT_DISPOSITION,
                   "attachment; filename=" + fileName.replace(" ", "_"));
    header.setContentLength(documentBody.length);

    return new HttpEntity<byte[]>(documentBody, header);
}

If the return type of your PDF Framework (documentBbody) is not already a byte array (and also no ByteArrayInputStream) then it would been wise NOT to make it a byte array first. Instead it is better to use:

example with FileSystemResource:

@RequestMapping(value = "/files/{fileName}", method = RequestMethod.GET)
public HttpEntity<byte[]> createPdf(
                 @PathVariable("fileName") String fileName) throws IOException {

    File document = this.pdfFramework.createPdf(filename);

    HttpHeaders header = new HttpHeaders();
    header.setContentType(MediaType.APPLICATION_PDF);
    header.set(HttpHeaders.CONTENT_DISPOSITION,
                   "attachment; filename=" + fileName.replace(" ", "_"));
    header.setContentLength(document.length());

    return new HttpEntity<byte[]>(new FileSystemResource(document),
                                  header);
}

Declare and assign multiple string variables at the same time

All the information is in the existing answers, but I personally wished for a concise summary, so here's an attempt at it; the commands use int variables for brevity, but they apply analogously to any type, including string.

To declare multiple variables and:

  • either: initialize them each:
int i = 0, j = 1; // declare and initialize each; `var` is NOT supported as of C# 8.0
  • or: initialize them all to the same value:
int i, j;    // *declare* first (`var` is NOT supported)
i = j = 42;  // then *initialize* 

// Single-statement alternative that is perhaps visually less obvious:
// Initialize the first variable with the desired value, then use 
// the first variable to initialize the remaining ones.
int i = 42, j = i, k = i;

What doesn't work:

  • You cannot use var in the above statements, because var only works with (a) a declaration that has an initialization value (from which the type can be inferred), and (b), as of C# 8.0, if that declaration is the only one in the statement (otherwise you'll get compilation error error CS0819: Implicitly-typed variables cannot have multiple declarators).

  • Placing an initialization value only after the last variable in a multiple-declarations statement initializes the last variable only:

    int i, j = 1;// initializes *only* j

How to add an object to an array

_x000D_
_x000D_
/* array literal */
var aData = [];

/* object constructur */
function Person(firstname, lastname) {
  this.firstname = firstname;
  this.lastname = lastname;
  this.fullname = function() {
    return (this.firstname + " " + this.lastname);
  };
}

/* store object into array */
aData[aData.length] = new Person("Java", "Script"); // aData[0]

aData.push(new Person("Jhon", "Doe"));
aData.push(new Person("Anna", "Smith"));
aData.push(new Person("Black", "Pearl"));

aData[aData.length] = new Person("stack", "overflow"); // aData[4]

/* loop array */
for (var i in aData) {
  alert(aData[i].fullname());
}

/* convert array of object into string json */
var jsonString = JSON.stringify(aData);
document.write(jsonString);
_x000D_
_x000D_
_x000D_

Push object into array

How to filter by object property in angularJS

You could also do this to make it more dynamic.

<input name="filterByPolarity" data-ng-model="text.polarity"/>

Then you ng-repeat will look like this

<div class="tweet" data-ng-repeat="tweet in tweets | filter:text"></div>

This filter will of course only be used to filter by polarity

jQuery window scroll event does not fire up

The solution is:

 $('body').scroll(function(e){
    console.log(e);
});

Java: Add elements to arraylist with FOR loop where element name has increasing number

If you simply need a list, you could use:

List<Answer> answers = Arrays.asList(answer1, answer2, answer3);

If you specifically require an ArrayList, you could use:

ArrayList<Answer> answers = new ArrayList(Arrays.asList(answer1, answer2, answer3));

Insert line break inside placeholder attribute of a textarea?

What you could do is add the text as value, which respects the line break \n.

$('textarea').attr('value', 'This is a line \nthis should be a new line');

Then you could remove it on focus and apply it back (if empty) on blur. Something like this

var placeholder = 'This is a line \nthis should be a new line';
$('textarea').attr('value', placeholder);

$('textarea').focus(function(){
    if($(this).val() === placeholder){
        $(this).attr('value', '');
    }
});

$('textarea').blur(function(){
    if($(this).val() ===''){
        $(this).attr('value', placeholder);
    }    
});

Example: http://jsfiddle.net/airandfingers/pdXRx/247/

Not pure CSS and not clean but does the trick.

Show and hide divs at a specific time interval using jQuery

Working Example here - add /edit to the URL to play with the code

You just need to use JavaScript setInterval function

_x000D_
_x000D_
$('html').addClass('js');_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  var timer = setInterval(showDiv, 5000);_x000D_
_x000D_
  var counter = 0;_x000D_
_x000D_
  function showDiv() {_x000D_
    if (counter == 0) {_x000D_
      counter++;_x000D_
      return;_x000D_
    }_x000D_
_x000D_
    $('div', '#container')_x000D_
      .stop()_x000D_
      .hide()_x000D_
      .filter(function() {_x000D_
        return this.id.match('div' + counter);_x000D_
      })_x000D_
      .show('fast');_x000D_
    counter == 3 ? counter = 0 : counter++;_x000D_
_x000D_
  }_x000D_
_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"_x000D_
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">_x000D_
_x000D_
<head>_x000D_
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>_x000D_
  <title>Sandbox</title>_x000D_
  <meta http-equiv="Content-type" content="text/html; charset=utf-8" />_x000D_
  <style type="text/css" media="screen">_x000D_
    body {_x000D_
      background-color: #fff;_x000D_
      font: 16px Helvetica, Arial;_x000D_
      color: #000;_x000D_
    }_x000D_
    _x000D_
    .display {_x000D_
      width: 300px;_x000D_
      height: 200px;_x000D_
      border: 2px solid #000;_x000D_
    }_x000D_
    _x000D_
    .js .display {_x000D_
      display: none;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <h2>Example of using setInterval to trigger display of Div</h2>_x000D_
  <p>The first div will display after 10 seconds...</p>_x000D_
  <div id='container'>_x000D_
    <div id='div1' class='display' style="background-color: red;">_x000D_
      div1_x000D_
    </div>_x000D_
    <div id='div2' class='display' style="background-color: green;">_x000D_
      div2_x000D_
    </div>_x000D_
    <div id='div3' class='display' style="background-color: blue;">_x000D_
      div3_x000D_
    </div>_x000D_
    <div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

EDIT:

In response to your comment about the container div, just modify this

$('div','#container')

to this

$('#div1, #div2, #div3')

Error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

You may also use element.insertAdjacentHTML('beforeend', data);

Please read the "Security considerations" on MDN.

How to comment out a block of Python code in Vim

I have the following lines in my .vimrc:

" comment line, selection with Ctrl-N,Ctrl-N
au BufEnter *.py nnoremap  <C-N><C-N>    mn:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR>:noh<CR>`n
au BufEnter *.py inoremap  <C-N><C-N>    <C-O>mn<C-O>:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR><C-O>:noh<CR><C-O>`n
au BufEnter *.py vnoremap  <C-N><C-N>    mn:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR>:noh<CR>gv`n

" uncomment line, selection with Ctrl-N,N
au BufEnter *.py nnoremap  <C-N>n     mn:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR>:s/^#$//ge<CR>:noh<CR>`n
au BufEnter *.py inoremap  <C-N>n     <C-O>mn<C-O>:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR><C-O>:s/^#$//ge<CR><C-O>:noh<CR><C-O>`n
au BufEnter *.py vnoremap  <C-N>n     mn:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR>gv:s/#\n/\r/ge<CR>:noh<CR>gv`n

The shortcuts preserve your cursor position and your comments as long as they start with # (there is space after #). For example:

# variable x
x = 0

After commenting:

# variable x
#x = 0

After uncomennting:

# variable x
x = 0

EOFError: EOF when reading a line

convert your inputs to ints:

width = int(input())
height = int(input())

java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

Since this result is the first that Google returns for this error, I'll just add that if anyone looks for way do change java security settings without changing the global file java.security (for example you need to run some tests), you can just provide an overriding security file by JVM parameter -Djava.security.properties=your/file/path in which you can enable the necessary algorithms by overriding the disablements.

Getting multiple selected checkbox values in a string in javascript and PHP

var checkboxes = document.getElementsByName('location[]');
var vals = "";
for (var i=0, n=checkboxes.length;i<n;i++) 
{
    if (checkboxes[i].checked) 
    {
        vals += ","+checkboxes[i].value;
    }
}
if (vals) vals = vals.substring(1);

rotate image with css

Perform rotation using transform: rotate(xdeg) and also apply overflow: hidden to the parent component to avoid overlapping effect

.div-parent {
   overflow: hidden
}

.div-child {
   transform: rotate(270deg);
}

Setting Spring Profile variable

For Eclipse, setting -Dspring.profiles.active variable in the VM arguments would do the trick.

Go to

Right Click Project --> Run as --> Run Configurations --> Arguments

And add your -Dspring.profiles.active=dev in the VM arguments

How to print environment variables to the console in PowerShell?

Prefix the variable name with env:

$env:path

For example, if you want to print the value of environment value "MINISHIFT_USERNAME", then command will be:

$env:MINISHIFT_USERNAME

You can also enumerate all variables via the env drive:

Get-ChildItem env:

Get size of an Iterable in Java

java 8 and above

StreamSupport.stream(data.spliterator(), false).count();

How to update Ruby to 1.9.x on Mac?

I know it's an older post, but i wanna add some extra informations about that. Firstly, i think that rvm does great BUT it wasn't updating ruby from my system (MAC OS Yosemite).

What rvmwas doing : installing to another location and setting up the path there to my environment variable ... And i was kinda bored, because i had two ruby now on my system.

So to fix that, i uninstalled the rvm, then used the Homebrew package manager available here and installed ruby throw terminal command by doing brew install ruby.

And then, everything was working perfectly ! The ruby from my system was updated ! Hope it will help for the next adventurers !

Using GroupBy, Count and Sum in LINQ Lambda Expressions

var boxSummary = from b in boxes
                 group b by b.Owner into g
                 let nrBoxes = g.Count()
                 let totalWeight = g.Sum(w => w.Weight)
                 let totalVolume = g.Sum(v => v.Volume)
                 select new { Owner = g.Key, Boxes = nrBoxes,
                              TotalWeight = totalWeight,
                              TotalVolume = totalVolume }

What is the difference between 'typedef' and 'using' in C++11?

They are largely the same, except that:

The alias declaration is compatible with templates, whereas the C style typedef is not.

How to pass a null variable to a SQL Stored Procedure from C#.net code

Old question, but here's a fairly clean way to create a nullable parameter:

new SqlParameter("@note", (object) request.Body ?? DBNull.Value);

If request.Body has a value, then it's value is used. If it's null, then DbNull.Value is used.

How to add google-play-services.jar project dependency so my project will run and present map

Be Careful, Follow these steps and save your time

  1. Right Click on your Project Explorer.

  2. Select New-> Project -> Android Application Project from Existing Code

  3. Browse upto this path only - "C:\Users**your path**\Local\Android\android-sdk\extras\google\google_play_services"

  4. Be careful brose only upto - google_play_services and not upto google_play_services_lib

  5. And this way you are able to import the google play service lib.

Let me know if you have any queries regarding the same.

Thanks

Importing CSV data using PHP/MySQL

set_time_limit(10000);

$con = mysql_connect('127.0.0.1','root','password');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("db", $con);

$fp = fopen("file.csv", "r");

while( !feof($fp) ) {
  if( !$line = fgetcsv($fp, 1000, ';', '"')) {
     continue;
  }

    $importSQL = "INSERT INTO table_name VALUES('".$line[0]."','".$line[1]."','".$line[2]."')";

    mysql_query($importSQL) or die(mysql_error());  

}

fclose($fp);
mysql_close($con);

How to support placeholder attribute in IE8 and 9

You can use any one of these polyfills:

These scripts will add support for the placeholder attribute in browsers that do not support it, and they do not require jQuery!

Chrome Extension - Get DOM content

You don't have to use the message passing to obtain or modify DOM. I used chrome.tabs.executeScriptinstead. In my example I am using only activeTab permission, therefore the script is executed only on the active tab.

part of manifest.json

"browser_action": {
    "default_title": "Test",
    "default_popup": "index.html"
},
"permissions": [
    "activeTab",
    "<all_urls>"
]

index.html

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <button id="test">TEST!</button>
    <script src="test.js"></script>
  </body>
</html>

test.js

document.getElementById("test").addEventListener('click', () => {
    console.log("Popup DOM fully loaded and parsed");

    function modifyDOM() {
        //You can play with your DOM here or check URL against your regex
        console.log('Tab script:');
        console.log(document.body);
        return document.body.innerHTML;
    }

    //We have permission to access the activeTab, so we can call chrome.tabs.executeScript:
    chrome.tabs.executeScript({
        code: '(' + modifyDOM + ')();' //argument here is a string but function.toString() returns function's code
    }, (results) => {
        //Here we have just the innerHTML and not DOM structure
        console.log('Popup script:')
        console.log(results[0]);
    });
});

How do I execute .js files locally in my browser?

If you're using Google Chrome you can use the Chrome Dev Editor: https://github.com/dart-lang/chromedeveditor

Integrating Dropzone.js into existing HTML form with other fields

You can modify the formData by catching the 'sending' event from your dropzone.

dropZone.on('sending', function(data, xhr, formData){
        formData.append('fieldname', 'value');
});

Does `anaconda` create a separate PYTHONPATH variable for each new environment?

Anaconda does not use the PYTHONPATH. One should however note that if the PYTHONPATH is set it could be used to load a library that is not in the anaconda environment. That is why before activating an environment it might be good to do a

unset PYTHONPATH

For instance this PYTHONPATH points to an incorrect pandas lib:

export PYTHONPATH=/home/john/share/usr/anaconda/lib/python
source activate anaconda-2.7
python
>>>> import pandas as pd
/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/__init__.py", line 6, in <module>
    from . import hashtable, tslib, lib
ImportError: /home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8

unsetting the PYTHONPATH prevents the wrong pandas lib from being loaded:

unset PYTHONPATH
source activate anaconda-2.7
python
>>>> import pandas as pd
>>>>

Deleting records before a certain date

DELETE FROM table WHERE date < '2011-09-21 08:21:22';

Getting the text that follows after the regex match

if Matcher is initialized with str, after the match, you can get the part after the match with

str.substring(matcher.end())

Sample Code:

final String str = "Some lame sentence that is awesome";
final Matcher matcher = Pattern.compile("sentence").matcher(str);
if(matcher.find()){
    System.out.println(str.substring(matcher.end()).trim());
}

Output:

that is awesome

document.getElementById('btnid').disabled is not working in firefox and chrome

Try setting the disabled attribute directly:

if ( someCondition == true ) {
   document.getElementById('btn1').setAttribute('disabled', 'disabled');
} else {
   document.getElementById('btn1').removeAttribute('disabled');
}

Replace string within file contents

#!/usr/bin/python

with open(FileName) as f:
    newText=f.read().replace('A', 'Orange')

with open(FileName, "w") as f:
    f.write(newText)

How to vertically align text inside a flexbox?

Using display: flex you can control the vertical alignment of HTML elements.

_x000D_
_x000D_
.box {_x000D_
  height: 100px;_x000D_
  display: flex;_x000D_
  align-items: center; /* Vertical */_x000D_
  justify-content: center; /* Horizontal */_x000D_
  border:2px solid black;_x000D_
}_x000D_
_x000D_
.box div {_x000D_
  width: 100px;_x000D_
  height: 20px;_x000D_
  border:1px solid;_x000D_
}
_x000D_
<div class="box">_x000D_
  <div>Hello</div>_x000D_
  <p>World</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to catch an Exception from a thread

Use Callable instead of Thread, then you can call Future#get() which throws any exception that the Callable threw.

Including external jar-files in a new jar-file build with Ant

This is a classpath issue when running an executable jar as follows:

java -jar myfile.jar

One way to fix the problem is to set the classpath on the java command line as follows, adding the missing log4j jar:

java -cp myfile.jar:log4j.jar:otherjar.jar com.abc.xyz.MyMainClass

Of course the best solution is to add the classpath into the jar manifest so that the we can use the "-jar" java option:

<jar jarfile="myfile.jar">
    ..
    ..
    <manifest>
       <attribute name="Main-Class" value="com.abc.xyz.MyMainClass"/>
       <attribute name="Class-Path" value="log4j.jar otherjar.jar"/>
    </manifest>
</jar>

The following answer demonstrates how you can use the manifestclasspath to automate the seeting of the classpath manifest entry

Cannot find Main Class in File Compiled With Ant

How does HTTP file upload work?

I have this sample Java Code:

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;

public class TestClass {
    public static void main(String[] args) throws IOException {
        ServerSocket socket = new ServerSocket(8081);
        Socket accept = socket.accept();
        InputStream inputStream = accept.getInputStream();

        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
        char readChar;
        while ((readChar = (char) inputStreamReader.read()) != -1) {
            System.out.print(readChar);
        }

        inputStream.close();
        accept.close();
        System.exit(1);
    }
}

and I have this test.html file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>File Upload!</title>
</head>
<body>
<form method="post" action="http://localhost:8081" enctype="multipart/form-data">
    <input type="file" name="file" id="file">
    <input type="submit">
</form>
</body>
</html>

and finally the file I will be using for testing purposes, named a.dat has the following content:

0x39 0x69 0x65

if you interpret the bytes above as ASCII or UTF-8 characters, they will actually will be representing:

9ie

So let 's run our Java Code, open up test.html in our favorite browser, upload a.dat and submit the form and see what our server receives:

POST / HTTP/1.1
Host: localhost:8081
Connection: keep-alive
Content-Length: 196
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: null
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary06f6g54NVbSieT6y
DNT: 1
Accept-Encoding: gzip, deflate
Accept-Language: en,en-US;q=0.8,tr;q=0.6
Cookie: JSESSIONID=27D0A0637A0449CF65B3CB20F40048AF

------WebKitFormBoundary06f6g54NVbSieT6y
Content-Disposition: form-data; name="file"; filename="a.dat"
Content-Type: application/octet-stream

9ie
------WebKitFormBoundary06f6g54NVbSieT6y--

Well I am not surprised to see the characters 9ie because we told Java to print them treating them as UTF-8 characters. You may as well choose to read them as raw bytes..

Cookie: JSESSIONID=27D0A0637A0449CF65B3CB20F40048AF 

is actually the last HTTP Header here. After that comes the HTTP Body, where meta and contents of the file we uploaded actually can be seen.

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already

We don't know what server.properties file is that, we neither know what SimocoPoolSize means (do you?)

Let's guess you are using some custom pool of database connections. Then, I guess the problem is that your pool is configured to open 100 or 120 connections, but you Postgresql server is configured to accept MaxConnections=90 . These seem conflictive settings. Try increasing MaxConnections=120.

But you should first understand your db layer infrastructure, know what pool are you using, if you really need so many open connections in the pool. And, specially, if you are gracefully returning the opened connections to the pool

Detect IF hovering over element with jQuery

You can filter your elment from all hovered elements. Problematic code:

element.filter(':hover')

Save code:

jQuery(':hover').filter(element)

To return boolean:

jQuery(':hover').filter(element).length===0

Converting Object to JSON and JSON to Object in PHP, (library like Gson for Java)

I made a method to solve this. My approach is:

1 - Create a abstract class that have a method to convert Objects to Array (including private attr) using Regex. 2 - Convert the returned array to json.

I use this Abstract class as parent of all my domain classes

Class code:

namespace Project\core;

abstract class AbstractEntity {
    public function getAvoidedFields() {
        return array ();
    }
    public function toArray() {
        $temp = ( array ) $this;

        $array = array ();

        foreach ( $temp as $k => $v ) {
            $k = preg_match ( '/^\x00(?:.*?)\x00(.+)/', $k, $matches ) ? $matches [1] : $k;
            if (in_array ( $k, $this->getAvoidedFields () )) {
                $array [$k] = "";
            } else {

                // if it is an object recursive call
                if (is_object ( $v ) && $v instanceof AbstractEntity) {
                    $array [$k] = $v->toArray();
                }
                // if its an array pass por each item
                if (is_array ( $v )) {

                    foreach ( $v as $key => $value ) {
                        if (is_object ( $value ) && $value instanceof AbstractEntity) {
                            $arrayReturn [$key] = $value->toArray();
                        } else {
                            $arrayReturn [$key] = $value;
                        }
                    }
                    $array [$k] = $arrayReturn;
                }
                // if it is not a array and a object return it
                if (! is_object ( $v ) && !is_array ( $v )) {
                    $array [$k] = $v;
                }
            }
        }

        return $array;
    }
}

How to include() all PHP files from a directory?

this is just a modification of Karsten's code

function include_all_php($folder){
    foreach (glob("{$folder}/*.php") as $filename)
    {
        include $filename;
    }
}

include_all_php("my_classes");

CSS Display an Image Resized and Cropped

What I've done is to create a server side script that will resize and crop a picture on the server end so it'll send less data across the interweb.

It's fairly trivial, but if anyone is interested, I can dig up and post the code (asp.net)

How to make Bootstrap Panel body with fixed height

HTML :

<div class="span4">
  <div class="panel panel-primary">
    <div class="panel-heading">jhdsahfjhdfhs</div>
    <div class="panel-body panel-height">fdoinfds sdofjohisdfj</div>
  </div>
</div>

CSS :

.panel-height {
  height: 100px; / change according to your requirement/
}

Run .php file in Windows Command Prompt (cmd)

It seems your question is very much older. But I just saw it. I searched(not in google) and found My Answer.

So I am writing its solution so that others may get help from it.

Here is my solution.

Unlike the other answers, you don't need to setup environments.

all you need is just to write php index.php if index.php is your file name.

then you will see that, the file compiled and showing it's desired output.

Fast way of finding lines in one file that are not in another?

$ join -v 1 -t '' file1 file2
line2
line3

The -t makes sure that it compares the whole line, if you had a space in some of the lines.

Unable to execute dex: method ID not in [0, 0xffff]: 65536

Try adding below code in build.gradle, it worked for me -

compileSdkVersion 23
buildToolsVersion '23.0.1'
defaultConfig {
    multiDexEnabled true
}

MySQL INNER JOIN select only one row from second table

You can try this:

SELECT u.*, p.*
FROM users AS u LEFT JOIN (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY userid ORDER BY [Date] DESC) AS RowNo
    FROM payments  
) AS p ON u.userid = p.userid AND p.RowNo=1

Docker "ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network"

I had an identical problem with the same error message but the solution with removal of unused docker networks didn't help me. I've deleted all non-default docker networks (and all images and containers as well) but it didn't help - docker still was not able to create a new network.

The cause of the problem was in network interfaces that were left after OpenVpn installation. (It was installed on the host previously.) I found them by running ifconfig command:

...
tun0  Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  
      inet addr:10.8.0.2  P-t-P:10.8.0.2  Mask:255.255.255.0
      UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
      RX packets:75 errors:0 dropped:0 overruns:0 frame:0
      TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:100 
      RX bytes:84304 (84.3 KB)  TX bytes:0 (0.0 B)

tun1  Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  
      inet addr:10.8.0.2  P-t-P:10.8.0.2  Mask:255.255.255.0
      UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
      RX packets:200496 errors:0 dropped:0 overruns:0 frame:0
      TX packets:148828 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:100 
      RX bytes:211583838 (211.5 MB)  TX bytes:9568906 (9.5 MB)
...

I've found that I can remove them with a couple of commands:

ip link delete tun0
ip link delete tun1

After this the problem has disappeared.

WAMP 403 Forbidden message on Windows 7

hi there are 2 solutions :

  1. change the port 80 to 81 in the text file (httpd.conf) and click 127.0.0.1:81

  2. change setting the network go to control panel--network and internet--network and sharing center

click-->local area connection select-->propertis check true in the -allow other ..... and --- allo other .....

GSON - Date format

It seems that you need to define formats for both date and time part or use String-based formatting. For example:

Gson gson = new GsonBuilder()
   .setDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").create();

or using java.text.DateFormat

Gson gson = new GsonBuilder()
   .setDateFormat(DateFormat.FULL, DateFormat.FULL).create();

or do it with serializers:

I believe that formatters cannot produce timestamps, but this serializer/deserializer-pair seems to work

JsonSerializer<Date> ser = new JsonSerializer<Date>() {
  @Override
  public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext 
             context) {
    return src == null ? null : new JsonPrimitive(src.getTime());
  }
};

JsonDeserializer<Date> deser = new JsonDeserializer<Date>() {
  @Override
  public Date deserialize(JsonElement json, Type typeOfT,
       JsonDeserializationContext context) throws JsonParseException {
    return json == null ? null : new Date(json.getAsLong());
  }
};

Gson gson = new GsonBuilder()
   .registerTypeAdapter(Date.class, ser)
   .registerTypeAdapter(Date.class, deser).create();

If using Java 8 or above you should use the above serializers/deserializers like so:

JsonSerializer<Date> ser = (src, typeOfSrc, context) -> src == null ? null
            : new JsonPrimitive(src.getTime());

JsonDeserializer<Date> deser = (jSon, typeOfT, context) -> jSon == null ? null : new Date(jSon.getAsLong());

How do you reverse a string in place in JavaScript?

without converting string to array;

String.prototype.reverse = function() {

    var ret = "";
    var size = 0;

    for (var i = this.length - 1; -1 < i; i -= size) {

        if (
          '\uD800' <= this[i - 1] && this[i - 1] <= '\uDBFF' && 
          '\uDC00' <= this[i]     && this[i]     <= '\uDFFF'
        ) {
            size = 2;
            ret += this[i - 1] + this[i];
        } else {
            size = 1;
            ret += this[i];
        }
    }

    return ret;
}

console.log('ana~nam anañam' === 'mañana man~ana'.reverse());

using Array.reverse without converting characters to code points;

String.prototype.reverse = function() {

    var array = this.split("").reverse();

    for (var i = 0; i < this.length; ++i) {

        if (
          '\uD800' <= this[i - 1] && this[i - 1] <= '\uDBFF' && 
          '\uDC00' <= this[i]     && this[i]     <= '\uDFFF'
        ) {
            array[i - 1] = array[i - 1] + array[i];
            array[i] = array[i - 1].substr(0, 1);
            array[i - 1] = array[i - 1].substr(1, 1);
        }

    }

    return array.join("");
}

console.log('ana~nam anañam' === 'mañana man~ana'.reverse());

How to remove and clear all localStorage data

If you want to remove/clean all the values from local storage than use

localStorage.clear();

And if you want to remove the specific item from local storage than use the following code

localStorage.removeItem(key);

Eclipse: Set maximum line length for auto formatting?

for XML line width, update preferences > XML > XML Files > Editor > Line width

Is the ternary operator faster than an "if" condition in Java

Yes, it matters, but not because of code execution performance.

Faster (performant) coding is more relevant for looping and object instantiation than simple syntax constructs. The compiler should handle optimization (it's all gonna be about the same binary!) so your goal should be efficiency for You-From-The-Future (humans are always the bottleneck in software).

The answer citing 9 lines versus one can be misleading: fewer lines of code does not always equal better. Ternary operators can be a more concise way in limited situations (your example is a good one).

BUT they can often be abused to make code unreadable (which is a cardinal sin) = do not nest ternary operators!

Also consider future maintainability, if-else is much easier to extend or modify:

int a;
if ( i != 0 && k == 7 ){
    a = 10;
    logger.debug( "debug message here" );
}else
    a = 3;
    logger.debug( "other debug message here" );
}


int a = (i != 0 && k== 7 ) ? 10 : 3;  // density without logging nor ability to use breakpoints

p.s. very complete StackOverflow answer at To ternary or not to ternary?

How to map an array of objects in React

you must put object in your JSX, It`s easy way to do this just see my simple code here:

const link = [
  {
   name: "Cold Drink",
   link: "/coldDrink"
  },
  {
   name: "Hot Drink",
   link: "/HotDrink"
  },

{ name: "chease Cake", link: "/CheaseCake" } ]; and you must map this array in your code with simple object see this code :

const links = (this.props.link);
{links.map((item, i) => (
 <li key={i}>
   <Link to={item.link}>{item.name}</Link>
 </li>
 ))}

I hope this answer will be helpful for you ...:)

how to get the selected index of a drop down

$("select[name='CCards'] option:selected") should do the trick

See jQuery documentation for more detail: http://api.jquery.com/selected-selector/

UPDATE: if you need the index of the selected option, you need to use the .index() jquery method:

$("select[name='CCards'] option:selected").index()

Is it possible to format an HTML tooltip (title attribute)?

Mootools also has a nice 'Tips' class available in their 'more builder'.

What does hash do in python?

The Python docs for hash() state:

Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup.

Python dictionaries are implemented as hash tables. So any time you use a dictionary, hash() is called on the keys that you pass in for assignment, or look-up.

Additionally, the docs for the dict type state:

Values that are not hashable, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys.

Insert php variable in a href

Try using printf function or the concatination operator

http://php.net/manual/en/function.printf.php

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

There are several options... assuming you found your TD by var td = document.getElementyById('myTD_ID'); you can do:

  • td.innerHTML = "mytext";

  • td.textContent= "mytext";

  • td.innerText= "mytext"; - this one may not work outside IE? Not sure

  • Use firstChild or children array as previous poster noted.

If it's just the text that needs to be changed, textContent is faster and less prone to XSS attacks (https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent)

How to prevent SIGPIPEs (or handle them properly)

I'm super late to the party, but SO_NOSIGPIPE isn't portable, and might not work on your system (it seems to be a BSD thing).

A nice alternative if you're on, say, a Linux system without SO_NOSIGPIPE would be to set the MSG_NOSIGNAL flag on your send(2) call.

Example replacing write(...) by send(...,MSG_NOSIGNAL) (see nobar's comment)

char buf[888];
//write( sockfd, buf, sizeof(buf) );
send(    sockfd, buf, sizeof(buf), MSG_NOSIGNAL );

Should I use encodeURI or encodeURIComponent for encoding URLs?

Difference between encodeURI and encodeURIComponent:

encodeURIComponent(value) is mainly used to encode queryString parameter values, and it encodes every applicable character in value. encodeURI ignores protocol prefix (http://) and domain name.


In very, very rare cases, when you want to implement manual encoding to encode additional characters (though they don't need to be encoded in typical cases) like: ! * , then you might use:

function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

(source)

UnicodeEncodeError: 'latin-1' codec can't encode character

You are trying to store a Unicode codepoint \u201c using an encoding ISO-8859-1 / Latin-1 that can't describe that codepoint. Either you might need to alter the database to use utf-8, and store the string data using an appropriate encoding, or you might want to sanitise your inputs prior to storing the content; i.e. using something like Sam Ruby's excellent i18n guide. That talks about the issues that windows-1252 can cause, and suggests how to process it, plus links to sample code!

How to enumerate an enum

This question appears in Chapter 10 of "C# Step by Step 2013"

The author uses a double for-loop to iterate through a pair of Enumerators (to create a full deck of cards):

class Pack
{
    public const int NumSuits = 4;
    public const int CardsPerSuit = 13;
    private PlayingCard[,] cardPack;

    public Pack()
    {
        this.cardPack = new PlayingCard[NumSuits, CardsPerSuit];
        for (Suit suit = Suit.Clubs; suit <= Suit.Spades; suit++)
        {
            for (Value value = Value.Two; value <= Value.Ace; value++)
            {
                cardPack[(int)suit, (int)value] = new PlayingCard(suit, value);
            }
        }
    }
}

In this case, Suit and Value are both enumerations:

enum Suit { Clubs, Diamonds, Hearts, Spades }
enum Value { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace}

and PlayingCard is a card object with a defined Suit and Value:

class PlayingCard
{
    private readonly Suit suit;
    private readonly Value value;

    public PlayingCard(Suit s, Value v)
    {
        this.suit = s;
        this.value = v;
    }
}

The difference between fork(), vfork(), exec() and clone()

  1. fork() - creates a new child process, which is a complete copy of the parent process. Child and parent processes use different virtual address spaces, which is initially populated by the same memory pages. Then, as both processes are executed, the virtual address spaces begin to differ more and more, because the operating system performs a lazy copying of memory pages that are being written by either of these two processes and assigns an independent copies of the modified pages of memory for each process. This technique is called Copy-On-Write (COW).
  2. vfork() - creates a new child process, which is a "quick" copy of the parent process. In contrast to the system call fork(), child and parent processes share the same virtual address space. NOTE! Using the same virtual address space, both the parent and child use the same stack, the stack pointer and the instruction pointer, as in the case of the classic fork()! To prevent unwanted interference between parent and child, which use the same stack, execution of the parent process is frozen until the child will call either exec() (create a new virtual address space and a transition to a different stack) or _exit() (termination of the process execution). vfork() is the optimization of fork() for "fork-and-exec" model. It can be performed 4-5 times faster than the fork(), because unlike the fork() (even with COW kept in the mind), implementation of vfork() system call does not include the creation of a new address space (the allocation and setting up of new page directories).
  3. clone() - creates a new child process. Various parameters of this system call, specify which parts of the parent process must be copied into the child process and which parts will be shared between them. As a result, this system call can be used to create all kinds of execution entities, starting from threads and finishing by completely independent processes. In fact, clone() system call is the base which is used for the implementation of pthread_create() and all the family of the fork() system calls.
  4. exec() - resets all the memory of the process, loads and parses specified executable binary, sets up new stack and passes control to the entry point of the loaded executable. This system call never return control to the caller and serves for loading of a new program to the already existing process. This system call with fork() system call together form a classical UNIX process management model called "fork-and-exec".

How to dynamic filter options of <select > with jQuery?

This is a simple solution where you clone the lists options and keep them in an object for recovery later. The scripts cleans out the list and add only the options that contains the input text. This should also work cross browser. I got some help from this post: https://stackoverflow.com/a/5748709/542141

Html

<input id="search_input" placeholder="Type to filter">
<select id="theList" class="List" multiple="multiple">

or razor

@Html.ListBoxFor(g => g.SelectedItem, Model.items, new { @class = "List", @id = "theList" })

script

<script type="text/javascript">
  $(document).ready(function () {
    //copy options
    var options = $('#theList option').clone();
    //react on keyup in textbox
    $('#search_input').keyup(function () {
      var val = $(this).val();
      $('#theList').empty();
      //take only the options containing your filter text or all if empty
      options.filter(function (idx, el) {
        return val === '' || $(el).text().indexOf(val) >= 0;
      }).appendTo('#theList');//add it to list
     });
  });
</script>

Two inline-block, width 50% elements wrap to second line

NOTE: In 2016, you can probably use flexbox to solve this problem easier.

This method works correctly IE7+ and all major browsers, it's been tried and tested in a number of complex viewport-based web applications.

<style>
    .container {
        font-size: 0;
    }

    .ie7 .column {
        font-size: 16px; 
        display: inline; 
        zoom: 1;
    }

    .ie8 .column {
        font-size:16px;
    }

    .ie9_and_newer .column { 
        display: inline-block; 
        width: 50%; 
        font-size: 1rem;
    }
</style>

<div class="container">
    <div class="column">text that can wrap</div>
    <div class="column">text that can wrap</div>
</div>

Live demo: http://output.jsbin.com/sekeco/2

The only downside to this method for IE7/8, is relying on body {font-size:??px} as basis for em/%-based font-sizing.

IE7/IE8 specific CSS could be served using IE's Conditional comments

How to set Sqlite3 to be case insensitive when string comparing?

You can do it like this:

SELECT * FROM ... WHERE name LIKE 'someone'

(It's not the solution, but in some cases is very convenient)

"The LIKE operator does a pattern matching comparison. The operand to the right contains the pattern, the left hand operand contains the string to match against the pattern. A percent symbol ("%") in the pattern matches any sequence of zero or more characters in the string. An underscore ("_") in the pattern matches any single character in the string. Any other character matches itself or its lower/upper case equivalent (i.e. case-insensitive matching). (A bug: SQLite only understands upper/lower case for ASCII characters. The LIKE operator is case sensitive for unicode characters that are beyond the ASCII range. For example, the expression 'a' LIKE 'A' is TRUE but 'æ' LIKE 'Æ' is FALSE.)."

How do I change the text of a span element using JavaScript?

I used this one document.querySelector('ElementClass').innerText = 'newtext';

Appears to work with span, texts within classes/buttons

Android : change button text and background color

When you create an App, a file called styles.xml will be created in your res/values folder. If you change the styles, you can change the background, text color, etc for all your layouts. That way you don’t have to go into each individual layout and change the it manually.

styles.xml:

<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="Theme.AppBaseTheme" parent="@android:style/Theme.Light">
    <item name="android:editTextColor">#295055</item> 
    <item name="android:textColorPrimary">#295055</item>
    <item name="android:textColorSecondary">#295055</item>
    <item name="android:textColorTertiary">#295055</item>
    <item name="android:textColorPrimaryInverse">#295055</item>
    <item name="android:textColorSecondaryInverse">#295055</item>
    <item name="android:textColorTertiaryInverse">#295055</item>

     <item name="android:windowBackground">@drawable/custom_background</item>        
</style>

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>

parent="@android:style/Theme.Light" is Google’s native colors. Here is a reference of what the native styles are: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/res/res/values/themes.xml

name="Theme.AppBaseTheme" means that you are creating a style that inherits all the styles from parent="@android:style/Theme.Light". This part you can ignore unless you want to inherit from AppBaseTheme again. = <style name="AppTheme" parent="AppBaseTheme">

@drawable/custom_background is a custom image I put in the drawable’s folder. It is a 300x300 png image.

#295055 is a dark blue color.

My code changes the background and text color. For Button text, please look through Google’s native stlyes (the link I gave u above).

Then in Android Manifest, remember to include the code:

<application
android:theme="@style/Theme.AppBaseTheme">

XCOPY switch to create specified directory if it doesn't exist?

Use the /i with xcopy and if the directory doesn't exist it will create the directory for you.

What is a Data Transfer Object (DTO)?

A DTO is a dumb object - it just holds properties and has getters and setters, but no other logic of any significance (other than maybe a compare() or equals() implementation).

Typically model classes in MVC (assuming .net MVC here) are DTOs, or collections/aggregates of DTOs

Java 256-bit AES Password-Based Encryption

Share the password (a char[]) and salt (a byte[]—8 bytes selected by a SecureRandom makes a good salt—which doesn't need to be kept secret) with the recipient out-of-band. Then to derive a good key from this information:

/* Derive the key, given password and salt. */
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

The magic numbers (which could be defined as constants somewhere) 65536 and 256 are the key derivation iteration count and the key size, respectively.

The key derivation function is iterated to require significant computational effort, and that prevents attackers from quickly trying many different passwords. The iteration count can be changed depending on the computing resources available.

The key size can be reduced to 128 bits, which is still considered "strong" encryption, but it doesn't give much of a safety margin if attacks are discovered that weaken AES.

Used with a proper block-chaining mode, the same derived key can be used to encrypt many messages. In Cipher Block Chaining (CBC), a random initialization vector (IV) is generated for each message, yielding different cipher text even if the plain text is identical. CBC may not be the most secure mode available to you (see AEAD below); there are many other modes with different security properties, but they all use a similar random input. In any case, the outputs of each encryption operation are the cipher text and the initialization vector:

/* Encrypt the message. */
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] ciphertext = cipher.doFinal("Hello, World!".getBytes(StandardCharsets.UTF_8));

Store the ciphertext and the iv. On decryption, the SecretKey is regenerated in exactly the same way, using using the password with the same salt and iteration parameters. Initialize the cipher with this key and the initialization vector stored with the message:

/* Decrypt the message, given derived key and initialization vector. */
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
String plaintext = new String(cipher.doFinal(ciphertext), StandardCharsets.UTF_8);
System.out.println(plaintext);

Java 7 included API support for AEAD cipher modes, and the "SunJCE" provider included with OpenJDK and Oracle distributions implements these beginning with Java 8. One of these modes is strongly recommended in place of CBC; it will protect the integrity of the data as well as their privacy.


A java.security.InvalidKeyException with the message "Illegal key size or default parameters" means that the cryptography strength is limited; the unlimited strength jurisdiction policy files are not in the correct location. In a JDK, they should be placed under ${jdk}/jre/lib/security

Based on the problem description, it sounds like the policy files are not correctly installed. Systems can easily have multiple Java runtimes; double-check to make sure that the correct location is being used.

Is it possible to cherry-pick a commit from another git repository?

You'll need to add the other repository as a remote, then fetch its changes. From there you see the commit and you can cherry-pick it.

Like that:

git remote add other https://example.link/repository.git
git fetch other

Now you have all the information to simply do git cherry-pick.

More info about working with remotes here: https://git-scm.com/book/en/v2/Git-Basics-Working-with-Remotes

Is there a library function for Root mean square error (RMSE) in python?

Just in case someone finds this thread in 2019, there is a library called ml_metrics which is available without pre-installation in Kaggle's kernels, pretty lightweighted and accessible through pypi ( it can be installed easily and fast with pip install ml_metrics):

from ml_metrics import rmse
rmse(actual=[0, 1, 2], predicted=[1, 10, 5])
# 5.507570547286102

It has few other interesting metrics which are not available in sklearn, like mapk.

References:

how to add a jpg image in Latex

You need to use a graphics library. Put this in your preamble:

\usepackage{graphicx}

You can then add images like this:

\begin{figure}[ht!]
\centering
\includegraphics[width=90mm]{fixed_dome1.jpg}
\caption{A simple caption \label{overflow}}
\end{figure}

This is the basic template I use in my documents. The position and size should be tweaked for your needs. Refer to the guide below for more information on what parameters to use in \figure and \includegraphics. You can then refer to the image in your text using the label you gave in the figure:

And here we see figure \ref{overflow}.

Read this guide here for a more detailed instruction: http://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions

Convert IQueryable<> type object to List<T> type?

Then just Select:

var list = source.Select(s=>new { ID = s.ID, Name = s.Name }).ToList();

(edit) Actually - the names could be inferred in this case, so you could use:

var list = source.Select(s=>new { s.ID, s.Name }).ToList();

which saves a few electrons...

Which is preferred: Nullable<T>.HasValue or Nullable<T> != null?

There second method will be many times more effective (mostly because of compilers inlining and boxing but still numbers are very expressive):

public static bool CheckObjectImpl(object o)
{
    return o != null;
}

public static bool CheckNullableImpl<T>(T? o) where T: struct
{
    return o.HasValue;
}

Benchmark test:

BenchmarkDotNet=v0.10.5, OS=Windows 10.0.14393
Processor=Intel Core i5-2500K CPU 3.30GHz (Sandy Bridge), ProcessorCount=4
Frequency=3233539 Hz, Resolution=309.2587 ns, Timer=TSC
  [Host] : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1648.0
  Clr    : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1648.0
  Core   : .NET Core 4.6.25009.03, 64bit RyuJIT


        Method |  Job | Runtime |       Mean |     Error |    StdDev |        Min |        Max |     Median | Rank |  Gen 0 | Allocated |
-------------- |----- |-------- |-----------:|----------:|----------:|-----------:|-----------:|-----------:|-----:|-------:|----------:|
   CheckObject |  Clr |     Clr | 80.6416 ns | 1.1983 ns | 1.0622 ns | 79.5528 ns | 83.0417 ns | 80.1797 ns |    3 | 0.0060 |      24 B |
 CheckNullable |  Clr |     Clr |  0.0029 ns | 0.0088 ns | 0.0082 ns |  0.0000 ns |  0.0315 ns |  0.0000 ns |    1 |      - |       0 B |
   CheckObject | Core |    Core | 77.2614 ns | 0.5703 ns | 0.4763 ns | 76.4205 ns | 77.9400 ns | 77.3586 ns |    2 | 0.0060 |      24 B |
 CheckNullable | Core |    Core |  0.0007 ns | 0.0021 ns | 0.0016 ns |  0.0000 ns |  0.0054 ns |  0.0000 ns |    1 |      - |       0 B |

Benchmark code:

public class BenchmarkNullableCheck
{
    static int? x = (new Random()).Next();

    public static bool CheckObjectImpl(object o)
    {
        return o != null;
    }

    public static bool CheckNullableImpl<T>(T? o) where T: struct
    {
        return o.HasValue;
    }

    [Benchmark]
    public bool CheckObject()
    {
        return CheckObjectImpl(x);
    }

    [Benchmark]
    public bool CheckNullable()
    {
        return CheckNullableImpl(x);
    }
}

https://github.com/dotnet/BenchmarkDotNet was used

So if you have an option (e.g. writing custom serializers) to process Nullable in different pipeline than object - and use their specific properties - do it and use Nullable specific properties. So from consistent thinking point of view HasValue should be preferred. Consistent thinking can help you to write better code do not spending too much time in details.

PS. People say that advice "prefer HasValue because of consistent thinking" is not related and useless. Can you predict the performance of this?

public static bool CheckNullableGenericImpl<T>(T? t) where T: struct
{
    return t != null; // or t.HasValue?
}

PPS People continue minus, seems nobody tries to predict performance of CheckNullableGenericImpl. I will tell you: there compiler will not help you replacing !=null with HasValue. HasValue should be used directly if you are interested in performance.

Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src'

In my laravel & VueJS project I solved this error with webpack.mix.js file. It contains

const mix = require('laravel-mix');

mix.webpackConfig({
   devServer: {
     proxy: {
       '*': 'http://localhost:8000'
     }
   },
   resolve: {
     alias: {
       "@": path.resolve(
         __dirname,
         "resources/assets/js"
       )
     }
   }
 });

mix.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css');

C# LINQ find duplicates in List

Complete set of Linq to SQL extensions of Duplicates functions checked in MS SQL Server. Without using .ToList() or IEnumerable. These queries executing in SQL Server rather than in memory.. The results only return at memory.

public static class Linq2SqlExtensions {

    public class CountOfT<T> {
        public T Key { get; set; }
        public int Count { get; set; }
    }

    public static IQueryable<TKey> Duplicates<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> groupBy)
        => source.GroupBy(groupBy).Where(w => w.Count() > 1).Select(s => s.Key);

    public static IQueryable<TSource> GetDuplicates<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> groupBy)
        => source.GroupBy(groupBy).Where(w => w.Count() > 1).SelectMany(s => s);

    public static IQueryable<CountOfT<TKey>> DuplicatesCounts<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> groupBy)
        => source.GroupBy(groupBy).Where(w => w.Count() > 1).Select(y => new CountOfT<TKey> { Key = y.Key, Count = y.Count() });

    public static IQueryable<Tuple<TKey, int>> DuplicatesCountsAsTuble<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> groupBy)
        => source.GroupBy(groupBy).Where(w => w.Count() > 1).Select(s => Tuple.Create(s.Key, s.Count()));
}

Android - Start service on boot

Your Service may be getting shut down before it completes due to the device going to sleep after booting. You need to obtain a wake lock first. Luckily, the Support library gives us a class to do this:

public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // This is the Intent to deliver to our service.
        Intent service = new Intent(context, SimpleWakefulService.class);

        // Start the service, keeping the device awake while it is launching.
        Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
        startWakefulService(context, service);
    }
}

then, in your Service, make sure to release the wake lock:

    @Override
    protected void onHandleIntent(Intent intent) {
        // At this point SimpleWakefulReceiver is still holding a wake lock
        // for us.  We can do whatever we need to here and then tell it that
        // it can release the wakelock.

...
        Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
        SimpleWakefulReceiver.completeWakefulIntent(intent);
    }

Don't forget to add the WAKE_LOCK permission:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

Option to ignore case with .contains method?

With a null check on the dvdList and your searchString

    if (!StringUtils.isEmpty(searchString)) {
        return Optional.ofNullable(dvdList)
                       .map(Collection::stream)
                       .orElse(Stream.empty())
                       .anyMatch(dvd >searchString.equalsIgnoreCase(dvd.getTitle()));
      }

pull access denied repository does not exist or may require docker login

If you don't have an image with that name locally, docker will try to pull it from docker hub, but there's no such image on docker hub. Or simply try "docker login".

Create a new Ruby on Rails application using MySQL instead of SQLite

If you are creating a new rails application you can set the database using the -d switch like this:

rails -d mysql myapp

Its always easy to switch your database later though, and using sqlite really is easier if you are developing on a Mac.

How do I get a button to open another activity?

Apply the following steps:

  1. insert new layout xml in folder layout
  2. rename window2
  3. add new button and add this line: android:onClick="window2"

mainactivity.java

public void openWindow2(View v) {
        //call window2
        setContentView(R.layout.window2);           
    }
}

How to use <md-icon> in Angular Material?

<md-button class="md-fab md-primary" md-theme="cyan" aria-label="Profile">
    <md-icon icon="/img/icons/ic_people_24px.svg" style="width: 24px; height: 24px;"></md-icon>
</md-button>

source: https://material.angularjs.org/#/demo/material.components.button

Why use Ruby's attr_accessor, attr_reader and attr_writer?

All of the answers above are correct; attr_reader and attr_writer are more convenient to write than manually typing the methods they are shorthands for. Apart from that they offer much better performance than writing the method definition yourself. For more info see slide 152 onwards from this talk (PDF) by Aaron Patterson.

Using PropertyInfo.GetValue()

In your example propertyInfo.GetValue(this, null) should work. Consider altering GetNamesAndTypesAndValues() as follows:

public void GetNamesAndTypesAndValues()
{
  foreach (PropertyInfo propertyInfo in allClassProperties)
  {
    Console.WriteLine("{0} [type = {1}] [value = {2}]",
      propertyInfo.Name,
      propertyInfo.PropertyType,
      propertyInfo.GetValue(this, null));
  }
}

What's the difference between a null pointer and a void pointer?

Both void and null pointers point to a memory location in the end.

A null pointer points to place (in a memory segment) which is usually the 0th address of memory segment. It is almost all about how the underlying OS treat that "reserved" memory location (an implementation detail) when you try to access it to read/write or dereference. For example, that particular memory location can be marked as "non-accessible" and throws an expection when it's accessed.

A void pointer can point to anywhere and potentially represent any type (primitive, reference-type, and including null).

As someone nicely put above, null pointer represents a value whereas void* represents a type more than a value.

How to construct a WebSocket URI relative to the page URI?

Assuming your WebSocket server is listening on the same port as from which the page is being requested, I would suggest:

function createWebSocket(path) {
    var protocolPrefix = (window.location.protocol === 'https:') ? 'wss:' : 'ws:';
    return new WebSocket(protocolPrefix + '//' + location.host + path);
}

Then, for your case, call it as follows:

var socket = createWebSocket(location.pathname + '/to/ws');

Login to website, via C#

You can continue using WebClient to POST (instead of GET, which is the HTTP verb you're currently using with DownloadString), but I think you'll find it easier to work with the (slightly) lower-level classes WebRequest and WebResponse.

There are two parts to this - the first is to post the login form, the second is recovering the "Set-cookie" header and sending that back to the server as "Cookie" along with your GET request. The server will use this cookie to identify you from now on (assuming it's using cookie-based authentication which I'm fairly confident it is as that page returns a Set-cookie header which includes "PHPSESSID").


POSTing to the login form

Form posts are easy to simulate, it's just a case of formatting your post data as follows:

field1=value1&field2=value2

Using WebRequest and code I adapted from Scott Hanselman, here's how you'd POST form data to your login form:

string formUrl = "http://www.mmoinn.com/index.do?PageModule=UsersAction&Action=UsersLogin"; // NOTE: This is the URL the form POSTs to, not the URL of the form (you can find this in the "action" attribute of the HTML's form tag
string formParams = string.Format("email_address={0}&password={1}", "your email", "your password");
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
    os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];

Here's an example of what you should see in the Set-cookie header for your login form:

PHPSESSID=c4812cffcf2c45e0357a5a93c137642e; path=/; domain=.mmoinn.com,wowmine_referer=directenter; path=/; domain=.mmoinn.com,lang=en; path=/;domain=.mmoinn.com,adt_usertype=other,adt_host=-

GETting the page behind the login form

Now you can perform your GET request to a page that you need to be logged in for.

string pageSource;
string getUrl = "the url of the page behind the login";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
    pageSource = sr.ReadToEnd();
}

EDIT:

If you need to view the results of the first POST, you can recover the HTML it returned with:

using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
    pageSource = sr.ReadToEnd();
}

Place this directly below cookieHeader = resp.Headers["Set-cookie"]; and then inspect the string held in pageSource.

"Conversion to Dalvik format failed with error 1" on external JAR

I had the same problem, when I tried to export my project. Nothing to see in the console.

For me the solution was upgrading proguard to the lastest version, hopes this helpes someone.

Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection refused: connect

The mail server on CentOS 6 and other IPv6 capable server platforms may be bound to IPv6 localhost (::1) instead of IPv4 localhost (127.0.0.1).

Typical symptoms:

[root@host /]# telnet 127.0.0.1 25
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused

[root@host /]# telnet localhost 25
Trying ::1...
Connected to localhost.
Escape character is '^]'.
220 host ESMTP Exim 4.72 Wed, 14 Aug 2013 17:02:52 +0100

[root@host /]# netstat -plant | grep 25
tcp        0      0 :::25                       :::*                        LISTEN      1082/exim           

If this happens, make sure that you don't have two entries for localhost in /etc/hosts with different IP addresses, like this (bad) example:

[root@host /]# cat /etc/hosts
127.0.0.1 localhost.localdomain localhost localhost4.localdomain4 localhost4
::1       localhost localhost.localdomain localhost6 localhost6.localdomain6

To avoid confusion, make sure you only have one entry for localhost, preferably an IPv4 address, like this:

[root@host /]# cat /etc/hosts
127.0.0.1 localhost  localhost.localdomain   localhost4.localdomain4 localhost4
::1       localhost6 localhost6.localdomain6

React Router with optional path parameter

The edit you posted was valid for an older version of React-router (v0.13) and doesn't work anymore.


React Router v1, v2 and v3

Since version 1.0.0 you define optional parameters with:

<Route path="to/page(/:pathParam)" component={MyPage} />

and for multiple optional parameters:

<Route path="to/page(/:pathParam1)(/:pathParam2)" component={MyPage} />

You use parenthesis ( ) to wrap the optional parts of route, including the leading slash (/). Check out the Route Matching Guide page of the official documentation.

Note: The :paramName parameter matches a URL segment up to the next /, ?, or #. For more about paths and params specifically, read more here.


React Router v4 and above

React Router v4 is fundamentally different than v1-v3, and optional path parameters aren't explicitly defined in the official documentation either.

Instead, you are instructed to define a path parameter that path-to-regexp understands. This allows for much greater flexibility in defining your paths, such as repeating patterns, wildcards, etc. So to define a parameter as optional you add a trailing question-mark (?).

As such, to define an optional parameter, you do:

<Route path="/to/page/:pathParam?" component={MyPage} />

and for multiple optional parameters:

<Route path="/to/page/:pathParam1?/:pathParam2?" component={MyPage} />

Note: React Router v4 is incompatible with (read more here). Use version v3 or earlier (v2 recommended) instead.

Excel function to make SQL-like queries on worksheet data?

If you can save the workbook then you have the option to use ADO and Jet/ACE to treat the workbook as a database, and execute SQL against the sheet.

The MSDN information on how to hit Excel using ADO can be found here.

How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

Why so complicated?

Just check System Objects in Access-Options/Current Database/Navigation Options/Show System Objects

Open Table "MSysIMEXSpecs" and change according to your needs - its easy to read...

Easy way to test a URL for 404 in PHP?

this is just and slice of code, hope works for you

            $ch = @curl_init();
            @curl_setopt($ch, CURLOPT_URL, 'http://example.com');
            @curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1");
            @curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            @curl_setopt($ch, CURLOPT_TIMEOUT, 10);

            $response       = @curl_exec($ch);
            $errno          = @curl_errno($ch);
            $error          = @curl_error($ch);

                    $response = $response;
                    $info = @curl_getinfo($ch);
return $info['http_code'];

Writing BMP image in pure c/c++ without other libraries

If you get strange colors switches in the middle of your image using the above C++ function. Be sure to open the outstream in binary mode: imgFile.open(filename, std::ios_base::out | std::ios_base::binary);
Otherwise windows inserts unwanted characters in the middle of your file! (been banging my head on this issue for hours)

See related question here: Why does ofstream insert a 0x0D byte before 0x0A?

How do I resolve a path relative to an ASP.NET MVC 4 application root?

In the action you can call:

this.Request.PhysicalPath

that returns the physical path in reference to the current controller. If you only need the root path call:

this.Request.PhysicalApplicationPath

Python convert object to float

I eventually used:

weather["Temp"] = weather["Temp"].convert_objects(convert_numeric=True)

It worked just fine, except that I got the following message.

C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:3: FutureWarning:
convert_objects is deprecated.  Use the data-type specific converters pd.to_datetime, pd.to_timedelta and pd.to_numeric.

How to set an button align-right with Bootstrap?

This worked for me:

<div class="text-right">
    <button type="button">Button 1</button>
    <button type="button">Button 2</button>
</div>

Sort a two dimensional array based on one column

Using Lambdas since java 8:

final String[][] data = new String[][] { new String[] { "2009.07.25 20:24", "Message A" },
        new String[] { "2009.07.25 20:17", "Message G" }, new String[] { "2009.07.25 20:25", "Message B" },
        new String[] { "2009.07.25 20:30", "Message D" }, new String[] { "2009.07.25 20:01", "Message F" },
        new String[] { "2009.07.25 21:08", "Message E" }, new String[] { "2009.07.25 19:54", "Message R" } };
String[][] out = Arrays.stream(data).sorted(Comparator.comparing(x -> x[1])).toArray(String[][]::new);

System.out.println(Arrays.deepToString(out));
    

Output:

[[2009.07.25 20:24, Message A], [2009.07.25 20:25, Message B], [2009.07.25 20:30, Message D], [2009.07.25 21:08, Message E], [2009.07.25 20:01, Message F], [2009.07.25 20:17, Message G], [2009.07.25 19:54, Message R]]

Using ResourceManager

The quick and dirty way to check what string you need it to look at the generated .resources files.

Your .resources are generated in the resources projects obj/Debug directory. (if not right click on .resx file in solution explorer and hit 'Run Custom Tool' to generate the .resources files)

Navigate to this directory and have a look at the filenames. You should see a file ending in XYZ.resources. Copy that filename and remove the trailing .resources and that is the file you should be loading.

For example in my obj/Bin directory I have the file:

MyLocalisation.Properties.Resources.resources

If the resource files are in the same Class library/Application I would use the following C#

ResourceManager RM = new ResourceManager("MyLocalisation.Properties.Resources", Assembly.GetExecutingAssembly());

However, as it sounds like you are using the resources file from a separate Class library/Application you probably want

Assembly localisationAssembly = Assembly.Load("MyLocalisation");
ResourceManager RM =  new ResourceManager("MyLocalisation.Properties.Resources", localisationAssembly);

How do you select a particular option in a SELECT element in jQuery?

There are a number of ways to do this, but the cleanest approach has been lost among the top answers and loads of arguments over val(). Also some methods changed as of jQuery 1.6, so this needs an update.

For the following examples I will assume the variable $select is a jQuery object pointing at the desired <select> tag, e.g. via the following:

var $select = $('.selDiv .opts');

Note 1 - use val() for value matches:

For value matching, using val() is far simpler than using an attribute selector: https://jsfiddle.net/yz7tu49b/6/

$select.val("SEL2");

The setter version of .val() is implemented on select tags by setting the selected property of a matching option with the same value, so works just fine on all modern browsers.

Note 2 - use prop('selected', true):

If you want to set the selected state of an option directly, you can use prop (not attr) with a boolean parameter (rather than the text value selected):

e.g. https://jsfiddle.net/yz7tu49b/

$option.prop('selected', true);  // Will add selected="selected" to the tag

Note 3 - allow for unknown values:

If you use val() to select an <option>, but the val is not matched (might happen depending on the source of the values), then "nothing" is selected and $select.val() will return null.

So, for the example shown, and for the sake of robustness, you could use something like this https://jsfiddle.net/1250Ldqn/:

var $select = $('.selDiv .opts');
$select.val("SEL2");
if ($select.val() == null) {
  $select.val("DEFAULT");
}

Note 4 - exact text match:

If you want to match by exact text, you can use a filter with function. e.g. https://jsfiddle.net/yz7tu49b/2/:

var $select = $('.selDiv .opts');
$select.children().filter(function(){
    return this.text == "Selection 2";
}).prop('selected', true);

although if you may have extra whitespace you may want to add a trim to the check as in

    return $.trim(this.text) == "some value to match";

Note 5 - match by index

If you want to match by index just index the children of the select e.g. https://jsfiddle.net/yz7tu49b/3/

var $select = $('.selDiv .opts');
var index = 2;
$select.children()[index].selected = true;

Although I tend to avoid direct DOM properties in favour of jQuery nowadays, to future-proof code, so that could also be done as https://jsfiddle.net/yz7tu49b/5/:

var $select = $('.selDiv .opts');
var index = 2;
$select.children().eq(index).prop('selected', true);

Note 6 - use change() to fire the new selection

In all the above cases, the change event does not fire. This is by design so that you do not wind up with recursive change events.

To generate the change event, if required, just add a call to .change() to the jQuery select object. e.g. the very first simplest example becomes https://jsfiddle.net/yz7tu49b/7/

var $select = $('.selDiv .opts');
$select.val("SEL2").change();

There are also plenty of other ways to find the elements using attribute selectors, like [value="SEL2"], but you have to remember attribute selectors are relatively slow compared to all these other options.

How to move mouse cursor using C#?

First Add a Class called Win32.cs

public class Win32
{ 
    [DllImport("User32.Dll")]
    public static extern long SetCursorPos(int x, int y);

    [DllImport("User32.Dll")]
    public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);

    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int x;
        public int y;

        public POINT(int X, int Y)
        {
            x = X;
            y = Y;
        }
    }
}

You can use it then like this:

Win32.POINT p = new Win32.POINT(xPos, yPos);

Win32.ClientToScreen(this.Handle, ref p);
Win32.SetCursorPos(p.x, p.y);

How to declare a static const char* in your header file?

If you're using Visual C++, you can non-portably do this using hints to the linker...

// In foo.h...

class Foo
{
public:
   static const char *Bar;
};

// Still in foo.h; doesn't need to be in a .cpp file...

__declspec(selectany)
const char *Foo::Bar = "Blah";

__declspec(selectany) means that even though Foo::Bar will get declared in multiple object files, the linker will only pick up one.

Keep in mind this will only work with the Microsoft toolchain. Don't expect this to be portable.

How to display gpg key details without importing it?

pgpdump (https://www.lirnberger.com/tools/pgpdump/) is a tool that you can use to inspect pgp blocks.

It is not user friendly, and fairly technical, however,

  • it parses public or private keys (without warning)
  • it does not modify any keyring (sometimes it is not so clear what gpg does behind the hood, in my experience)
  • it prints all packets, specifically userid's packets which shows the various text data about the keys.
pgpdump -p test.asc 
New: Secret Key Packet(tag 5)(920 bytes)
    Ver 4 - new
    Public key creation time - Fri May 24 00:33:48 CEST 2019
    Pub alg - RSA Encrypt or Sign(pub 1)
    RSA n(2048 bits) - ...
    RSA e(17 bits) - ...
    RSA d(2048 bits) - ...
    RSA p(1024 bits) - ...
    RSA q(1024 bits) - ...
    RSA u(1020 bits) - ...
    Checksum - 49 2f 
New: User ID Packet(tag 13)(18 bytes)
    User ID - test (test) <tset>                        
New: Signature Packet(tag 2)(287 bytes)
    Ver 4 - new
    Sig type - Positive certification of a User ID and Public Key packet(0x13).
    Pub alg - RSA Encrypt or Sign(pub 1)
    Hash alg - SHA256(hash 8)
    Hashed Sub: signature creation time(sub 2)(4 bytes)
        Time - Fri May 24 00:33:49 CEST 2019
    Hashed Sub: issuer key ID(sub 16)(8 bytes)
        Key ID - 0x396D5E4A2E92865F
    Hashed Sub: key flags(sub 27)(1 bytes)
        Flag - This key may be used to certify other keys
        Flag - This key may be used to sign data
    Hash left 2 bytes - 74 7a 
    RSA m^d mod n(2048 bits) - ...
        -> PKCS-1

unfortunately it does not read stdin : /

Select n random rows from SQL Server table

This works for me:

SELECT * FROM table_name
ORDER BY RANDOM()
LIMIT [number]

SQL Server: How to check if CLR is enabled?

The accepted answer needs a little clarification. The row will be there if CLR is enabled or disabled. Value will be 1 if enabled, or 0 if disabled.

I use this script to enable on a server, if the option is disabled:

if not exists(
    SELECT value
    FROM sys.configurations
    WHERE name = 'clr enabled'
     and value = 1
)
begin
    exec sp_configure @configname=clr_enabled, @configvalue=1
    reconfigure
end

TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"

Thank you to all the commenters on this page. When I first installed the latest TortoiseSVN I got this error.

I was using the latest version, so decided to downgrade to 1.5.9 (as the rest of my colleagues were using) and this got it to work. Then, once built, my machine was moved onto another subnet and the problem started again.

I went to TortoiseSVN->Settings->Saved Data and cleared the Authentication data. After this it worked fine.

How do I create a SQL table under a different schema?

                           create a database schema in SQL Server 2008
1. Navigate to Security > Schemas
2. Right click on Schemas and select New Schema
3. Complete the details in the General tab for the new schema. Like, the schema name is "MySchema" and the schema owner is "Admin".
4. Add users to the schema as required and set their permissions:
5. Add any extended properties (via the Extended Properties tab)
6. Click OK.
                           Add a Table to the New Schema "MySchema"
1. In Object Explorer, right click on the table name and select "Design":
2. Changing database schema for a table in SQL Server Management Studio
3. From Design view, press F4 to display the Properties window.
4. From the Properties window, change the schema to the desired schema:
5. Close Design View by right clicking the tab and selecting "Close":
6. Closing Design View
7. Click "OK" when prompted to save
8. Your table has now been transferred to the "MySchema" schema.

Refresh the Object Browser view To confirm the changes
Done

I ran into a merge conflict. How can I abort the merge?

If you end up with merge conflict and doesn't have anything to commit, but still a merge error is being displayed. After applying all the below mentioned commands,

git reset --hard HEAD
git pull --strategy=theirs remote_branch
git fetch origin
git reset --hard origin

Please remove

.git\index.lock

File [cut paste to some other location in case of recovery] and then enter any of below command depending on which version you want.

git reset --hard HEAD
git reset --hard origin

Hope that helps!!!

Markdown and including multiple files

IMHO, You can get your result by concatenating your input *.md files like:

$ pandoc -s -o outputDoc.pdf inputDoc1.md inputDoc2.md outputDoc3.md

Credit card payment gateway in PHP?

Stripe has a PHP library to accept credit cards without needing a merchant account: https://github.com/stripe/stripe-php

Check out the documentation and FAQ, and feel free to drop by our chatroom if you have more questions.

How to add java plugin for Firefox on Linux?

Do you want the JDK or the JRE? Anyways, I had this problem too, a few weeks ago. I followed the instructions here and it worked:

http://www.backtrack-linux.org/wiki/index.php/Java_Install

NOTE: Before installing Java make sure you kill Firefox.

root@bt:~# killall -9 /opt/firefox/firefox-bin

You can download java from the official website. (Download tar.gz version)

We first create the directory and place java there:

root@bt:~# mkdir /opt/java

root@bt:~# mv -f jre1.7.0_05/ /opt/java/

Final changes.

root@bt:~# update-alternatives --install /usr/bin/java java /opt/java/jre1.7.0_05/bin/java 1

root@bt:~# update-alternatives --set java /opt/java/jre1.7.0_05/bin/java

root@bt:~# export JAVA_HOME="/opt/java/jre1.7.0_05"

Adding the plugin to Firefox.

For Java 7 (32 bit)

root@bt:~# ln -sf $JAVA_HOME/lib/i386/libnpjp2.so /usr/lib/mozilla/plugins/

For Java 8 (64 bit)

root@bt:~# ln -sf $JAVA_HOME/jre/lib/amd64/libnpjp2.so /usr/lib/mozilla/plugins/

Testing the plugin.

root@bt:~# firefox http://java.com/en/download/testjava.jsp

Changing password with Oracle SQL Developer

I confirmed this works in SQL Developer 3.0.04. Our passwords are required to have a special character, so the double-quoted string is needed in our case. Of course, this only works if the password has not already expired and you are currently logged in.

ALTER USER MYUSERID
IDENTIFIED BY "new#password"
REPLACE "old#password"

how to modify the size of a column

If you run it, it will work, but in order for SQL Developer to recognize and not warn about a possible error you can change it as:

ALTER TABLE TEST_PROJECT2 MODIFY (proj_name VARCHAR2(300));

Caesar Cipher Function in Python

>>> def rotate(txt, key):
...   def cipher(i, low=range(97,123), upper=range(65,91)):
...     if i in low or i in upper:
...       s = 65 if i in upper else 97
...       i = (i - s + key) % 26 + s
...     return chr(i)
...   return ''.join([cipher(ord(s)) for s in txt])

# test
>>> rotate('abc', 2)
'cde'
>>> rotate('xyz', 2)
'zab'
>>> rotate('ab', 26)
'ab'
>>> rotate('Hello, World!', 7)
'Olssv, Dvysk!'

How to clean old dependencies from maven repositories?

I wanted to remove old dependencies from my Maven repository as well. I thought about just running Florian's answer, but I wanted something that I could run over and over without remembering a long linux snippet, and I wanted something with a little bit of configurability -- more of a program, less of a chain of unix commands, so I took the base idea and made it into a (relatively small) Ruby program, which removes old dependencies based on their last access time.

It doesn't remove "old versions" but since you might actually have two different active projects with two different versions of a dependency, that wouldn't have done what I wanted anyway. Instead, like Florian's answer, it removes dependencies that haven't been accessed recently.

If you want to try it out, you can:

  1. Visit the GitHub repository
  2. Clone the repository, or download the source
  3. Optionally inspect the code to make sure it's not malicious
  4. Run bin/mvnclean

There are options to override the default Maven repository, ignore files, set the threshold date, but you can read those in the README on GitHub.

I'll probably package it as a Ruby gem at some point after I've done a little more work on it, which will simplify matters (gem install mvnclean; mvnclean) if you already have Ruby installed and operational.

C# compiler error: "not all code paths return a value"

I also experienced this problem and found the easy solution to be

public string ReturnValues()
{
    string _var = ""; // Setting an innitial value

    if (.....)  // Looking at conditions
    {
        _var = "true"; // Re-assign the value of _var
    }

    return _var; // Return the value of var
}

This also works with other return types and gives the least amount of problems

The initial value I chose was a fall-back value and I was able to re-assign the value as many times as required.

How to pass a type as a method parameter in Java

You can pass an instance of java.lang.Class that represents the type, i.e.

private void foo(Class cls)

Access denied for user 'test'@'localhost' (using password: YES) except root user

Make sure the user has a localhost entry in the users table. That was the problem I was having. EX:

CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';

Gerrit error when Change-Id in commit messages are missing

I got this error message too.

and what makes me think it is useful to give an answer here is that the answer from @Rafal Rawicki is a good solution in some cases but not for all circumstances. example that i met:

1.run "git log" we can get the HEAD commit change-id

2.we also can get a 'HEAD' commit change-id on Gerrit website.

3.they are different ,which makes us can not push successfully and get the "missing change-id error"

solution:

0.'git add .'

1.save your HEAD commit change-id got from 'git log',it will be used later.

2.copy the HEAD commit change-id from Gerrit website.

3.'git reset HEAD'

4.'git commit --amend' and copy the change-id from **Gerrit website** to the commit message in the last paragraph(replace previous change-id)

5.'git push *' you can push successfully now but can not find the HEAD commit from **git log** on Gerrit website too

6.'git reset HEAD'

7.'git commit --amend' and copy the change-id from **git log**(we saved in step 1) to the commit message in the last paragraph(replace previous change-id)

8.'git push *' you can find the HEAD commit from **git log** on Gerrit website,they have the same change-id

9.done

How to check task status in Celery?

Return the task_id (which is given from .delay()) and ask the celery instance afterwards about the state:

x = method.delay(1,2)
print x.task_id

When asking, get a new AsyncResult using this task_id:

from celery.result import AsyncResult
res = AsyncResult("your-task-id")
res.ready()

Using std::max_element on a vector<double>

min/max_element return the iterator to the min/max element, not the value of the min/max element. You have to dereference the iterator in order to get the value out and assign it to a double. That is:

cLower = *min_element(C.begin(), C.end());

wget command to download a file and save as a different filename

Also notice the order of parameters on the command line. At least on some systems (e.g. CentOS 6):

wget -O FILE URL

works. But:

wget URL -O FILE

does not work.

How to plot a subset of a data frame in R?

Most straightforward option:

plot(var1[var3<155],var2[var3<155])

It does not look good because of code redundancy, but is ok for fastndirty hacking.

What does the C++ standard state the size of int, long type to be?

From Alex B The C++ standard does not specify the size of integral types in bytes, but it specifies minimum ranges they must be able to hold. You can infer minimum size in bits from the required range. You can infer minimum size in bytes from that and the value of the CHAR_BIT macro that defines the number of bits in a byte (in all but the most obscure platforms it's 8, and it can't be less than 8).

One additional constraint for char is that its size is always 1 byte, or CHAR_BIT bits (hence the name).

Minimum ranges required by the standard (page 22) are:

and Data Type Ranges on MSDN:

signed char: -127 to 127 (note, not -128 to 127; this accommodates 1's-complement platforms) unsigned char: 0 to 255 "plain" char: -127 to 127 or 0 to 255 (depends on default char signedness) signed short: -32767 to 32767 unsigned short: 0 to 65535 signed int: -32767 to 32767 unsigned int: 0 to 65535 signed long: -2147483647 to 2147483647 unsigned long: 0 to 4294967295 signed long long: -9223372036854775807 to 9223372036854775807 unsigned long long: 0 to 18446744073709551615 A C++ (or C) implementation can define the size of a type in bytes sizeof(type) to any value, as long as

the expression sizeof(type) * CHAR_BIT evaluates to the number of bits enough to contain required ranges, and the ordering of type is still valid (e.g. sizeof(int) <= sizeof(long)). The actual implementation-specific ranges can be found in header in C, or in C++ (or even better, templated std::numeric_limits in header).

For example, this is how you will find maximum range for int:

C:

#include <limits.h>
const int min_int = INT_MIN;
const int max_int = INT_MAX;

C++:

#include <limits>
const int min_int = std::numeric_limits<int>::min();
const int max_int = std::numeric_limits<int>::max();

This is correct, however, you were also right in saying that: char : 1 byte short : 2 bytes int : 4 bytes long : 4 bytes float : 4 bytes double : 8 bytes

Because 32 bit architectures are still the default and most used, and they have kept these standard sizes since the pre-32 bit days when memory was less available, and for backwards compatibility and standardization it remained the same. Even 64 bit systems tend to use these and have extentions/modifications. Please reference this for more information:

http://en.cppreference.com/w/cpp/language/types

Inserting multiple rows in a single SQL query?

If you are inserting into a single table, you can write your query like this (maybe only in MySQL):

INSERT INTO table1 (First, Last)
VALUES
    ('Fred', 'Smith'),
    ('John', 'Smith'),
    ('Michael', 'Smith'),
    ('Robert', 'Smith');

How to filter a RecyclerView with a SearchView

Following @Shruthi Kamoji in a cleaner way, we can just use a filterable, its meant for that:

public abstract class GenericRecycleAdapter<E> extends RecyclerView.Adapter implements Filterable
{
    protected List<E> list;
    protected List<E> originalList;
    protected Context context;

    public GenericRecycleAdapter(Context context,
    List<E> list)
    {
        this.originalList = list;
        this.list = list;
        this.context = context;
    }

    ...

    @Override
    public Filter getFilter() {
        return new Filter() {
            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                list = (List<E>) results.values;
                notifyDataSetChanged();
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                List<E> filteredResults = null;
                if (constraint.length() == 0) {
                    filteredResults = originalList;
                } else {
                    filteredResults = getFilteredResults(constraint.toString().toLowerCase());
                }

                FilterResults results = new FilterResults();
                results.values = filteredResults;

                return results;
            }
        };
    }

    protected List<E> getFilteredResults(String constraint) {
        List<E> results = new ArrayList<>();

        for (E item : originalList) {
            if (item.getName().toLowerCase().contains(constraint)) {
                results.add(item);
            }
        }
        return results;
    }
} 

The E here is a Generic Type, you can extend it using your class:

public class customerAdapter extends GenericRecycleAdapter<CustomerModel>

Or just change the E to the type you want (<CustomerModel> for example)

Then from searchView (the widget you can put on menu.xml):

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String text) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String text) {
        yourAdapter.getFilter().filter(text);
        return true;
    }
});

Shell script : How to cut part of a string

I pasted the contents of your example into a file named so.txt.

$ cat so.txt | awk '{ print $7 }' | cut -f2 -d"="
9
10

Explanation:

  1. cat so.txt will print the contents of the file to stdout.
  2. awk '{ print $7 }' will print the seventh column, i.e. the one containing id=n
  3. cut -f2 -d"=" will cut the output of step #2 using = as the delimiter and get the second column (-f2)

If you'd rather get id= also, then:

$ cat so.txt | awk '{ print $7 }' 
id=9
id=10

How to read one single line of csv data in Python?

You can use Pandas library to read the first few lines from the huge dataset.

import pandas as pd

data = pd.read_csv("names.csv", nrows=1)

You can mention the number of lines to be read in the nrows parameter.

Use jQuery to change value of a label

val() is more like a shortcut for attr('value'). For your usage use text() or html() instead

Find a file in python

If you are working with Python 2 you have a problem with infinite recursion on windows caused by self-referring symlinks.

This script will avoid following those. Note that this is windows-specific!

import os
from scandir import scandir
import ctypes

def is_sym_link(path):
    # http://stackoverflow.com/a/35915819
    FILE_ATTRIBUTE_REPARSE_POINT = 0x0400
    return os.path.isdir(path) and (ctypes.windll.kernel32.GetFileAttributesW(unicode(path)) & FILE_ATTRIBUTE_REPARSE_POINT)

def find(base, filenames):
    hits = []

    def find_in_dir_subdir(direc):
        content = scandir(direc)
        for entry in content:
            if entry.name in filenames:
                hits.append(os.path.join(direc, entry.name))

            elif entry.is_dir() and not is_sym_link(os.path.join(direc, entry.name)):
                try:
                    find_in_dir_subdir(os.path.join(direc, entry.name))
                except UnicodeDecodeError:
                    print "Could not resolve " + os.path.join(direc, entry.name)
                    continue

    if not os.path.exists(base):
        return
    else:
        find_in_dir_subdir(base)

    return hits

It returns a list with all paths that point to files in the filenames list. Usage:

find("C:\\", ["file1.abc", "file2.abc", "file3.abc", "file4.abc", "file5.abc"])

C# Remove object from list of objects

You can use a while loop to delete item/items matching ChunkID. Here is my suggestion:

public void DeleteChunk(int ChunkID)
{
   int i = 0;
   while (i < ChunkList.Count) 
   {
      Chunk currentChunk = ChunkList[i];
      if (currentChunk.UniqueID == ChunkID) {
         ChunkList.RemoveAt(i);
      }
      else {
        i++;
      }
   }
}

Installing Numpy on 64bit Windows 7 with Python 2.7.3

Download numpy-1.9.2+mkl-cp27-none-win32.whl from http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy .

Copy the file to C:\Python27\Scripts

Run cmd from the above location and type

pip install numpy-1.9.2+mkl-cp27-none-win32.whl

You will hopefully get the below output:

Processing c:\python27\scripts\numpy-1.9.2+mkl-cp27-none-win32.whl
Installing collected packages: numpy
Successfully installed numpy-1.9.2

Hope that works for you.

EDIT 1
Adding @oneleggedmule 's suggestion:

You can also run the following command in the cmd:

pip2.7 install numpy-1.9.2+mkl-cp27-none-win_amd64.whl

Basically, writing pip alone also works perfectly (as in the original answer). Writing the version 2.7 can also be done for the sake of clarity or specification.

Install dependencies globally and locally using package.json

All modules from package.json are installed to ./node_modules/

I couldn't find this explicitly stated but this is the package.json reference for NPM.

Apply style to parent if it has child with css

It's not possible with CSS3. There is a proposed CSS4 selector, $, to do just that, which could look like this (Selecting the li element):

ul $li ul.sub { ... }

See the list of CSS4 Selectors here.

As an alternative, with jQuery, a one-liner you could make use of would be this:

$('ul li:has(ul.sub)').addClass('has_sub');

You could then go ahead and style the li.has_sub in your CSS.

Cannot find libcrypto in Ubuntu

I solved this on 12.10 by installing libssl-dev.

sudo apt-get install libssl-dev

In-place type conversion of a NumPy array

a = np.subtract(a, 0., dtype=np.float32)

Datatables - Setting column width

If you ever need to set your datatable column's width using CSS ONLY, following css will help you :-)

HTML

<table class="table table-striped table-bordered table-hover table-checkable" id="datatable">
    <thead>
    <tr role="row" class="heading">
        <th width="2%">
            <label class="mt-checkbox mt-checkbox-single mt-checkbox-outline">
                <input type="checkbox" class="group-checkable" data-set="#sample_2 .checkboxes" />
                <span></span>
            </label>
        </th>
        <th width=""> Col 1 </th>
        <th width=""> Col 2 </th>
        <th width=""> Col 3 </th>
        <th width=""> Actions </th>
    </tr>
    <tr role="row" class="filter">
        <td> </td>
        <td><input type="text" class="form-control form-filter input-sm" name="col_1"></td>
        <td><input type="text" class="form-control form-filter input-sm" name="col_2"></td>
        <td><input type="text" class="form-control form-filter input-sm" name="col_3"></td>
        <td>
            <div class="margin-bottom-5">
                <button class="btn btn-sm btn-success filter-submit margin-bottom"><i class="fa fa-search"></i> Search</button>
            </div>
            <button class="btn btn-sm btn-default filter-cancel"><i class="fa fa-times"></i> Reset</button>
        </td>
    </tr>
    </thead>
    <tbody> </tbody> 
</table>

Using metronic admin theme and my table id is #datatable as above.

CSS

#datatable > thead > tr.heading > th:nth-child(2),
#datatable > thead > tr.heading > th:nth-child(3) { width: 120px; min-width: 120px; }

React fetch data in server before render

Responded to a similar question with a potentially simple solution to this if anyone is still after an answer, the catch is it involves the use of redux-sagas:

https://stackoverflow.com/a/38701184/978306

Or just skip straight to the article I wrote on the topic:

https://medium.com/@navgarcha7891/react-server-side-rendering-with-simple-redux-store-hydration-9f77ab66900a

Clear dropdownlist with JQuery

Just use .empty():

// snip...
}).done(function (data) {
    // Clear drop down list
    $(dropdown).empty(); // <<<<<< No more issue here
    // Fill drop down list with new data
    $(data).each(function () {
        // snip...

There's also a more concise way to build up the options:

// snip...
$(data).each(function () {
    $("<option />", {
        val: this.value,
        text: this.text
    }).appendTo(dropdown);
});

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

you are getting this error because of the server is not enabled by default i.e you don't have any runtime chosen for that is why you are getting the error so, for that you need to do the following steps to choose the runtime.

Follow The Path right-click on the project --> GoTo Properties--> Click on Targeted Runtimes-->then click on the checkbox i.e Apache tomcat or other servers which you are using --->then click on apply and then apply and close

How to sort a file in-place

Here's an approach which (ab)uses vim:

vim -c :sort -c :wq -E -s "${filename}"

The -c :sort -c :wq portion invokes commands to vim after the file opens. -E and -s are necessary so that vim executes in a "headless" mode which doesn't draw to the terminal.

This has almost no benefits over the sort -o "${filename}" "${filename}" approach except that it only takes the filename argument once.


This was useful for me to implement a formatter directive in a nanorc entry for .gitignore files. Here's what I used for that:

syntax "gitignore" "\.gitignore$"

formatter vim -c :sort -c :wq -E -s

Cell spacing in UICollectionView

If u want to tweak the spacing without touching the actual cell size, this is the solution that worked best for me. #xcode 9 #tvOS11 #iOS11 #swift

So in UICollectionViewDelegateFlowLayout, change implement the next methods, the trick is u have to use both of them, and the documentation was not really pointing me to think in that direction. :D

open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return cellSpacing
}

public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return cellSpacing
}

HTML img tag: title attribute vs. alt attribute?

The ALT attribute is for the visually impaired user that would use a screen reader. If the ALT is missing from ANY image tag, the entire url for the image will be read. If the images are for part of the design of the site, they should still have the ALT but they can be left empty so the url doesn't have to be read for every part of the site.

Ruby 2.0.0p0 IRB warning: "DL is deprecated, please use Fiddle"

The message "DL is deprecated, please use Fiddle" is not an error; it's only a warning.
Solution:
You can ignore this in 3 simple steps.
Step 1. Goto C:\RailsInstaller\Ruby2.1.0\lib\ruby\2.1.0
Step 2. Then find dl.rb and open the file with any online editors like Aptana,sublime text etc
Step 3. Comment the line 8 with '#' ie # warn "DL is deprecated, please use Fiddle" .
That's it, Thank you.

Copy entire contents of a directory to another using php

I clone entire directory by SPL Directory Iterator.

function recursiveCopy($source, $destination)
{
    if (!file_exists($destination)) {
        mkdir($destination);
    }

    $splFileInfoArr = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

    foreach ($splFileInfoArr as $fullPath => $splFileinfo) {
        //skip . ..
        if (in_array($splFileinfo->getBasename(), [".", ".."])) {
            continue;
        }
        //get relative path of source file or folder
        $path = str_replace($source, "", $splFileinfo->getPathname());

        if ($splFileinfo->isDir()) {
            mkdir($destination . "/" . $path);
        } else {
        copy($fullPath, $destination . "/" . $path);
        }
    }
}
#calling the function
recursiveCopy(__DIR__ . "/source", __DIR__ . "/destination");

show and hide divs based on radio button click

With $("div.desc").hide(); you are essentially trying to hide a div with a class name of desc. Which doesn't exist. With $("#"+test).show(); you are trying to show either a div with an id of #2 or #3. Those are illegal id's in HTML (can't start with a number), though they will work in many browsers. However, they don't exist.

I'd rename the two divs to carDiv2 and carDiv3 and then use different logic to hide or show.

if((test) == 2) { ... }

Also, use a class for your checkboxes so your binding becomes something like

$('.carCheckboxes').click(function ...

Change IPython/Jupyter notebook working directory

jupyter notebook --help-all could be of help:

--notebook-dir=<Unicode> (NotebookManager.notebook_dir)
    Default: u'/Users/me/ipynbs'
    The directory to use for notebooks.

For example:

jupyter notebook --notebook-dir=/Users/yourname/folder1/folder2/

You can of course set it in your profiles if needed, you might need to escape backslash in Windows.

Note that this will override whatever path you might have set in a jupyter_notebook_config.py file. (Where you can set a variable c.NotebookApp.notebook_dir that will be your default startup location.)

How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session

For those who have this problem with collection of enums here is how to solve it:

@Enumerated(EnumType.STRING)
@Column(name = "OPTION")
@CollectionTable(name = "MY_ENTITY_MY_OPTION")
@ElementCollection(targetClass = MyOptionEnum.class, fetch = EAGER)
Collection<MyOptionEnum> options;

Django return redirect() with parameters

Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.

Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:

/link/mybackend/?field1=value1&field2=value2&field3=value3

and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET.

So your urlconf would be:

url(r'^link/(?P<backend>\w+?)/$', my_function)

and the view would look like:

def my_function(request, backend):
   data = request.GET

and the reverse would be (after importing urllib):

return "%s?%s" % (redirect('my_function', args=(backend,)),
                  urllib.urlencode(form.cleaned_data))

Edited after comment

The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.

If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.

That said, if all you want to do is store the data, then just put it in the session:

request.session['temp_data'] = form.cleaned_data

get index of DataTable column with name

You can simply use DataColumnCollection.IndexOf

So that you can get the index of the required column by name then use it with your row:

row[dt.Columns.IndexOf("ColumnName")] = columnValue;

How to SUM parts of a column which have same text value in different column in the same row

This can be done by using SUMPRODUCT as well. Update the ranges as you see fit

=SUMPRODUCT(($A$2:$A$7=A2)*($B$2:$B$7=B2)*$C$2:$C$7)

A2:A7 = First name range

B2:B7 = Last Name Range

C2:C7 = Numbers Range

This will find all the names with the same first and last name and sum the numbers in your numbers column

close fancy box from function from within open 'fancybox'

Add $.fancybox.close() to where ever you want it to be trigged, in a function or a callback, end of an ajax call!

Woohoo.

How can one develop iPhone apps in Java?

I think we will have to wait a couple of years more to see more progress. However, there are now more frameworks and tools available:

Here a list of 5 options:

How can I see CakePHP's SQL dump in the controller?

What worked finally for me and also compatible with 2.0 is to add in my layout (or in model)

<?php echo $this->element('sql_dump');?>

It is also depending on debug variable setted into Config/core.php

JavaScript: client-side vs. server-side validation

Well, I still find some room to answer.

In addition to answers from Rob and Nathan, I would add that having client-side validations matters. When you are applying validations on your webforms you must follow these guidelines:

Client-Side

  1. Must use client-side validations in order to filter genuine requests coming from genuine users at your website.
  2. The client-side validation should be used to reduce the errors that might occure during server side processing.
  3. Client-side validation should be used to minimize the server-side round-trips so that you save bandwidth and the requests per user.

Server-Side

  1. You SHOULD NOT assume the validation successfully done at client side is 100% perfect. No matter even if it serves less than 50 users. You never know which of your user/emplyee turn into an "evil" and do some harmful activity knowing you dont have proper validations in place.
  2. Even if its perfect in terms of validating email address, phone numbers or checking some valid inputs it might contain very harmful data. Which needs to be filtered at server-side no matter if its correct or incorrect.
  3. If client-side validation is bypassed, your server-side validations comes to rescue you from any potential damage to your server-side processing. In recent times, we have already heard lot of stories of SQL Injections and other sort of techniques that might be applied in order to gain some evil benefits.

Both types of validations play important roles in their respective scope but the most strongest is the server-side. If you receive 10k users at a single point of time then you would definitely end up filtering the number of requests coming to your webserver. If you find there was a single mistake like invalid email address then they post back the form again and ask your user to correct it which will definitely eat your server resources and bandwidth. So better you apply javascript validation. If javascript is disabled then your server side validation will come to rescue and i bet only a few users might have accidentlly disable it since 99.99% of websites use javascript and its already enabled by default in all modern browsers.

How to convert a datetime to string in T-SQL

You can use the convert statement in Microsoft SQL Server to convert a date to a string. An example of the syntax used would be:

SELECT convert(varchar(20), getdate(), 120)

The above would return the current date and time in a string with the format of YYYY-MM-DD HH:MM:SS in 24 hour clock.

You can change the number at the end of the statement to one of many which will change the returned strings format. A list of these codes can be found on the MSDN in the CAST and CONVERT reference section.

CSS selector based on element text?

I know it's not exactly what you are looking for, but maybe it'll help you.

You can try use a jQuery selector :contains(), add a class and then do a normal style for a class.

Getting attribute using XPath

You can also get it by

string(//bookstore/book[1]/title/@lang)    
string(//bookstore/book[2]/title/@lang)

although if you are using XMLDOM with JavaScript you can code something like

var n1 = uXmlDoc.selectSingleNode("//bookstore/book[1]/title/@lang");

and n1.text will give you the value "eng"

Can't bind to 'dataSource' since it isn't a known property of 'table'

  • Angular Core v6.0.2,
  • Angular Material, v6.0.2,
  • Angular CLI v6.0.0 (globally v6.1.2)

I had this issue when running ng test, so to fix it, I added to my xyz.component.spec.ts file:

import { MatTableModule } from '@angular/material';

And added it to imports section in TestBed.configureTestingModule({}):

beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ ReactiveFormsModule, HttpClientModule, RouterTestingModule, MatTableModule ],
      declarations: [ BookComponent ],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
    })
    .compileComponents();
}));

Find duplicate records in MySQL

we can found the duplicates depends on more then one fields also.For those cases you can use below format.

SELECT COUNT(*), column1, column2 
FROM tablename
GROUP BY column1, column2
HAVING COUNT(*)>1;

How do I get a string format of the current date time, in python?

If you don't care about formatting and you just need some quick date, you can use this:

import time
print(time.ctime())

Filter df when values matches part of a string in pyspark

pyspark.sql.Column.contains() is only available in pyspark version 2.2 and above.

df.where(df.location.contains('google.com'))

Runtime vs. Compile time

we can classify these under different two broad groups static binding and dynamic binding. It is based on when the binding is done with the corresponding values. If the references are resolved at compile time, then it is static binding and if the references are resolved at runtime then it is dynamic binding. Static binding and dynamic binding also called as early binding and late binding. Sometimes they are also referred as static polymorphism and dynamic polymorphism.

Joseph Kulandai?.

NameError: global name is not defined

try

from sqlitedbx import SqliteDBzz

How to query MongoDB with "like"?

  • split name string by space and make array of words
  • map to iterate loop and convert string to regex of each word of name

_x000D_
_x000D_
let name = "My Name".split(" ").map(n => new RegExp(n));
console.log(name);
_x000D_
_x000D_
_x000D_

Result:

[/My/, /Name/]

Try $in Expressions, To include a regular expression in an $in query expression, you can only use JavaScript regular expression objects (i.e. /pattern/ ). For example:

db.users.find({ name: { $in: name } }); // name = [/My/, /Name/]

Where is the documentation for the values() method of Enum?

The method is implicitly defined (i.e. generated by the compiler).

From the JLS:

In addition, if E is the name of an enum type, then that type has the following implicitly declared static methods:

/**
* Returns an array containing the constants of this enum 
* type, in the order they're declared.  This method may be
* used to iterate over the constants as follows:
*
*    for(E c : E.values())
*        System.out.println(c);
*
* @return an array containing the constants of this enum 
* type, in the order they're declared
*/
public static E[] values();

/**
* Returns the enum constant of this type with the specified
* name.
* The string must match exactly an identifier used to declare
* an enum constant in this type.  (Extraneous whitespace 
* characters are not permitted.)
* 
* @return the enum constant with the specified name
* @throws IllegalArgumentException if this enum type has no
* constant with the specified name
*/
public static E valueOf(String name);

Peak memory usage of a linux/unix process

Here's a one-liner that doesn't require any external scripts or utilities and doesn't require you to start the process via another program like Valgrind or time, so you can use it for any process that's already running:

grep VmPeak /proc/$PID/status

(replace $PID with the PID of the process you're interested in)

Serialize and Deserialize Json and Json Array in Unity

Don't trim the [] and you should be fine. [] identify a JSON array which is exactly what you require to be able to iterate its elements.

Handling multiple IDs in jQuery

Yes, #id selectors combined with a multiple selector (comma) is perfectly valid in both jQuery and CSS.

However, for your example, since <script> comes before the elements, you need a document.ready handler, so it waits until the elements are in the DOM to go looking for them, like this:

<script>
  $(function() {
    $("#segement1,#segement2,#segement3").hide()
  });
</script>

<div id="segement1"></div>
<div id="segement2"></div>
<div id="segement3"></div>

HTTP requests and JSON parsing in Python

Also for pretty Json on console:

 json.dumps(response.json(), indent=2)

possible to use dumps with indent. (Please import json)

where does MySQL store database files?

For WampServer, click on its tray icon and then in the popup cascading menu select

MySQL | MySQL settings | datadir

MySQL Data Directory

jQuery $.cookie is not a function

Solve jQuery $.cookie is not a function this Problem jquery cdn update in solve this problem

 <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
 <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>

Bootstrap 4 card-deck with number of columns based on viewport

Define columns by min width based on viewport:


    /* Number of Cards by Row based on Viewport */
    @media (min-width: 576px) {
        .card-deck .card {
            min-width: 50.1%; /* 1 Column */
            margin-bottom: 12px;
        }
    }

    @media (min-width: 768px) {
        .card-deck .card {
            min-width: 33.4%;  /* 2 Columns */
        }
    }

    @media (min-width: 992px) {
        .card-deck .card {
            min-width: 25.1%;  /* 3 Columns */
        }
    }

    @media (min-width: 1200px) {
        .card-deck .card {
            min-width: 20.1%;  /* 4 Columns */
        }
    }

Enabling refreshing for specific html elements only

Try creating a javascript function which runs this:

document.getElementById("youriframeid").contentWindow.location.reload(true);

Or maybe use an HTML workaround:

<html>
<body>
<center>
      <a href="pagename.htm" target="middle">Refresh iframe</a>
      <p>
        <iframe src="pagename.htm" name="middle">
      </p>
</center>
</body>
</html>

Both might be what you're looking for...

Export MySQL database using PHP only

You can use this command it works or me 100%

exec('C:\\wamp\\bin\\mysql\\mysql5.6.17\\bin\\mysqldump.exe -uroot DatabaseName> c:\\database_backup.sql');

note:
C:\\wamp\\bin\\mysql\\mysql5.6.17\\bin\\mysqldump.exe is the path for mysqldump app , check on your pc.

-uroot is -u{UserName}

If your database is protected with password then add after -uroot this sentense -p{YourPassword}

Mapping two integers to one, in a unique and deterministic way

Here is an extension of @DoctorJ 's code to unbounded integers based on the method given by @nawfal. It can encode and decode. It works with normal arrays and numpy arrays.

#!/usr/bin/env python
from numbers import Integral    

def tuple_to_int(tup):
    """:Return: the unique non-negative integer encoding of a tuple of non-negative integers."""
    if len(tup) == 0:  # normally do if not tup, but doesn't work with np
        raise ValueError('Cannot encode empty tuple')
    if len(tup) == 1:
        x = tup[0]
        if not isinstance(x, Integral):
            raise ValueError('Can only encode integers')
        return x
    elif len(tup) == 2:
        # print("len=2")
        x, y = tuple_to_int(tup[0:1]), tuple_to_int(tup[1:2])  # Just to validate x and y

        X = 2 * x if x >= 0 else -2 * x - 1  # map x to positive integers
        Y = 2 * y if y >= 0 else -2 * y - 1  # map y to positive integers
        Z = (X * X + X + Y) if X >= Y else (X + Y * Y)  # encode

        # Map evens onto positives
        if (x >= 0 and y >= 0):
            return Z // 2
        elif (x < 0 and y >= 0 and X >= Y):
            return Z // 2
        elif (x < 0 and y < 0 and X < Y):
            return Z // 2
        # Map odds onto negative
        else:
            return (-Z - 1) // 2
    else:
        return tuple_to_int((tuple_to_int(tup[:2]),) + tuple(tup[2:]))  # ***speed up tuple(tup[2:])?***


def int_to_tuple(num, size=2):
    """:Return: the unique tuple of length `size` that encodes to `num`."""
    if not isinstance(num, Integral):
        raise ValueError('Can only encode integers (got {})'.format(num))
    if not isinstance(size, Integral) or size < 1:
        raise ValueError('Tuple is the wrong size ({})'.format(size))
    if size == 1:
        return (num,)
    elif size == 2:

        # Mapping onto positive integers
        Z = -2 * num - 1 if num < 0 else 2 * num

        # Reversing Pairing
        s = isqrt(Z)
        if Z - s * s < s:
            X, Y = Z - s * s, s
        else:
            X, Y = s, Z - s * s - s

        # Undoing mappint to positive integers
        x = (X + 1) // -2 if X % 2 else X // 2  # True if X not divisible by 2
        y = (Y + 1) // -2 if Y % 2 else Y // 2  # True if Y not divisible by 2

        return x, y

    else:
        x, y = int_to_tuple(num, 2)
        return int_to_tuple(x, size - 1) + (y,)


def isqrt(n):
    """":Return: the largest integer x for which x * x does not exceed n."""
    # Newton's method, via http://stackoverflow.com/a/15391420
    x = n
    y = (x + 1) // 2
    while y < x:
        x = y
        y = (x + n // x) // 2
    return x

What is Java String interning?

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern()

Basically doing String.intern() on a series of strings will ensure that all strings having same contents share same memory. So if you have list of names where 'john' appears 1000 times, by interning you ensure only one 'john' is actually allocated memory.

This can be useful to reduce memory requirements of your program. But be aware that the cache is maintained by JVM in permanent memory pool which is usually limited in size compared to heap so you should not use intern if you don't have too many duplicate values.


More on memory constraints of using intern()

On one hand, it is true that you can remove String duplicates by internalizing them. The problem is that the internalized strings go to the Permanent Generation, which is an area of the JVM that is reserved for non-user objects, like Classes, Methods and other internal JVM objects. The size of this area is limited, and is usually much smaller than the heap. Calling intern() on a String has the effect of moving it out from the heap into the permanent generation, and you risk running out of PermGen space.

-- From: http://www.codeinstructions.com/2009/01/busting-javalangstringintern-myths.html


From JDK 7 (I mean in HotSpot), something has changed.

In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences.

-- From Java SE 7 Features and Enhancements

Update: Interned strings are stored in main heap from Java 7 onwards. http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html#jdk7changes

Losing scope when using ng-include

I've figured out how to work around this issue without mixing parent and sub scope data. Set a ng-if on the the ng-include element and set it to a scope variable. For example :

<div ng-include="{{ template }}" ng-if="show"/>

In your controller, when you have set all the data you need in your sub scope, then set show to true. The ng-include will copy at this moment the data set in your scope and set it in your sub scope.

The rule of thumb is to reduce scope data deeper the scope are, else you have this situation.

Max

Plot two histograms on single chart with matplotlib

Plotting two overlapping histograms (or more) can lead to a rather cluttered plot. I find that using step histograms (aka hollow histograms) improves the readability quite a bit. The only downside is that in matplotlib the default legend for a step histogram is not properly formatted, so it can be edited like in the following example:

import numpy as np                   # v 1.19.2
import matplotlib.pyplot as plt      # v 3.3.2
from matplotlib.lines import Line2D

rng = np.random.default_rng(seed=123)

# Create two normally distributed random variables of different sizes
# and with different shapes
data1 = rng.normal(loc=30, scale=10, size=500)
data2 = rng.normal(loc=50, scale=10, size=1000)

# Create figure with 'step' type of histogram to improve plot readability
fig, ax = plt.subplots(figsize=(9,5))
ax.hist([data1, data2], bins=15, histtype='step', linewidth=2,
        alpha=0.7, label=['data1','data2'])

# Edit legend to get lines as legend keys instead of the default polygons
# and sort the legend entries in alphanumeric order
handles, labels = ax.get_legend_handles_labels()
leg_entries = {}
for h, label in zip(handles, labels):
    leg_entries[label] = Line2D([0], [0], color=h.get_facecolor()[:-1],
                                alpha=h.get_alpha(), lw=h.get_linewidth())
labels_sorted, lines = zip(*sorted(leg_entries.items()))
ax.legend(lines, labels_sorted, frameon=False)

# Remove spines
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

# Add annotations
plt.ylabel('Frequency', labelpad=15)
plt.title('Matplotlib step histogram', fontsize=14, pad=20)
plt.show()

step_hist

As you can see, the result looks quite clean. This is especially useful when overlapping even more than two histograms. Depending on how the variables are distributed, this can work for up to around 5 overlapping distributions. More than that would require the use of another type of plot, such as one of those presented here.

Trying to get PyCharm to work, keep getting "No Python interpreter selected"

Even I got the same issue and my mistake was that I didn't download python MSI file. You will get it here: https://www.python.org/downloads/

Once you download the msi, run the setup and that will solve the problem. After that you can go to File->Settings->Project Settings->Project Interpreter->Python Interpreters

and select the python.exe file. (This file will be available at c:\Python34) Select the python.exe file. That's it.

Laravel: Get base url

you can get it from Request, at laravel 5

request()->getSchemeAndHttpHost();

How to decode encrypted wordpress admin password?

MD5 encrypting is possible, but decrypting is still unknown (to me). However, there are many ways to compare these things.

  1. Using compare methods like so:

    <?php
      $db_pass = $P$BX5675uhhghfhgfhfhfgftut/0;
      $my_pass = "mypass";
      if ($db_pass === md5($my_pass)) {
        // password is matched
      } else {
        // password didn't match
      }
    
  2. Only for WordPress users. If you have access to your PHPMyAdmin, focus you have because you paste that hashing here: $P$BX5675uhhghfhgfhfhfgftut/0, WordPress user_pass is not only MD5 format it also uses utf8_mb4_cli charset so what to do?

    That's why I use another Approach if I forget my WordPress password I use

    I install other WordPress with new password :P, and I then go to PHPMyAdmin and copy that hashing from the database and paste that hashing to my current PHPMyAdmin password ( which I forget )

    EASY is use this :

    1. password = "ARJUNsingh@123"
    2. password_hasing = " $P$BDSdKx2nglM.5UErwjQGeVtVWvjEvD1 "
    3. Replace your $P$BX5675uhhghfhgfhfhfgftut/0 with my $P$BDSdKx2nglM.5UErwjQGeVtVWvjEvD1

I USE THIS APPROACH FOR MY SELF WHEN I DESIGN THEMES AND PLUGINS

WORDPRESS USE THIS

https://developer.wordpress.org/reference/functions/wp_hash_password/

How to call code behind server method from a client side JavaScript function?

Try creating a new service and calling it. The processing can be done there, and returned back.

http://code.msdn.microsoft.com/windowsazure/WCF-Azure-AJAX-Calculator-4cf3099e

function makeCall(operation){
    var n1 = document.getElementById("num1").value;
    var n2 = document.getElementById("num2").value;
if(n1 && n2){

        // Instantiate a service proxy
        var proxy = new Service();

        // Call correct operation on vf cproxy       
        switch(operation){

            case "gridOne":
                proxy.Calculate(AjaxService.Operation.getWeather, n1, n2,
 onSuccess, onFail, null);

****HTML CODE****
<p>Major City: <input type="text" id="num1" onclick="return num1_onclick()"
/></p>
<p>Country: <input type="text" id="num2" onclick="return num2_onclick()"
/></p> 
<input id="btnDivide" type="button" onclick="return makeCall('gridOne');" 

Recommended SQL database design for tags or tagging

If you are using a database that supports map-reduce, like couchdb, storing tags in a plain text field or list field is indeed the best way. Example:

tagcloud: {
  map: function(doc){ 
    for(tag in doc.tags){ 
      emit(doc.tags[tag],1) 
    }
  }
  reduce: function(keys,values){
    return values.length
  }
}

Running this with group=true will group the results by tag name, and even return a count of the number of times that tag was encountered. It's very similar to counting the occurrences of a word in text.

Using Python's os.path, how do I go up one directory?

from os.path import dirname, realpath, join
join(dirname(realpath(dirname(__file__))), 'templates')

Update:

If you happen to "copy" settings.py through symlinking, @forivall's answer is better:

~user/
    project1/  
        mysite/
            settings.py
        templates/
            wrong.html

    project2/
        mysite/
            settings.py -> ~user/project1/settings.py
        templates/
            right.html

The method above will 'see' wrong.html while @forivall's method will see right.html

In the absense of symlinks the two answers are identical.

How to change symbol for decimal point in double.ToString()?

You can change the decimal separator by changing the culture used to display the number. Beware however that this will change everything else about the number (eg. grouping separator, grouping sizes, number of decimal places). From your question, it looks like you are defaulting to a culture that uses a comma as a decimal separator.

To change just the decimal separator without changing the culture, you can modify the NumberDecimalSeparator property of the current culture's NumberFormatInfo.

Thread.CurrentCulture.NumberFormat.NumberDecimalSeparator = ".";

This will modify the current culture of the thread. All output will now be altered, meaning that you can just use value.ToString() to output the format you want, without worrying about changing the culture each time you output a number.

(Note that a neutral culture cannot have its decimal separator changed.)

Bootstrap col-md-offset-* not working

Kindly use offset-md-4 instead of col-md-offset-4 in bootstrap 4. It's little changes adopted in bootstrap 4.

For more info

Can a unit test project load the target application's app.config file?

If you have a solution which contains for example Web Application and Test Project, you probably want that Test Project uses Web Application's web.config.

One way to solve it is to copy web.config to test project and rename it as app.config.

Another and better solution is to modify build chain and make it to make automatic copy of web.config to test projects output directory. To do that, right click Test Application and select properties. Now you should see project properties. Click "Build Events" and then click "Edit Post-build..." button. Write following line to there:

copy "$(SolutionDir)\WebApplication1\web.config" "$(ProjectDir)$(OutDir)$(TargetFileName).config"

And click OK. (Note you most probably need to change WebApplication1 as you project name which you want to test). If you have wrong path to web.config then copy fails and you will notice it during unsuccessful build.

Edit:

To Copy from the current Project to the Test Project:

copy "$(ProjectDir)bin\WebProject.dll.config" "$(SolutionDir)WebProject.Tests\bin\Debug\App.Config"

Bootstrap: add margin/padding space between columns

You may use the padding and margin shorthand Bootstrap 4 classes as follows:

For extra small devices i.e. xs

{property}{sides}-{size}

For other devices/viewports (small, medium, large and extra large)

{property}{sides}-{breakpoint}-{size}

Where:

property = m for margin and p for padding

Following are sides shorthand meanings:

l = defines the left-margin or left-padding
r = defines the right-margin or right-padding
t = defines the top-margin or top-padding
b = defines the bottom-margin or right-padding
x = For setting left and right padding and margins by the single call
y = For setting top and bottom margins
blank = margin and padding for all sides

The breakpoint = sm, md, lg, and xl.

Combining all the above, the left padding complete code can be (for example):

For left padding in extra small devices

pl-2

or for medium to extra large

pl-md-2