Programs & Examples On #Hindi

Hindi is the most spoken language of India, the world's second-most populated country. The script which is used to write Hindi is called "Devanagari".

Flutter - The method was called on null

As stated in the above answers, it's always a good practice to initialize the variables, but if you have something which you don't know what value should it takes, and you want to leave it uninitialized so you have to make sure that you are updating it before using it.

For example: Assume we have double _bmi; and you don't know what value should it takes, so you can leave it as it is, but before using it, you have to update its value first like calling a function that calculating BMI like follows:

String calculateBMI (){
_bmi = weight / pow( height/100, 2);
return _bmi.toStringAsFixed(1);}

or whatever, what I mean is, you can leave the variable as it is, but before using it make sure you have initialized it using whatever the method you are using.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

Adding Google Translate to a web site

{{-- Google Language Translator  START --}}
<style>
.google-translate {
    display: inline-block;
    vertical-align: top;
    padding-top: 15px;
}

.goog-logo-link {
    display: none !important;
}

.goog-te-gadget {
    color: transparent !important;
}

#google_translate_element {
    display: none;
}

.goog-te-banner-frame.skiptranslate {
    display: none !important;
}

body {
    top: 0px !important;
}

</style>

<script src="{{asset('js/translate-google.js')}}"></script>



<script type="text/javascript">
function googleTranslateElementInit2(){
    new google.translate.TranslateElement({
                    pageLanguage:'en',
                    includedLanguages: 'en,es',
        // https://ctrlq.org/code/19899-google-translate-languages
        // includedLanguages: 'en,it,la,fr',
        // layout:     google.translate.TranslateElement.InlineLayout.SIMPLE,
        autoDisplay:true
    },'google_translate_element2');
    var a = document.querySelector("#google_translate_element select");
    // console.log(a);

    if(a){
        a.selectedIndex=1;
        a.dispatchEvent(new Event('change'));
    }
}
</script>

<ul class="navbar-nav my-lg-0 m-r-10">
<li>
    <div class="google-translate">
        <div id="google_translate_element2"></div>
    </div>
</li>

{{-- Google Language Translator ENDS --}}

// translate-google.js
(function () {
var gtConstEvalStartTime = new Date();

function d(b) {
    var a = document.getElementsByTagName("head")[0];
    a || (a = document.body.parentNode.appendChild(document.createElement("head")));
    a.appendChild(b)
}

function _loadJs(b) {
    // console.log(b);
    var a = document.createElement("script");
    a.type = "text/javascript";
    a.charset = "UTF-8";
    a.src = b;
    d(a)
}

function _loadCss(b) {
    var a = document.createElement("link");
    a.type = "text/css";
    a.rel = "stylesheet";
    a.charset = "UTF-8";
    a.href = b;
    d(a)
}

function _isNS(b) {
    b = b.split(".");
    for (var a = window, c = 0; c < b.length; ++c)
        if (!(a = a[b[c]])) return !1;
    return !0
}

function _setupNS(b) {
    b = b.split(".");
    for (var a = window, c = 0; c < b.length; ++c) a.hasOwnProperty ? a.hasOwnProperty(b[c]) ? a = a[b[c]] : a = a[b[c]] = {} : a = a[b[c]] || (a[b[c]] = {});
    return a
}
window.addEventListener && "undefined" == typeof document.readyState && window.addEventListener("DOMContentLoaded", function () {
    document.readyState = "complete"
}, !1);
if (_isNS('google.translate.Element')) {
    return
}(function () {
    var c = _setupNS('google.translate._const');
    c._cest = gtConstEvalStartTime;
    gtConstEvalStartTime = undefined;
    c._cl = 'en';
    c._cuc = 'googleTranslateElementInit2';
    c._cac = '';
    c._cam = '';
    c._ctkk = eval('((function(){var a\x3d3002255536;var b\x3d-2533142796;return 425386+\x27.\x27+(a+b)})())');
    var h = 'translate.googleapis.com';
    var s = (true ? 'https' : window.location.protocol == 'https:' ? 'https' : 'http') + '://';
    var b = s + h;
    c._pah = h;
    c._pas = s;
    c._pbi = b + '/translate_static/img/te_bk.gif';
    c._pci = b + '/translate_static/img/te_ctrl3.gif';
    c._pli = b + '/translate_static/img/loading.gif';
    c._plla = h + '/translate_a/l';
    c._pmi = b + '/translate_static/img/mini_google.png';
    c._ps = b + '/translate_static/css/translateelement.css';
    c._puh = 'translate.google.com';
    _loadCss(c._ps);
    _loadJs(b + '/translate_static/js/element/main.js');
})();
})();

JavaScript alert not working in Android WebView

The following code will work:

private WebView mWebView;
final Activity activity = this;

// private Button b;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setDomStorageEnabled(true);
    mWebView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
            activity.setProgress(progress * 1000);
        }
    });

    mWebView.loadUrl("file:///android_asset/raw/NewFile1.html");
}

Detect Browser Language in PHP

All of the above with fallback to 'en':

$lang = substr(explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE'])[0],0,2)?:'en';

...or with default language fallback and known language array:

function lang( $l = ['en'], $u ){
    return $l[
        array_keys(
            $l,
            substr(
                explode(
                    ',',
                    $u ?: $_SERVER['HTTP_ACCEPT_LANGUAGE']
                )[0],
                0,
                2
            )
        )[0]
    ] ?: $l[0];
}

One Line:

function lang($l=['en'],$u){return $l[array_keys($l,substr(explode(',',$u?:$_SERVER['HTTP_ACCEPT_LANGUAGE'])[0],0,2))[0]]?:$l[0];}

Examples:

// first known lang is always default
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'en-us';
lang(['de']); // 'de'
lang(['de','en']); // 'en'

// manual set accept-language
lang(['de'],'en-us'); // 'de'
lang(['de'],'de-de, en-us'); // 'de'
lang(['en','fr'],'de-de, en-us'); // 'en'
lang(['en','fr'],'fr-fr, en-us'); // 'fr'
lang(['de','en'],'fr-fr, en-us'); // 'de'

Storing and displaying unicode string (??????) using PHP and MySQL

For Those who are facing difficulty just got to php admin and change collation to utf8_general_ci Select Table go to Operations>> table options>> collations should be there

Difference between numpy.array shape (R, 1) and (R,)

The difference between (R,) and (1,R) is literally the number of indices that you need to use. ones((1,R)) is a 2-D array that happens to have only one row. ones(R) is a vector. Generally if it doesn't make sense for the variable to have more than one row/column, you should be using a vector, not a matrix with a singleton dimension.

For your specific case, there are a couple of options:

1) Just make the second argument a vector. The following works fine:

    np.dot(M[:,0], np.ones(R))

2) If you want matlab like matrix operations, use the class matrix instead of ndarray. All matricies are forced into being 2-D arrays, and operator * does matrix multiplication instead of element-wise (so you don't need dot). In my experience, this is more trouble that it is worth, but it may be nice if you are used to matlab.

How to unsubscribe to a broadcast event in angularJS. How to remove function registered via $on

One way is to simply destroy the listener once you are done with it.

var removeListener = $scope.$on('navBarRight-ready', function () {
        $rootScope.$broadcast('workerProfile-display', $scope.worker)
        removeListener(); //destroy the listener
    })

Creating a custom JButton in Java

When I was first learning Java we had to make Yahtzee and I thought it would be cool to create custom Swing components and containers instead of just drawing everything on one JPanel. The benefit of extending Swing components, of course, is to have the ability to add support for keyboard shortcuts and other accessibility features that you can't do just by having a paint() method print a pretty picture. It may not be done the best way however, but it may be a good starting point for you.

Edit 8/6 - If it wasn't apparent from the images, each Die is a button you can click. This will move it to the DiceContainer below. Looking at the source code you can see that each Die button is drawn dynamically, based on its value.

alt text
alt text
alt text

Here are the basic steps:

  1. Create a class that extends JComponent
  2. Call parent constructor super() in your constructors
  3. Make sure you class implements MouseListener
  4. Put this in the constructor:

    enableInputMethods(true);   
    addMouseListener(this);
    
  5. Override these methods:

    public Dimension getPreferredSize()  
    public Dimension getMinimumSize()  
    public Dimension getMaximumSize()
    
  6. Override this method:

    public void paintComponent(Graphics g)
    

The amount of space you have to work with when drawing your button is defined by getPreferredSize(), assuming getMinimumSize() and getMaximumSize() return the same value. I haven't experimented too much with this but, depending on the layout you use for your GUI your button could look completely different.

And finally, the source code. In case I missed anything.

Creating csv file with php

Just in case if someone is wondering to save the CSV file to a specific path for email attachments. Then it can be done as follows

I know I have added a lot of comments just for newbies :)

I have added an example so that you can summarize well.

$activeUsers = /** Query to get the active users */

/** Following is the Variable to store the Users data as 
    CSV string with newline character delimiter, 

    its good idea of check the delimiter based on operating system */

$userCSVData = "Name,Email,CreatedAt\n";

/** Looping the users and appending to my earlier csv data variable */
foreach ( $activeUsers as $user ) {
    $userCSVData .= $user->name. "," . $user->email. "," . $user->created_at."\n";
}
/** Here you can use with H:i:s too. But I really dont care of my old file  */
$todayDate  = date('Y-m-d');
/** Create Filname and Path to Store */
$fileName   = 'Active Users '.$todayDate.'.csv';
$filePath   = public_path('uploads/'.$fileName); //I am using laravel helper, in case if your not using laravel then just add absolute or relative path as per your requirements and path to store the file

/** Just in case if I run the script multiple time 
    I want to remove the old file and add new file.

    And before deleting the file from the location I am making sure it exists */
if(file_exists($filePath)){
    unlink($filePath);
}
$fp = fopen($filePath, 'w+');
fwrite($fp, $userCSVData); /** Once the data is written it will be saved in the path given */
fclose($fp);

/** Now you can send email with attachments from the $filePath */

NOTE: The following is a very bad idea to increase the memory_limit and time limit, but I have only added to make sure if anyone faces the problem of connection time out or any other. Make sure to find out some alternative before sticking to it.

You have to add the following at the start of the above script.

ini_set("memory_limit", "10056M");
set_time_limit(0);
ini_set('mysql.connect_timeout', '0');
ini_set('max_execution_time', '0');

How to call VS Code Editor from terminal / command line

In linux if you use code . it will open VS Code in the folder the terminal was in. Using code . Filename.cs it will open in folder and open said file.

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

@Column(name ="LEAD_ID")
private int leadId; 

Change to

@Column(name ="LEAD_ID")
private Integer leadId; 

parsing a tab-separated file in Python

I don't think any of the current answers really do what you said you want. (Correction: I now see that @Gareth Latty / @Lattyware has incorporated my answer into his own as an "Edit" near the end.)

Anyway, here's my take:

Say these are the tab-separated values in your input file:

1   2   3   4   5
6   7   8   9   10
11  12  13  14  15
16  17  18  19  20

then this:

with open("tab-separated-values.txt") as inp:
    print( list(zip(*(line.strip().split('\t') for line in inp))) )

would produce the following:

[('1', '6', '11', '16'), 
 ('2', '7', '12', '17'), 
 ('3', '8', '13', '18'), 
 ('4', '9', '14', '19'), 
 ('5', '10', '15', '20')]

As you can see, it put the k-th element of each row into the k-th array.

Expected corresponding JSX closing tag for input Reactjs

You need to close the input element with a /> at the end.

<input id="icon_prefix" type="text" class="validate" />

How to make a local variable (inside a function) global

Simply declare your variable outside any function:

globalValue = 1

def f(x):
    print(globalValue + x)

If you need to assign to the global from within the function, use the global statement:

def f(x):
    global globalValue
    print(globalValue + x)
    globalValue += 1

Shell script "for" loop syntax

If the seq command available on your system:

for i in `seq 2 $max`
do
  echo "output: $i"
done

If not, then use poor man's seq with perl:

seq=`perl -e "\$,=' ';print 2..$max"`
for i in $seq
do
  echo "output: $i"
done

Watch those quote marks.

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 2

Please make sure you have downloaded the sqldump fully, this problem is very common when we try to import half/incomplete downloaded sqldump. Please check size of your sqldump file.

Accessing JSON object keys having spaces

The way to do this is via the bracket notation.

_x000D_
_x000D_
var test = {_x000D_
    "id": "109",_x000D_
    "No. of interfaces": "4"_x000D_
}_x000D_
alert(test["No. of interfaces"]);
_x000D_
_x000D_
_x000D_

For more info read out here:

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

Try change update="insTable:display" to update="display". I believe you cannot prefix the id with the form ID like that.

How do I use the conditional operator (? :) in Ruby?

Easiest way:

param_a = 1
param_b = 2

result = param_a === param_b ? 'Same!' : 'Not same!'

since param_a is not equal to param_b then the result's value will be Not same!

DataRow: Select cell value by a given column name

for (int i=0;i < Table.Rows.Count;i++)
{
      Var YourValue = Table.Rows[i]["ColumnName"];
}

How is a CSS "display: table-column" supposed to work?

The "table-column" display type means it acts like the <col> tag in HTML - i.e. an invisible element whose width* governs the width of the corresponding physical column of the enclosing table.

See the W3C standard for more information about the CSS table model.

* And a few other properties like borders, backgrounds.

Executing <script> injected by innerHTML after AJAX call

I used this code, it is working fine

var arr = MyDiv.getElementsByTagName('script')
for (var n = 0; n < arr.length; n++)
    eval(arr[n].innerHTML)//run script inside div

fetch in git doesn't get all branches

I had a similar problem, however in my case I could pull/push to the remote branch but git status didn't show the local branch state w.r.t the remote ones.

Also, in my case git config --get remote.origin.fetch didn't return anything

The problem is that there was a typo in the .git/config file in the fetch line of the respective remote block. Probably something I added by mistake previously (sometimes I directly look at this file, or even edit it)

So, check if your remote entry in the .git/config file is correct, e.g.:

[remote "origin"]
    url = https://[server]/[user or organization]/[repo].git
    fetch = +refs/heads/*:refs/remotes/origin/*

XMLHttpRequest module not defined/found

XMLHttpRequest is a built-in object in web browsers.

It is not distributed with Node; you have to install it separately,

  1. Install it with npm,

    npm install xmlhttprequest
    
  2. Now you can require it in your code.

    var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
    var xhr = new XMLHttpRequest();
    

That said, the http module is the built-in tool for making HTTP requests from Node.

Axios is a library for making HTTP requests which is available for Node and browsers that is very popular these days.

Socket transport "ssl" in PHP not enabled

Ran into the same problem on Laravel 4 trying to send e-mail using SSL encryption.

Having WAMPServer 2.2 on Windows 7 64bit I only enabled php_openssl in the php.ini, restarted WAMPServer and worked flawlessly.

Did following:

  • Click WampServer -> PHP -> PHP extensions -> php_openssl
  • Restart WampServer

Using PowerShell to write a file in UTF-8 without the BOM

Could use below to get UTF8 without BOM

$MyFile | Out-File -Encoding ASCII

How do I launch the Android emulator from the command line?

Starting emulator from command line with dns help

Emulator program location : /Users/{{UserName}}/Library/Android/sdk/tools

  1. Check existing avd :- emulator -list-avds

  2. Start emulator with dns set /Users/{{UserName}}/Library/Android/sdk/tools/emulator -avd Pixel_API_26 -dns-server 8.8.8.8

How to use regex in XPath "contains" function

In Robins's answer ends-with is not supported in xpath 1.0 too.. Only starts-with is supported... So if your condition is not very specific..You can Use like this which worked for me

//*[starts-with(@id,'sometext') and contains(@name,'_text')]`\

Restore a postgres backup file using the command line?

try this:

psql -U <username> -d <dbname> -f <filename>.sql

Restore DB psql from .sql file

Change Background color (css property) using Jquery

$("#bchange").click(function() {
    $("body, this").css("background-color","yellow");
});

How to simulate a click by using x,y coordinates in JavaScript?

it doenst work for me but it prints the correct element to the console

this is the code:

function click(x, y)
{
    var ev = new MouseEvent('click', {
        'view': window,
        'bubbles': true,
        'cancelable': true,
        'screenX': x,
        'screenY': y
    });

    var el = document.elementFromPoint(x, y);
    console.log(el); //print element to console
    el.dispatchEvent(ev);
}
click(400, 400);

Get folder up one level

You could do either:

dirname(__DIR__);

Or:

__DIR__ . '/..';

...but in a web server environment you will probably find that you are already working from current file's working directory, so you can probably just use:

'../'

...to reference the directory above. You can replace __DIR__ with dirname(__FILE__) before PHP 5.3.0.

You should also be aware what __DIR__ and __FILE__ refers to:

The full path and filename of the file. If used inside an include, the name of the included file is returned.

So it may not always point to where you want it to.

How to get element by innerText

_x000D_
_x000D_
function findByTextContent(needle, haystack, precise) {_x000D_
  // needle: String, the string to be found within the elements._x000D_
  // haystack: String, a selector to be passed to document.querySelectorAll(),_x000D_
  //           NodeList, Array - to be iterated over within the function:_x000D_
  // precise: Boolean, true - searches for that precise string, surrounded by_x000D_
  //                          word-breaks,_x000D_
  //                   false - searches for the string occurring anywhere_x000D_
  var elems;_x000D_
_x000D_
  // no haystack we quit here, to avoid having to search_x000D_
  // the entire document:_x000D_
  if (!haystack) {_x000D_
    return false;_x000D_
  }_x000D_
  // if haystack is a string, we pass it to document.querySelectorAll(),_x000D_
  // and turn the results into an Array:_x000D_
  else if ('string' == typeof haystack) {_x000D_
    elems = [].slice.call(document.querySelectorAll(haystack), 0);_x000D_
  }_x000D_
  // if haystack has a length property, we convert it to an Array_x000D_
  // (if it's already an array, this is pointless, but not harmful):_x000D_
  else if (haystack.length) {_x000D_
    elems = [].slice.call(haystack, 0);_x000D_
  }_x000D_
_x000D_
  // work out whether we're looking at innerText (IE), or textContent _x000D_
  // (in most other browsers)_x000D_
  var textProp = 'textContent' in document ? 'textContent' : 'innerText',_x000D_
    // creating a regex depending on whether we want a precise match, or not:_x000D_
    reg = precise === true ? new RegExp('\\b' + needle + '\\b') : new RegExp(needle),_x000D_
    // iterating over the elems array:_x000D_
    found = elems.filter(function(el) {_x000D_
      // returning the elements in which the text is, or includes,_x000D_
      // the needle to be found:_x000D_
      return reg.test(el[textProp]);_x000D_
    });_x000D_
  return found.length ? found : false;;_x000D_
}_x000D_
_x000D_
_x000D_
findByTextContent('link', document.querySelectorAll('li'), false).forEach(function(elem) {_x000D_
  elem.style.fontSize = '2em';_x000D_
});_x000D_
_x000D_
findByTextContent('link3', 'a').forEach(function(elem) {_x000D_
  elem.style.color = '#f90';_x000D_
});
_x000D_
<ul>_x000D_
  <li><a href="#">link1</a>_x000D_
  </li>_x000D_
  <li><a href="#">link2</a>_x000D_
  </li>_x000D_
  <li><a href="#">link3</a>_x000D_
  </li>_x000D_
  <li><a href="#">link4</a>_x000D_
  </li>_x000D_
  <li><a href="#">link5</a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Of course, a somewhat simpler way still is:

_x000D_
_x000D_
var textProp = 'textContent' in document ? 'textContent' : 'innerText';_x000D_
_x000D_
// directly converting the found 'a' elements into an Array,_x000D_
// then iterating over that array with Array.prototype.forEach():_x000D_
[].slice.call(document.querySelectorAll('a'), 0).forEach(function(aEl) {_x000D_
  // if the text of the aEl Node contains the text 'link1':_x000D_
  if (aEl[textProp].indexOf('link1') > -1) {_x000D_
    // we update its style:_x000D_
    aEl.style.fontSize = '2em';_x000D_
    aEl.style.color = '#f90';_x000D_
  }_x000D_
});
_x000D_
<ul>_x000D_
  <li><a href="#">link1</a>_x000D_
  </li>_x000D_
  <li><a href="#">link2</a>_x000D_
  </li>_x000D_
  <li><a href="#">link3</a>_x000D_
  </li>_x000D_
  <li><a href="#">link4</a>_x000D_
  </li>_x000D_
  <li><a href="#">link5</a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

References:

Combine multiple Collections into a single logical Collection?

You could create a new List and addAll() of your other Lists to it. Then return an unmodifiable list with Collections.unmodifiableList().

What is "runtime"?

If my understanding from reading the above answers is correct, Runtime is basically 'background processes' such as garbage collection, memory-allocation, basically any processes that are invoked indirectly, by the libraries / frameworks that your code is written in, and specifically those processes that occur after compilation, while the application is running.

Underline text in UIlabel

Based on Kovpas & Damien Praca's Answers, here is an implementation of UILabelUnderligned which also support textAlignemnt.

#import <UIKit/UIKit.h>

@interface UILabelUnderlined : UILabel

@end

and the implementation:

#import "UILabelUnderlined.h"

@implementation DKUILabel

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)drawRect:(CGRect)rect {

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    const CGFloat* colors = CGColorGetComponents(self.textColor.CGColor);

    CGContextSetRGBStrokeColor(ctx, colors[0], colors[1], colors[2], 1.0); // RGBA

    CGContextSetLineWidth(ctx, 1.0f);

    CGSize textSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(200, 9999)];

    // handle textAlignement

    int alignementXOffset = 0;

    switch (self.textAlignment) {
        case UITextAlignmentLeft:
            break;
        case UITextAlignmentCenter:
            alignementXOffset = (self.frame.size.width - textSize.width)/2;
            break;
        case UITextAlignmentRight:
            alignementXOffset = self.frame.size.width - textSize.width;
            break;
    }

    CGContextMoveToPoint(ctx, alignementXOffset, self.bounds.size.height - 1);
    CGContextAddLineToPoint(ctx, alignementXOffset+textSize.width, self.bounds.size.height - 1);

    CGContextStrokePath(ctx);

    [super drawRect:rect];  
}


@end

How to determine if a decimal/double is an integer?

If upper and lower bound of Int32 matters:

public bool IsInt32(double value)
{
    return  value >= int.MinValue && value <= int.MaxValue && value == (int)value;
}

Cannot uninstall angular-cli

The following approach worked for me:

npm uninstall -g @angular/cli

and

npm cache verify

How to use awk sort by column 3

awk -F "," '{print $0}' user.csv | sort -nk3 -t ','

This should work

error LNK2001: unresolved external symbol (C++)

Sounds like you are using Microsoft Visual C++. If that is the case, then the most possibility is that you don't compile your two.cpp with one.cpp (one.cpp is the implementation for one.h).

If you are from command line (cmd.exe), then try this first: cl -o two.exe one.cpp two.cpp

If you are from IDE, right click on the project name from Solution Explore. Then choose Add, Existing Item.... Add one.cpp into your project.

Write values in app.config file

As others mentioned, you can do this with ConfigurationManager.AppSettings.Settings. But: Using Settings[key] = value will not work if the key doesn't exist.
Using Settings.Add(key, value), if the key already exists, it will join the new value to its value(s) separated by a comma, something like <add key="myKey" value="value1, value2, value3" />

To avoid these unexpected results, you have to handle two scenario's

  • If entry with the given key exists? then update its value
  • if entry with the given key doesn't exist? then create new entry(key,value)

Code

public static void Set(string key, string value)
{
    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    var entry = config.AppSettings.Settings[key];
    if (entry == null)
        config.AppSettings.Settings.Add(key, value);
    else
        config.AppSettings.Settings[key].Value = value;

    config.Save(ConfigurationSaveMode.Modified);
}

For more info about the check entry == null, check this post.
Hope this will help someone.

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

Use BigDecimal.valueOf(double d) instead of new BigDecimal(double d). The last one has precision errors by float and double.

How to use support FileProvider for sharing content to other apps?

Since as Phil says in his comment on the original question, this is unique and there is no other info on SO on in google, I thought I should also share my results:

In my app FileProvider worked out of the box to share files using the share intent. There was no special configuration or code necessary, beyond that to setup the FileProvider. In my manifest.xml I placed:

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.my.apps.package.files"
        android:exported="false"
        android:grantUriPermissions="true" >
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/my_paths" />
    </provider>

In my_paths.xml I have:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="files" path="." />
</paths>

In my code I have:

    Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.setType("application/xml");

    Uri uri = FileProvider.getUriForFile(this, "com.my.apps.package.files", fileToShare);
    shareIntent.putExtra(Intent.EXTRA_STREAM, uri);

    startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share_file)));

And I am able to share my files store in my apps private storage with apps such as Gmail and google drive without any trouble.

Get property value from string using reflection

How about something like this:

public static Object GetPropValue(this Object obj, String name) {
    foreach (String part in name.Split('.')) {
        if (obj == null) { return null; }

        Type type = obj.GetType();
        PropertyInfo info = type.GetProperty(part);
        if (info == null) { return null; }

        obj = info.GetValue(obj, null);
    }
    return obj;
}

public static T GetPropValue<T>(this Object obj, String name) {
    Object retval = GetPropValue(obj, name);
    if (retval == null) { return default(T); }

    // throws InvalidCastException if types are incompatible
    return (T) retval;
}

This will allow you to descend into properties using a single string, like this:

DateTime now = DateTime.Now;
int min = GetPropValue<int>(now, "TimeOfDay.Minutes");
int hrs = now.GetPropValue<int>("TimeOfDay.Hours");

You can either use these methods as static methods or extensions.

How to select date from datetime column?

You can use MySQL's DATE() function:

WHERE DATE(datetime) = '2009-10-20'

You could also try this:

WHERE datetime LIKE '2009-10-20%'

See this answer for info on the performance implications of using LIKE.

What's the best way to loop through a set of elements in JavaScript?

Here's a nice form of a loop I often use. You create the iterated variable from the for statement and you don't need to check the length property, which can be expensive specially when iterating through a NodeList. However, you must be careful, you can't use it if any of the values in array could be "falsy". In practice, I only use it when iterating over an array of objects that does not contain nulls (like a NodeList). But I love its syntactic sugar.

var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}];

for (var i=0, item; item = list[i]; i++) {
  // Look no need to do list[i] in the body of the loop
  console.log("Looping: index ", i, "item" + item);
}

Note that this can also be used to loop backwards (as long as your list doesn't have a ['-1'] property)

var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}];

for (var i = list.length - 1, item; item = list[i]; i--) {
  console.log("Looping: index ", i, "item", item);
}

ES6 Update

for...of gives you the name but not the index, available since ES6

for (let item of list) {
    console.log("Looping: index ", "Sorry!!!", "item" + item);
}

Get current date in DD-Mon-YYY format in JavaScript/Jquery

Can be done with toLocaleDateString

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

_x000D_
_x000D_
<script>_x000D_
const date = new Date();_x000D_
const formattedDate = date.toLocaleDateString('en-GB', {_x000D_
  day: '2-digit', month: 'short', year: 'numeric'_x000D_
}).replace(/ /g, '-');_x000D_
document.write(formattedDate);_x000D_
</script>
_x000D_
_x000D_
_x000D_

Is it possible to make Font Awesome icons larger than 'fa-5x'?

You can redefine/overwrite the default font-awesome sizes and also add you own sizes

.fa-1x{
    font-size:0.8em;
}
.fa-2x{
    font-size:1em;
}
.fa-3x{
    font-size:1.2em;
}
.fa-4x{
    font-size:1.4em;
}
.fa-5x{
    font-size:1.6em;
}
.fa-mycustomx{
    font-size:3.2em;
}

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

  • vfork() is an obsolete optimization. Before good memory management, fork() made a full copy of the parent's memory, so it was pretty expensive. since in many cases a fork() was followed by exec(), which discards the current memory map and creates a new one, it was a needless expense. Nowadays, fork() doesn't copy the memory; it's simply set as "copy on write", so fork()+exec() is just as efficient as vfork()+exec().

  • clone() is the syscall used by fork(). with some parameters, it creates a new process, with others, it creates a thread. the difference between them is just which data structures (memory space, processor state, stack, PID, open files, etc) are shared or not.

Condition within JOIN or WHERE

I typically see performance increases when filtering on the join. Especially if you can join on indexed columns for both tables. You should be able to cut down on logical reads with most queries doing this too, which is, in a high volume environment, a much better performance indicator than execution time.

I'm always mildly amused when someone shows their SQL benchmarking and they've executed both versions of a sproc 50,000 times at midnight on the dev server and compare the average times.

How to view the assembly behind the code using Visual C++?

Additional note: there is big difference between Debug assembler output and Release one. The first one is good to learn how compiler produces assembler code from C++. The second one is good to learn how compiler optimizes various C++ constructs. In this case some C++-to-asm transformations are not obvious.

Alert after page load

There are three ways.
The first is to put the script tag on the bottom of the page:

<body>
<!--Body content-->
<script type="text/javascript">
alert('<%: TempData["Resultat"]%>');
</script>
</body>

The second way is to create an onload event:

<head>
<script type="text/javascript">
window.onload = function(){//window.addEventListener('load',function(){...}); (for Netscape) and window.attachEvent('onload',function(){...}); (for IE and Opera) also work
    alert('<%: TempData["Resultat"]%>');
}
</script>
</head>

It will execute a function when the window loads.
Finally, the third way is to create a readystatechange event and check the current document.readystate:

<head>
<script type="text/javascript">
document.onreadystatechange = function(){//window.addEventListener('readystatechange',function(){...}); (for Netscape) and window.attachEvent('onreadystatechange',function(){...}); (for IE and Opera) also work
    if(document.readyState=='loaded' || document.readyState=='complete')
        alert('<%: TempData["Resultat"]%>');
}
</script>
</head>

How to change the font on the TextView?

import java.lang.ref.WeakReference;
import java.util.HashMap;

import android.content.Context;
import android.graphics.Typeface;

public class FontsManager {

    private static FontsManager instance;

    private static HashMap<String, WeakReference<Typeface>> typefaces = new HashMap<String, WeakReference<Typeface>>();

    private static Context context;

    private FontsManager(final Context ctx) {
        if (context == null) {
            context = ctx;
        }
    }

    public static FontsManager getInstance(final Context appContext) {
        if (instance == null) {
            instance = new FontsManager(appContext);
        }
        return instance;
    }

    public static FontsManager getInstance() {
        if (instance == null) {
            throw new RuntimeException(
                    "Call getInstance(Context context) at least once to init the singleton properly");
        }
        return instance;
    }

    public Typeface getFont(final String assetName) {
        final WeakReference<Typeface> tfReference = typefaces.get(assetName);
        if (tfReference == null || tfReference.get() == null) {
            final Typeface tf = Typeface.createFromAsset(context.getResources().getAssets(),
                    assetName);
            typefaces.put(assetName, new WeakReference<Typeface>(tf));
            return tf;
        }
        return tfReference.get();
    }

}

This way, you can create a View which inherits from TextView and calls setTypeface on its constructor.

How does Go update third-party packages?

@tux answer is great, just wanted to add that you can use go get to update a specific package:

go get -u full_package_name

Is there a way to call a stored procedure with Dapper?

In the simple case you can do:

var user = cnn.Query<User>("spGetUser", new {Id = 1}, 
        commandType: CommandType.StoredProcedure).First();

If you want something more fancy, you can do:

 var p = new DynamicParameters();
 p.Add("@a", 11);
 p.Add("@b", dbType: DbType.Int32, direction: ParameterDirection.Output);
 p.Add("@c", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);

 cnn.Execute("spMagicProc", p, commandType: CommandType.StoredProcedure); 

 int b = p.Get<int>("@b");
 int c = p.Get<int>("@c"); 

Additionally you can use exec in a batch, but that is more clunky.

Retina displays, high-res background images

Do I need to double the size of the .box div to 400px by 400px to match the new high res background image

No, but you do need to set the background-size property to match the original dimensions:

@media (-webkit-min-device-pixel-ratio: 2), 
(min-resolution: 192dpi) { 

    .box{
        background:url('images/[email protected]') no-repeat top left;
        background-size: 200px 200px;
    }
}

EDIT

To add a little more to this answer, here is the retina detection query I tend to use:

@media
only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and (   min--moz-device-pixel-ratio: 2),
only screen and (     -o-min-device-pixel-ratio: 2/1),
only screen and (        min-device-pixel-ratio: 2),
only screen and (                min-resolution: 192dpi),
only screen and (                min-resolution: 2dppx) { 

}

- Source

NB. This min--moz-device-pixel-ratio: is not a typo. It is a well documented bug in certain versions of Firefox and should be written like this in order to support older versions (prior to Firefox 16). - Source


As @LiamNewmarch mentioned in the comments below, you can include the background-size in your shorthand background declaration like so:

.box{
    background:url('images/[email protected]') no-repeat top left / 200px 200px;
}

However, I personally would not advise using the shorthand form as it is not supported in iOS <= 6 or Android making it unreliable in most situations.

Map and Reduce in .NET

The classes of problem that are well suited for a mapreduce style solution are problems of aggregation. Of extracting data from a dataset. In C#, one could take advantage of LINQ to program in this style.

From the following article: http://codecube.net/2009/02/mapreduce-in-c-using-linq/

the GroupBy method is acting as the map, while the Select method does the job of reducing the intermediate results into the final list of results.

var wordOccurrences = words
                .GroupBy(w => w)
                .Select(intermediate => new
                {
                    Word = intermediate.Key,
                    Frequency = intermediate.Sum(w => 1)
                })
                .Where(w => w.Frequency > 10)
                .OrderBy(w => w.Frequency);

For the distributed portion, you could check out DryadLINQ: http://research.microsoft.com/en-us/projects/dryadlinq/default.aspx

How to add a line break within echo in PHP?

\n is a line break. /n is not.


use of \n with

1. echo directly to page

Now if you are trying to echo string to the page:

echo  "kings \n garden";

output will be:

kings garden

you won't get garden in new line because PHP is a server-side language, and you are sending output as HTML, you need to create line breaks in HTML. HTML doesn't understand \n. You need to use the nl2br() function for that.

What it does is:

Returns string with <br /> or <br> inserted before all newlines (\r\n, \n\r, \n and \r).

echo  nl2br ("kings \n garden");

Output

kings
garden

Note Make sure you're echoing/printing \n in double quotes, else it will be rendered literally as \n. because php interpreter parse string in single quote with concept of as is

so "\n" not '\n'

2. write to text file

Now if you echo to text file you can use just \n and it will echo to a new line, like:

$myfile = fopen("test.txt", "w+")  ;

$txt = "kings \n garden";
fwrite($myfile, $txt);
fclose($myfile);
 

output will be:

kings
 garden

Regex: match word that ends with "Id"

This may do the trick:

\b\p{L}*Id\b

Where \p{L} matches any (Unicode) letter and \b matches a word boundary.

HTML 5: Is it <br>, <br/>, or <br />?

The elements without having end tags are called as empty tags. In html 4 and html 5, end tags are not required and can be omitted.

In xhtml, tags are so strict. That means must start with start tag and end with end tag.

How to replicate vector in c?

https://github.com/jakubgorny47/baku-code/tree/master/c_vector

Here's my implementation. It's basicaly a struct containing pointer to the data, size (in elements), overall allocated space and a size of the type that's being stored in vector to allow use of void pointer.

Oracle SQL Developer spool output?

You can export the query results to a text file (or insert statements, or even pdf) by right-clicking on Query Result row (any row) and choose Export

using Sql Developer 3.0

See SQL Developer downloads for latest versions

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

What you have is a parse error. Those are thrown before any code is executed. A PHP file needs to be parsed in its entirety before any code in it can be executed. If there's a parse error in the file where you're setting your error levels, they won't have taken effect by the time the error is thrown.

Either break your files up into smaller parts, like setting the error levels in one file and then includeing another file which contains the actual code (and errors), or set the error levels outside PHP using php.ini or .htaccess directives.

What's the equivalent of Java's Thread.sleep() in JavaScript?

This eventually helped me:

    var x = 0;
    var buttonText = 'LOADING';

    $('#startbutton').click(function(){
        $(this).text(buttonText);
        window.setTimeout(addDotToButton,2000);
    })

    function addDotToButton(){
        x++;
        buttonText += '.';
        $('#startbutton').text(buttonText);

        if (x < 4) window.setTimeout(addDotToButton, 2000);
        else location.reload(true);
    }

Python match a string with regex

You do not need regular expressions to check if a substring exists in a string.

line = 'This,is,a,sample,string'
result = bool('sample' in line) # returns True

If you want to know if a string contains a pattern then you should use re.search

line = 'This,is,a,sample,string'
result = re.search(r'sample', line) # finds 'sample'

This is best used with pattern matching, for example:

line = 'my name is bob'
result = re.search(r'my name is (\S+)', line) # finds 'bob'

wget/curl large file from google drive

The easiest way to is put what ever you want to download in a folder. Share that folder and then grab the Folder ID from the URL Bar.

Then go to https://googledrive.com/host/[ID] (Replace the ID with your folder ID) You should see a list of all the files in that folder, click the one you want to download. A download should then visit your download page (Ctrl+J on Chrome), you then want to copy the download link then use wget "download link"

Enjoy :)

Select where count of one field is greater than one

It should also be mentioned that the "pk" should be a key field. The self-join

SELECT t1.* FROM db.table t1
JOIN db.table t2 ON t1.someField = t2.someField AND t1.pk != t2.pk 

by Bill Karwin give you all the records that are duplicates which is what I wanted. Because some have more than two, you can get the same record more than once. I wrote all to another table with the same fields to get rid of the same records by key fields suppression. I tried

SELECT * FROM db.table HAVING COUNT(someField) > 1

above first. The data returned from it give only one of the duplicates, less than 1/2 of what this gives you but the count is good if that is all you want.

Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

You need to manually filter input to constructors and setters. Well... you could use reflection but I wouldn't advise it. Part of the job of constructors and setters is to validate input. That can include things like:

public void setPrice(double price) {
  if (price < 0.0d) {
    throw new IllegalArgumentException("price cannot be negative " + price);
  }
  this.price = price;
}

and

public void setName(String name) {
  if (name == null) {
    throw new NullPointerException("name cannot be null");
  }
  this.name = name;
}

You could use wrapper functions for the actual check and throwing the exception.

Adding and using header (HTTP) in nginx

To add a header just add the following code to the location block where you want to add the header:

location some-location {
  add_header X-my-header my-header-content;      
}

Obviously, replace the x-my-header and my-header-content with what you want to add. And that's all there is to it.

Execute a shell script in current shell with sudo permission

The answers here explain why it happens but I thought I'd add my simple way around the issue. First you can cat the file into a variable with sudo permissions. Then you can evaluate the variable to execute the code in the file in your current shell.

Here is an example of reading and executing an .env file (ex Docker)

 sensitive_stuff=$(sudo cat ".env")
 eval "${sensitive_stuff}"
 echo $ADMIN_PASSWORD 

Java, Shifting Elements in an Array

Assuming your array is {10,20,30,40,50,60,70,80,90,100}

What your loop does is:

Iteration 1: array[1] = array[0]; {10,10,30,40,50,60,70,80,90,100}

Iteration 2: array[2] = array[1]; {10,10,10,40,50,60,70,80,90,100}

What you should be doing is

Object temp = pool[position];

for (int i = (position - 1); i >= 0; i--) {                
    array[i+1] = array[i];
}

array[0] = temp;

Difference between Ctrl+Shift+F and Ctrl+I in Eclipse

Ctrl+Shift+F formats the selected line(s) or the whole source code if you haven't selected any line(s) as per the format specified in your Eclipse, while Ctrl+I gives proper indent to the selected line(s) or the current line if you haven't selected any line(s). try this. or more precisely

The Ant editor that ships with Eclipse can be used to reformat

XML/XHTML/HTML code (with a few configuration options in Window > Preferences > Ant > Editor).

You can right-click a file then

Open With... > Other... > Internal Editors > Ant Editor

Or add a file association between .html (or .xhtml) and that editor with

Window > Preferences > General > Editors > File Associations

Once open in the editor, hit ESC then CTRL-F to reformat.

Why does this iterative list-growing code give IndexError: list assignment index out of range?

j is an empty list, but you're attempting to write to element [0] in the first iteration, which doesn't exist yet.

Try the following instead, to add a new element to the end of the list:

for l in i:
    j.append(l)

Of course, you'd never do this in practice if all you wanted to do was to copy an existing list. You'd just do:

j = list(i)

Alternatively, if you wanted to use the Python list like an array in other languages, then you could pre-create a list with its elements set to a null value (None in the example below), and later, overwrite the values in specific positions:

i = [1, 2, 3, 5, 8, 13]
j = [None] * len(i)
#j == [None, None, None, None, None, None]
k = 0

for l in i:
   j[k] = l
   k += 1

The thing to realise is that a list object will not allow you to assign a value to an index that doesn't exist.

How to create a string with format?

Use this following code:

    let intVal=56
    let floatval:Double=56.897898
    let doubleValue=89.0
    let explicitDaouble:Double=89.56
    let stringValue:"Hello"

    let stringValue="String:\(stringValue) Integer:\(intVal) Float:\(floatval) Double:\(doubleValue) ExplicitDouble:\(explicitDaouble) "

How to get the last day of the month?

Use pandas!

def isMonthEnd(date):
    return date + pd.offsets.MonthEnd(0) == date

isMonthEnd(datetime(1999, 12, 31))
True
isMonthEnd(pd.Timestamp('1999-12-31'))
True
isMonthEnd(pd.Timestamp(1965, 1, 10))
False

Removing Java 8 JDK from Mac

Use /usr/libexec/java_home ; I found these alias and function to be pretty useful in my ~/.profile:

alias java_ls='/usr/libexec/java_home -V 2>&1 | cut -s -d , -f 1 | cut -c 5-'
function java_use() {
    export JAVA_HOME=$(/usr/libexec/java_home -v $1)
    java -version
}

Cannot access a disposed object - How to fix?

You sure the timer isn't outliving the 'dbiSchedule' somehow and firing after the 'dbiSchedule' has been been disposed of?

If that is the case you might be able to recreate it more consistently if the timer fires more quickly thus increasing the chances of you closing the Form just as the timer is firing.

JAX-WS client : what's the correct path to access the local WSDL?

Had the exact same problem that is described herein. No matter what I did, following the above examples, to change the location of my WSDL file (in our case from a web server), it was still referencing the original location embedded within the source tree of the server process.

After MANY hours trying to debug this, I noticed that the Exception was always being thrown from the exact same line (in my case 41). Finally this morning, I decided to just send my source client code to our trade partner so they can at least understand how the code looks, but perhaps build their own. To my shock and horror I found a bunch of class files mixed in with my .java files within my client source tree. How bizarre!! I suspect these were a byproduct of the JAX-WS client builder tool.

Once I zapped those silly .class files and performed a complete clean and rebuild of the client code, everything works perfectly!! Redonculous!!

YMMV, Andrew

Implode an array with JavaScript?

Like This:

[1,2,3,4].join('; ')

How to gracefully handle the SIGKILL signal in Java

I would expect that the JVM gracefully interrupts (thread.interrupt()) all the running threads created by the application, at least for signals SIGINT (kill -2) and SIGTERM (kill -15).

This way, the signal will be forwarded to them, allowing a gracefully thread cancellation and resource finalization in the standard ways.

But this is not the case (at least in my JVM implementation: Java(TM) SE Runtime Environment (build 1.8.0_25-b17), Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode).

As other users commented, the usage of shutdown hooks seems mandatory.

So, how do I would handle it?

Well first, I do not care about it in all programs, only in those where I want to keep track of user cancellations and unexpected ends. For example, imagine that your java program is a process managed by other. You may want to differentiate whether it has been terminated gracefully (SIGTERM from the manager process) or a shutdown has occurred (in order to relaunch automatically the job on startup).

As a basis, I always make my long-running threads periodically aware of interrupted status and throw an InterruptedException if they interrupted. This enables execution finalization in way controlled by the developer (also producing the same outcome as standard blocking operations). Then, at the top level of the thread stack, InterruptedException is captured and appropriate clean-up performed. These threads are coded to known how to respond to an interruption request. High cohesion design.

So, in these cases, I add a shutdown hook, that does what I think the JVM should do by default: interrupt all the non-daemon threads created by my application that are still running:

Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {
        System.out.println("Interrupting threads");
        Set<Thread> runningThreads = Thread.getAllStackTraces().keySet();
        for (Thread th : runningThreads) {
            if (th != Thread.currentThread() 
                && !th.isDaemon() 
                && th.getClass().getName().startsWith("org.brutusin")) {
                System.out.println("Interrupting '" + th.getClass() + "' termination");
                th.interrupt();
            }
        }
        for (Thread th : runningThreads) {
            try {
                if (th != Thread.currentThread() 
                && !th.isDaemon() 
                && th.isInterrupted()) {
                    System.out.println("Waiting '" + th.getName() + "' termination");
                    th.join();
                }
            } catch (InterruptedException ex) {
                System.out.println("Shutdown interrupted");
            }
        }
        System.out.println("Shutdown finished");
    }
});

Complete test application at github: https://github.com/idelvall/kill-test

npm install gives error "can't find a package.json file"

I was facing the same issue as below.

npm ERR! errno -4058 npm ERR! syscall open npm ERR! enoent ENOENT: no such file or directory, open 'D:\SVenu\FullStackDevelopment\Angular\Angular2_Splitter_CodeSkeleton\CodeSke leton\run\package.json' npm ERR! enoent This is related to npm not being able to find a file. npm ERR! enoent

The problem I made was, I was running the command npm build run instead of running npm run build.

Just sharing to help someone who does small mistakes like me.

How to change JFrame icon

Unfortunately, the above solution did not work for Jython Fiji plugin. I had to use getProperty to construct the relative path dynamically.

Here's what worked for me:

import java.lang.System.getProperty;
import javax.swing.JFrame;
import javax.swing.ImageIcon;

frame = JFrame("Test")
icon = ImageIcon(getProperty('fiji.dir') + '/path/relative2Fiji/icon.png')
frame.setIconImage(icon.getImage());
frame.setVisible(True)

How can I change column types in Spark SQL's DataFrame?

As the cast operation is available for Spark Column's (and as I personally do not favour udf's as proposed by @Svend at this point), how about:

df.select( df("year").cast(IntegerType).as("year"), ... )

to cast to the requested type? As a neat side effect, values not castable / "convertable" in that sense, will become null.

In case you need this as a helper method, use:

object DFHelper{
  def castColumnTo( df: DataFrame, cn: String, tpe: DataType ) : DataFrame = {
    df.withColumn( cn, df(cn).cast(tpe) )
  }
}

which is used like:

import DFHelper._
val df2 = castColumnTo( df, "year", IntegerType )

What is the suggested way to install brew, node.js, io.js, nvm, npm on OS X?

  1. Using homebrew install nvm:

    brew update
    brew install nvm
    source $(brew --prefix nvm)/nvm.sh
    

    Add the last command to the .profile, .bashrc or .zshrc file to not run it again on every terminal start. So for example to add it to the .profile run:

    echo "source $(brew --prefix nvm)/nvm.sh" >> ~/.profile
    

    If you have trouble with installing nvm using brew you can install it manually (see here)

  2. Using nvm install node or iojs (you can install any version you want):

    nvm install 0.10
    # or
    nvm install iojs-1.2.0
    
  3. npm is shipping with node (or iojs), so it will be available after installing node (or iojs). You may want to upgrade it to the latest version:

    $ npm install -g npm@latest
    

    UPD Previous version was npm update -g npm. Thanks to @Metallica for pointing to the correct way (look at the comment bellow).

  4. Using npm install ionic:

    npm install -g ionic
    
  5. What about ngCordova: you can install it using npm or bower. I don't know what variant is more fit for you, it depends on the package manager you want to use for the client side. So I'll describe them both:

    1. Using npm: Go to your project folder and install ng-cordova in it:

      npm install --save ng-cordova
      
    2. Using bower: Install bower:

       npm install -g bower
      

      And then go to your project folder and install ngCordova in it:

       bower install --save ngCordova
      

PS

  1. Some commands may require superuser privilege
  2. Short variant of npm install some_module is npm i some_module

Fastest way to convert JavaScript NodeList to Array?

With ES6, we now have a simple way to create an Array from a NodeList: the Array.from() function.

// nl is a NodeList
let myArray = Array.from(nl)

Session unset, or session_destroy?

Unset will destroy a particular session variable whereas session_destroy() will destroy all the session data for that user.

It really depends on your application as to which one you should use. Just keep the above in mind.

unset($_SESSION['name']); // will delete just the name data

session_destroy(); // will delete ALL data associated with that user.

How to search for a file in the CentOS command line

Try this command:

find / -name file.look

How can I calculate the difference between two ArrayLists?

THIS WORK ALSO WITH Arraylist

    // Create a couple ArrayList objects and populate them
    // with some delicious fruits.
    ArrayList<String> firstList = new ArrayList<String>() {/**
         * 
         */
        private static final long serialVersionUID = 1L;

    {
        add("apple");
        add("orange");
        add("pea");
    }};

    ArrayList<String> secondList = new ArrayList<String>() {

    /**
         * 
         */
        private static final long serialVersionUID = 1L;

    {
        add("apple");
        add("orange");
        add("banana");
        add("strawberry");
    }};

    // Show the "before" lists
    System.out.println("First List: " + firstList);
    System.out.println("Second List: " + secondList);

    // Remove all elements in firstList from secondList
    secondList.removeAll(firstList);

    // Show the "after" list
    System.out.println("Result: " + secondList);

Check Whether a User Exists

Late answer but finger also shows more information on user

  sudo apt-get finger 
  finger "$username"

"Comparison method violates its general contract!"

You can't compare object data like this:s1.getParent() == s2 - this will compare the object references. You should override equals function for Foo class and then compare them like this s1.getParent().equals(s2)

Copying files using rsync from remote server to local machine

I think it is better to copy files from your local computer, because if files number or file size is very big, copying process could be interrupted if your current ssh session would be lost (broken pipe or whatever).

If you have configured ssh key to connect to your remote server, you could use the following command:

rsync -avP -e "ssh -i /home/local_user/ssh/key_to_access_remote_server.pem" remote_user@remote_host.ip:/home/remote_user/file.gz /home/local_user/Downloads/

Where v option is --verbose, a option is --archive - archive mode, P option same as --partial - keep partially transferred files, e option is --rsh=COMMAND - specifying the remote shell to use.

rsync man page

.NET Out Of Memory Exception - Used 1.3GB but have 16GB installed

As already mentioned, compiling the app in x64 gives you far more available memory.

But in the case one must build an app in x86, there is a way to raise the memory limit from 1,2GB to 4GB (which is the actual limit for 32 bit processes):

In the VC/bin folder of the Visual Studio installation directory, there must be an editbin.exe file. So in my default installation I find it under

C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\editbin.exe

In order to make the program work, maybe you must execute vcvars32.bat in the same directory first. Then a

editbin /LARGEADDRESSAWARE <your compiled exe file>

is enough to let your program use 4GB RAM. <your compiled exe file> is the exe, which VS generated while compiling your project.

If you want to automate this behavior every time you compile your project, use the following Post-Build event for the executed project:

if exist "$(DevEnvDir)..\tools\vsvars32.bat" (
   call "$(DevEnvDir)..\tools\vsvars32.bat"
   editbin /largeaddressaware "$(TargetPath)"
)

Sidenote: The same can be done with the devenv.exe to let Visual Studio also use 4GB RAM instead of 1.2GB (but first backup the old devenv.exe).

Print a list in reverse order with range()?

You could use range(10)[::-1] which is the same thing as range(9, -1, -1) and arguably more readable (if you're familiar with the common sequence[::-1] Python idiom).

Try/catch does not seem to have an effect

If you want try/catch to work for all errors (not just the terminating errors) you can manually make all errors terminating by setting the ErrorActionPreference.

try {

   $ErrorActionPreference = "Stop"; #Make all errors terminating
   get-item filethatdoesntexist; # normally non-terminating
   write-host "You won't hit me";  
} catch{
   Write-Host "Caught the exception";
   Write-Host $Error[0].Exception;
}finally{
   $ErrorActionPreference = "Continue"; #Reset the error action pref to default
}

Alternatively... you can make your own trycatch function that accepts scriptblocks so that your try catch calls are not as kludge. I have mine return true/false just in case i need to check if there was an error... but it doesnt have to. Also, exception logging is optional, and can be taken care of in the catch, but i found myself always calling the logging function in the catch block, so i added it to the try catch function.

function log([System.String] $text){write-host $text;}

function logException{
    log "Logging current exception.";
    log $Error[0].Exception;
}


function mytrycatch ([System.Management.Automation.ScriptBlock] $try,
                    [System.Management.Automation.ScriptBlock] $catch,
                    [System.Management.Automation.ScriptBlock]  $finally = $({})){



# Make all errors terminating exceptions.
    $ErrorActionPreference = "Stop";

    # Set the trap
    trap [System.Exception]{
        # Log the exception.
        logException;

        # Execute the catch statement
        & $catch;

        # Execute the finally statement
        & $finally

        # There was an exception, return false
        return $false;
    }

    # Execute the scriptblock
    & $try;

    # Execute the finally statement
    & $finally

    # The following statement was hit.. so there were no errors with the scriptblock
    return $true;
}


#execute your own try catch
mytrycatch {
        gi filethatdoesnotexist; #normally non-terminating
        write-host "You won't hit me."
    } {
        Write-Host "Caught the exception";
    }

Is there a Google Sheets formula to put the name of the sheet into a cell?

Here is my proposal for a script which returns the name of the sheet from its position in the sheet list in parameter. If no parameter is provided, the current sheet name is returned.

function sheetName(idx) {
  if (!idx)
    return SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
  else {
    var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
    var idx = parseInt(idx);
    if (isNaN(idx) || idx < 1 || sheets.length < idx)
      throw "Invalid parameter (it should be a number from 0 to "+sheets.length+")";
    return sheets[idx-1].getName();
  }
}

You can then use it in a cell like any function

=sheetName() // display current sheet name
=sheetName(1) // display first sheet name
=sheetName(5) // display 5th sheet name

As described by other answers, you need to add this code in a script with :

Tools > Script editor

Assigning the return value of new by reference is deprecated

Nitin is correct - the issue is actually in the MDB2 code.

According to Replacement for PEAR: MDB2 on PHP 5.3 you can update to the SVN version of MDB2 for a version which is PHP5.3 compatible.

As that answer was given in March 2010, and http://pear.php.net/package/MDB2/ shows a release some months later, I expect the current version of MDB2 will solve the issue also.

Gradle does not find tools.jar

For me this error ocurred after trying to use audioplayers flutter library. To solve i got tools.jar of the folder:

C:\Program Files\Android\Android Studio\jre\lib

and pasted on

C:\Program Files\Java\jre1.8.0_181\lib.

After this the build worked fine.

"for line in..." results in UnicodeDecodeError: 'utf-8' codec can't decode byte

The following also worked for me. ISO 8859-1 is going to save a lot, hahaha - mainly if using Speech Recognition APIs.

Example:

file = open('../Resources/' + filename, 'r', encoding="ISO-8859-1");

Django Rest Framework File Upload

models.py

from django.db import models

import uuid

class File(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    file = models.FileField(blank=False, null=False)
    
    def __str__(self):
        return self.file.name

serializers.py

from rest_framework import serializers
from .models import File

class FileSerializer(serializers.ModelSerializer):
    class Meta:
        model = File
        fields = "__all__"

views.py

from django.shortcuts import render
from rest_framework.parsers import FileUploadParser
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status

from .serializers import FileSerializer


class FileUploadView(APIView):
    permission_classes = []
    parser_class = (FileUploadParser,)

    def post(self, request, *args, **kwargs):

      file_serializer = FileSerializer(data=request.data)

      if file_serializer.is_valid():
          file_serializer.save()
          return Response(file_serializer.data, status=status.HTTP_201_CREATED)
      else:
          return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

urls.py

from apps.files import views as FileViews

urlpatterns = [
    path('api/files', FileViews.FileUploadView.as_view()),
]

settings.py

# file uload parameters
MEDIA_URL =  '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Send a post request to api/files with a your file attached to a form-data field file. The file will be uploaded to /media folder and a db record will be added with id and file name.

Implementing SearchView in action bar


For Searchview use these code

  1. For XML

    <android.support.v7.widget.SearchView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/searchView">
    
    </android.support.v7.widget.SearchView>
    

  2. In your Fragment or Activity

    package com.example.user.salaryin;
    
    import android.app.ProgressDialog;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.view.MenuItemCompat;
    import android.support.v7.widget.GridLayoutManager;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.support.v7.widget.SearchView;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Toast;
    import com.example.user.salaryin.Adapter.BusinessModuleAdapter;
    import com.example.user.salaryin.Network.ApiClient;
    import com.example.user.salaryin.POJO.ProductDetailPojo;
    import com.example.user.salaryin.Service.ServiceAPI;
    import java.util.ArrayList;
    import java.util.List;
    import retrofit2.Call;
    import retrofit2.Callback;
    import retrofit2.Response;
    
    
    public class OneFragment extends Fragment implements SearchView.OnQueryTextListener {
    
    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;
    ArrayList<ProductDetailPojo> arrayList;
    BusinessModuleAdapter adapter;
    private ProgressDialog pDialog;
    GridLayoutManager gridLayoutManager;
    SearchView searchView;
    
    public OneFragment() {
        // Required empty public constructor
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    
        View rootView = inflater.inflate(R.layout.one_fragment,container,false);
    
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Please wait...");
    
    
        searchView=(SearchView)rootView.findViewById(R.id.searchView);
        searchView.setQueryHint("Search BY Brand");
        searchView.setOnQueryTextListener(this);
    
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
        layoutManager = new LinearLayoutManager(this.getActivity());
        recyclerView.setLayoutManager(layoutManager);
        gridLayoutManager = new GridLayoutManager(this.getActivity().getApplicationContext(), 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setHasFixedSize(true);
        getImageData();
    
    
        // Inflate the layout for this fragment
        //return inflater.inflate(R.layout.one_fragment, container, false);
        return rootView;
    }
    
    
    private void getImageData() {
        pDialog.show();
        ServiceAPI service = ApiClient.getRetrofit().create(ServiceAPI.class);
        Call<List<ProductDetailPojo>> call = service.getBusinessImage();
    
        call.enqueue(new Callback<List<ProductDetailPojo>>() {
            @Override
            public void onResponse(Call<List<ProductDetailPojo>> call, Response<List<ProductDetailPojo>> response) {
                if (response.isSuccessful()) {
                    arrayList = (ArrayList<ProductDetailPojo>) response.body();
                    adapter = new BusinessModuleAdapter(arrayList, getActivity());
                    recyclerView.setAdapter(adapter);
                    pDialog.dismiss();
                } else if (response.code() == 401) {
                    pDialog.dismiss();
                    Toast.makeText(getActivity(), "Data is not found", Toast.LENGTH_SHORT).show();
                }
    
            }
    
            @Override
            public void onFailure(Call<List<ProductDetailPojo>> call, Throwable t) {
                Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show();
                pDialog.dismiss();
    
            }
        });
    }
    
       /* @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.menu_search, menu);
        MenuItem menuItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
        searchView.setQueryHint("Search Product");
        searchView.setOnQueryTextListener(this);
    }*/
    
    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }
    
    @Override
    public boolean onQueryTextChange(String newText) {
        newText = newText.toLowerCase();
        ArrayList<ProductDetailPojo> newList = new ArrayList<>();
        for (ProductDetailPojo productDetailPojo : arrayList) {
            String name = productDetailPojo.getDetails().toLowerCase();
    
            if (name.contains(newText) )
                newList.add(productDetailPojo);
            }
        adapter.setFilter(newList);
        return true;
       }
    }
    
  3. In adapter class

     public void setFilter(List<ProductDetailPojo> newList){
        arrayList=new ArrayList<>();
        arrayList.addAll(newList);
        notifyDataSetChanged();
    }
    

Hidden features of Windows batch files

here's one trick that I use to run My Nant Build script consecutively without having to click the batch file over and over again.

:CODELINE
NANT.EXE -buildfile:alltargets.build -l:build.log build.product
@pause
GOTO :CODELINE

What will happen is that after your solution finished building, it will be paused. And then if you press any key it will rerun the build script again. Very handy I must say.

Can we pass model as a parameter in RedirectToAction?

Just call the action no need for redirect to action or the new keyword for model.

 [HttpPost]
    public ActionResult FillStudent(Student student1)
    {
        return GetStudent(student1); //this will also work
    }
    public ActionResult GetStudent(Student student)
    {
        return View(student);
    }

What is the meaning of @_ in Perl?

The question was what @_ means in Perl. The answer to that question is that, insofar as $_ means it in Perl, @_ similarly means they.

No one seems to have mentioned this critical aspect of its meaning — as well as theirs.

They’re consequently both used as pronouns, or sometimes as topicalizers.

They typically have nominal antecedents, although not always.

How to reliably open a file in the same directory as a Python script

I'd do it this way:

from os.path import abspath, exists

f_path = abspath("fooabar.txt")

if exists(f_path):
    with open(f_path) as f:
        print f.read()

The above code builds an absolute path to the file using abspath and is equivalent to using normpath(join(os.getcwd(), path)) [that's from the pydocs]. It then checks if that file actually exists and then uses a context manager to open it so you don't have to remember to call close on the file handle. IMHO, doing it this way will save you a lot of pain in the long run.

Position: absolute and parent height?

If I understand what you're trying to do correctly, then I don't think this is possible with CSS while keeping the children absolutely positioned.

Absolutely positioned elements are completely removed from the document flow, and thus their dimensions cannot alter the dimensions of their parents.

If you really had to achieve this affect while keeping the children as position: absolute, you could do so with JavaScript by finding the height of the absolutely positioned children after they have rendered, and using that to set the height of the parent.

Alternatively, just use float: left/float:right and margins to get the same positioning effect while keeping the children in the document flow, you can then use overflow: hidden on the parent (or any other clearfix technique) to cause its height to expand to that of its children.

article {
    position: relative;
    overflow: hidden;
}

.one {
    position: relative;
    float: left;
    margin-top: 10px;
    margin-left: 10px;
    background: red;
    width: 30px;
    height: 30px;
}

.two {
    position: relative;
    float: right;
    margin-top: 10px;
    margin-right: 10px;
    background: blue;
    width: 30px;
    height: 30px;
}

How do I read an attribute on a class at runtime?

In case anyone needs a nullable result and for this to work across Enums, PropertyInfo and classes, here's how I solved it. This is a modification of Darin Dimitrov's updated solution.

public static object GetAttributeValue<TAttribute, TValue>(this object val, Func<TAttribute, TValue> valueSelector) where TAttribute : Attribute
{
    try
    {
        Type t = val.GetType();
        TAttribute attr;
        if (t.IsEnum && t.GetField(val.ToString()).GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() is TAttribute att)
        {
            // Applies to Enum values
            attr = att;
        }
        else if (val is PropertyInfo pi && pi.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() is TAttribute piAtt)
        {
            // Applies to Properties in a Class
            attr = piAtt;
        }
        else
        {
            // Applies to classes
            attr = (TAttribute)t.GetCustomAttributes(typeof(TAttribute), false).FirstOrDefault();
        }
        return valueSelector(attr);
    }
    catch
    {
        return null;
    }
}

Usage examples:

// Class
SettingsEnum.SettingGroup settingGroup = (SettingsEnum.SettingGroup)(this.GetAttributeValue((SettingGroupAttribute attr) => attr.Value) as SettingsEnum.SettingGroup?);

// Enum
DescriptionAttribute desc = settingGroup.GetAttributeValue((DescriptionAttribute attr) => attr) as DescriptionAttribute;

// PropertyInfo       
foreach (PropertyInfo pi in this.GetType().GetProperties())
{
    string setting = ((SettingsEnum.SettingName)(pi.GetAttributeValue((SettingNameAttribute attr) => attr.Value) as SettingsEnum.SettingName?)).ToString();
}

Radio Buttons ng-checked with ng-model

I think you should only use ng-model and should work well for you, here is the link to the official documentation of angular https://docs.angularjs.org/api/ng/input/input%5Bradio%5D

The code from the example should not be difficult to adapt to your specific situation:

<script>
   function Ctrl($scope) {
      $scope.color = 'blue';
      $scope.specialValue = {
         "id": "12345",
         "value": "green"
      };
   }
</script>
<form name="myForm" ng-controller="Ctrl">
   <input type="radio" ng-model="color" value="red">  Red <br/>
   <input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
   <input type="radio" ng-model="color" value="blue"> Blue <br/>
   <tt>color = {{color | json}}</tt><br/>
</form>

Find substring in the string in TWIG

Just searched for the docs, and found this:

Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:

{# returns true #}

{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}

How do you remove Subversion control for a folder?

Also, if you are using TortoiseSVN, just export to the current working copy location and it will remove the .svn folders and files.

http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-export.html#tsvn-dug-export-unversion

Updated Answer for Subversion 1.7:
In Subversion 1.7 the working copy has been revised extensively. There is only one .svn folder, located in the base of the working copy. If you are using 1.7, then just deleting the .svn folder and its contents is an easy solution (regardless of using TortoiseSVN or command line tools).

Numpy converting array from float to strings

This is probably slower than what you want, but you can do:

>>> tostring = vectorize(lambda x: str(x))
>>> numpy.where(tostring(phis).astype('float64') != phis)
(array([], dtype=int64),)

It looks like it rounds off the values when it converts to str from float64, but this way you can customize the conversion however you like.

Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

I discovered this error on a recent application project. I was writing to run from the command line or the browser window, so I was using server detection to get the relative URL of the document I was asking for. The trouble was, the site is https, and each time I attempted to access http://(same server), cURL helpfully changed it to https.

This works fine from the browser, but from the command-line, I'd then get an SSL error even with both verify's set to false. What I had to do was,

1) Check $_SERVER['HTTP_HOST']. If present, use ($_SERVER['HTTPS'] ? "https://" : "http://").$_SERVER['HTTP_HOST']

2) Check $_SERVER['COMPUTERNAME'], and if it matched the production server, provide the https URL. ("https://(servername)")

3) If neither condition passed, it means I'm running command-line on a different server, and use "http://localhost".

Now, this worked, but it's a hack. Also, I never did figure out why on one server (https) cURL changed my URL, while on the other (also https) it left my URL alone.

Weird.

phpmyadmin "no data received to import" error, how to fix?

Change your upload settings in php.ini configuration file

Change the below settings to these values:

Change to:

post_max_size = 750M
upload_max_filesize = 750M
max_execution_time = 5000
max_input_time = 5000
memory_limit = 1000M

Dynamically adding elements to ArrayList in Groovy

The Groovy way to do this is

def list = []
list << new MyType(...)

which creates a list and uses the overloaded leftShift operator to append an item

See the Groovy docs on Lists for lots of examples.

SQL Server stored procedure parameters

CREATE PROCEDURE GetTaskEvents
@TaskName varchar(50),
@Id INT
AS
BEGIN
-- SP Logic
END

Procedure Calling

DECLARE @return_value nvarchar(50)

EXEC  @return_value = GetTaskEvents
        @TaskName = 'TaskName',
        @Id =2  

SELECT  'Return Value' = @return_value

Xcode 6 Bug: Unknown class in Interface Builder file

I faced a problem when I created a project with the same name that already existed in my projects directory (though it was deleted some time ago). I wrote my solution there https://stackoverflow.com/a/27763697/1654692

Google Maps JS API v3 - Simple Multiple Marker Example

This is the simplest I could reduce it to:

<!DOCTYPE html>
<html> 
<head> 
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
  <title>Google Maps Multiple Markers</title> 
  <script src="http://maps.google.com/maps/api/js?sensor=false" 
          type="text/javascript"></script>
</head> 
<body>
  <div id="map" style="width: 500px; height: 400px;"></div>

  <script type="text/javascript">
    var locations = [
      ['Bondi Beach', -33.890542, 151.274856, 4],
      ['Coogee Beach', -33.923036, 151.259052, 5],
      ['Cronulla Beach', -34.028249, 151.157507, 3],
      ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
      ['Maroubra Beach', -33.950198, 151.259302, 1]
    ];

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(-33.92, 151.25),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }
  </script>
</body>
</html>

? Edit/fork on a Codepen ?

SCREENSHOT

Google Maps Multiple Markers

There is some closure magic happening when passing the callback argument to the addListener method. This can be quite a tricky topic if you are not familiar with how closures work. I would suggest checking out the following Mozilla article for a brief introduction if it is the case:

? Mozilla Dev Center: Working with Closures

Maven in Eclipse: step by step installation

You have to follow the following steps in the Eclipse IDE

  1. Go to Help - > Install New Software
  2. Click add button at top right corner
  3. In the popup coming, type in name as "Maven" and location as "http://download.eclipse.org/technology/m2e/releases"
  4. Click on OK.

Maven integration for eclipse will be dowloaded and installed. Restart the workspace.

In the .m2 folder(usually under C:\user\ directory) add settings.xml. Give proper proxy and profiles. Now create a new Maven project in eclipse.

How to check if Receiver is registered in Android?

There is no API function to check if a receiver is registered. The workaround is to put your code in a try catch block as done below.

try {

 //Register or UnRegister your broadcast receiver here

} catch(IllegalArgumentException e) {

    e.printStackTrace();
}

Delete keychain items when an app is uninstalled

You can take advantage of the fact that NSUserDefaults are cleared by uninstallation of an app. For example:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //Clear keychain on first run in case of reinstallation
    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"FirstRun"]) {
        // Delete values from keychain here
        [[NSUserDefaults standardUserDefaults] setValue:@"1strun" forKey:@"FirstRun"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }

    //...Other stuff that usually happens in didFinishLaunching
}

This checks for and sets a "FirstRun" key/value in NSUserDefaults on the first run of your app if it's not already set. There's a comment where you should put code to delete values from the keychain. Synchronize can be called to make sure the "FirstRun" key/value is immediately persisted in case the user kills the app manually before the system persists it.

Put icon inside input element in a form

The site you linked uses a combination of CSS tricks to pull this off. First, it uses a background-image for the <input> element. Then, in order to push the cursor over, it uses padding-left.

In other words, they have these two CSS rules:

background: url(images/comment-author.gif) no-repeat scroll 7px 7px;
padding-left:30px;

Add items to comboBox in WPF

Use this

string[] str = new string[] {"Foo", "Bar"};

myComboBox.ItemsSource = str;
myComboBox.SelectedIndex = 0;

OR

foreach (string s in str)
    myComboBox.Items.Add(s);

myComboBox.SelectedIndex = 0;      

Convert java.time.LocalDate into java.util.Date type

java.util.Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());

Tracking CPU and Memory usage per process

Download process monitor

  1. Start Process Monitor

  2. Set a filter if required

  3. Enter menu Options > Profiling Events

  4. Click "Generate thread prof?iling events", choose the frequency, and click OK.

  5. To see the collected historical data at any time, enter menu Tools > Process Activity Summary

Difference between List, List<?>, List<T>, List<E>, and List<Object>

In your third point, "T" cannot be resolved because its not declared, usually when you declare a generic class you can use "T" as the name of the bound type parameter, many online examples including oracle's tutorials use "T" as the name of the type parameter, say for example, you declare a class like:

public class FooHandler<T>
{
   public void operateOnFoo(T foo) { /*some foo handling code here*/}

}

you are saying that FooHandler's operateOnFoo method expects a variable of type "T" which is declared on the class declaration itself, with this in mind, you can later add another method like

public void operateOnFoos(List<T> foos)

in all the cases either T, E or U there all identifiers of the type parameter, you can even have more than one type parameter which uses the syntax

public class MyClass<Atype,AnotherType> {}

in your forth ponint although efectively Sting is a sub type of Object, in generics classes there is no such relation, List<String> is not a sub type of List<Object> they are two diferent types from the compiler point of view, this is best explained in this blog entry

Get current URL/URI without some of $_GET variables

Yii::app()->createAbsoluteUrl(Yii::app()->request->url)

This will output something in the following format:

http://www.yoursite.com/your_yii_application/

PHP - count specific array values

array_count_values only works for integers and strings. If you happen to want counts for float/numeric values (and you are heedless of small variations in precision or representation), this works:

function arrayCountValues($arr) {
  $vals = [];
  foreach ($arr as $val) { array_push($vals,strval($val)); }
  $cnts = array_count_values($vals);
  arsort($cnts);
  return $cnts;
}

Note that I return $cnts with the keys as strings. It would be easy to reconvert them, but I'm trying to determine the mode for the values, so I only need to re-convert the first (several) values.

I tested a version which looped, creating an array of counts rather than using array_count_values, and this turned out to be more efficient (by maybe 8-10%)!

How to see data from .RData file?

I think the problem is that you load isfar data.frame but you overwrite it by value returned by load.

Try either:

load("C:/Users/isfar.RData") 
head(isfar)

Or more general way

load("C:/Users/isfar.RData", ex <- new.env())
ls.str(ex) 

How to convert JSON string to array

$data = json_encode($result, true);

echo $data;

Secure hash and salt for PHP passwords

ok in the fitsy we need salt salt must be unique so let generate it

   /**
     * Generating string
     * @param $size
     * @return string
     */
    function Uniwur_string($size){
        $text = md5(uniqid(rand(), TRUE));
        RETURN substr($text, 0, $size);
    }

also we need the hash I`m using sha512 it is the best and it is in php

   /**
     * Hashing string
     * @param $string
     * @return string
     */
    function hash($string){
        return hash('sha512', $string);
    }

so now we can use this functions to generate safe password

// generating unique password
$password = Uniwur_string(20); // or you can add manual password
// generating 32 character salt
$salt = Uniwur_string(32);
// now we can manipulate this informations

// hashin salt for safe
$hash_salt = hash($salt);
// hashing password
$hash_psw = hash($password.$hash_salt);

now we need to save in database our $hash_psw variable value and $salt variable

and for authorize we will use same steps...

it is the best way to safe our clients passwords...

P.s. for last 2 steps you can use your own algorithm... but be sure that you can generate this hashed password in the future when you need to authorize user...

CSS how to make scrollable list

As per your question vertical listing have a scrollbar effect.

CSS / HTML :

_x000D_
_x000D_
nav ul{height:200px; width:18%;}_x000D_
nav ul{overflow:hidden; overflow-y:scroll;}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <head>_x000D_
        <meta charset="utf-8">_x000D_
        <title>JS Bin</title>_x000D_
    </head>_x000D_
    <body>_x000D_
        <header>header area</header>_x000D_
        <nav>_x000D_
            <ul>_x000D_
                <li>Link 1</li>_x000D_
                <li>Link 2</li>_x000D_
                <li>Link 3</li>_x000D_
                <li>Link 4</li>_x000D_
                <li>Link 5</li>_x000D_
                <li>Link 6</li> _x000D_
                <li>Link 7</li> _x000D_
                <li>Link 8</li>_x000D_
                <li>Link 9</li>_x000D_
                <li>Link 10</li>_x000D_
                <li>Link 11</li>_x000D_
                <li>Link 13</li>_x000D_
                <li>Link 13</li>_x000D_
_x000D_
            </ul>_x000D_
        </nav>_x000D_
        _x000D_
        <footer>footer area</footer>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Replace preg_replace() e modifier with preg_replace_callback

preg_replace shim with eval support

This is very inadvisable. But if you're not a programmer, or really prefer terrible code, you could use a substitute preg_replace function to keep your /e flag working temporarily.

/**
 * Can be used as a stopgap shim for preg_replace() calls with /e flag.
 * Is likely to fail for more complex string munging expressions. And
 * very obviously won't help with local-scope variable expressions.
 *
 * @license: CC-BY-*.*-comment-must-be-retained
 * @security: Provides `eval` support for replacement patterns. Which
 *   poses troubles for user-supplied input when paired with overly
 *   generic placeholders. This variant is only slightly stricter than
 *   the C implementation, but still susceptible to varexpression, quote
 *   breakouts and mundane exploits from unquoted capture placeholders.
 * @url: https://stackoverflow.com/q/15454220
 */
function preg_replace_eval($pattern, $replacement, $subject, $limit=-1) {
    # strip /e flag
    $pattern = preg_replace('/(\W[a-df-z]*)e([a-df-z]*)$/i', '$1$2', $pattern);
    # warn about most blatant misuses at least
    if (preg_match('/\(\.[+*]/', $pattern)) {
        trigger_error("preg_replace_eval(): regex contains (.*) or (.+) placeholders, which easily causes security issues for unconstrained/user input in the replacement expression. Transform your code to use preg_replace_callback() with a sane replacement callback!");
    }
    # run preg_replace with eval-callback
    return preg_replace_callback(
        $pattern,
        function ($matches) use ($replacement) {
            # substitute $1/$2/… with literals from $matches[]
            $repl = preg_replace_callback(
                '/(?<!\\\\)(?:[$]|\\\\)(\d+)/',
                function ($m) use ($matches) {
                    if (!isset($matches[$m[1]])) { trigger_error("No capture group for '$m[0]' eval placeholder"); }
                    return addcslashes($matches[$m[1]], '\"\'\`\$\\\0'); # additionally escapes '$' and backticks
                },
                $replacement
            );
            # run the replacement expression
            return eval("return $repl;");
        },
        $subject,
        $limit
    );
}

In essence, you just include that function in your codebase, and edit preg_replace to preg_replace_eval wherever the /e flag was used.

Pros and cons:

  • Really just tested with a few samples from Stack Overflow.
  • Does only support the easy cases (function calls, not variable lookups).
  • Contains a few more restrictions and advisory notices.
  • Will yield dislocated and less comprehensible errors for expression failures.
  • However is still a usable temporary solution and doesn't complicate a proper transition to preg_replace_callback.
  • And the license comment is just meant to deter people from overusing or spreading this too far.

Replacement code generator

Now this is somewhat redundant. But might help those users who are still overwhelmed with manually restructuring their code to preg_replace_callback. While this is effectively more time consuming, a code generator has less trouble to expand the /e replacement string into an expression. It's a very unremarkable conversion, but likely suffices for the most prevalent examples.

To use this function, edit any broken preg_replace call into preg_replace_eval_replacement and run it once. This will print out the according preg_replace_callback block to be used in its place.

/**
 * Use once to generate a crude preg_replace_callback() substitution. Might often
 * require additional changes in the `return …;` expression. You'll also have to
 * refit the variable names for input/output obviously.
 *
 * >>>  preg_replace_eval_replacement("/\w+/", 'strtopupper("$1")', $ignored);
 */
function preg_replace_eval_replacement($pattern, $replacement, $subjectvar="IGNORED") {
    $pattern = preg_replace('/(\W[a-df-z]*)e([a-df-z]*)$/i', '$1$2', $pattern);
    $replacement = preg_replace_callback('/[\'\"]?(?<!\\\\)(?:[$]|\\\\)(\d+)[\'\"]?/', function ($m) { return "\$m[{$m[1]}]"; }, $replacement);
    $ve = "var_export";
    $bt = debug_backtrace(0, 1)[0];
    print "<pre><code>
    #----------------------------------------------------
    # replace preg_*() call in '$bt[file]' line $bt[line] with:
    #----------------------------------------------------
    \$OUTPUT_VAR = preg_replace_callback(
        {$ve($pattern, TRUE)},
        function (\$m) {
            return {$replacement};
        },
        \$YOUR_INPUT_VARIABLE_GOES_HERE
    )
    #----------------------------------------------------
    </code></pre>\n";
}

Take in mind that mere copy&pasting is not programming. You'll have to adapt the generated code back to your actual input/output variable names, or usage context.

  • Specificially the $OUTPUT = assignment would have to go if the previous preg_replace call was used in an if.
  • It's best to keep temporary variables or the multiline code block structure though.

And the replacement expression may demand more readability improvements or rework.

  • For instance stripslashes() often becomes redundant in literal expressions.
  • Variable-scope lookups require a use or global reference for/within the callback.
  • Unevenly quote-enclosed "-$1-$2" capture references will end up syntactically broken by the plain transformation into "-$m[1]-$m[2].

The code output is merely a starting point. And yes, this would have been more useful as an online tool. This code rewriting approach (edit, run, edit, edit) is somewhat impractical. Yet could be more approachable to those who are accustomed to task-centric coding (more steps, more uncoveries). So this alternative might curb a few more duplicate questions.

Nginx not picking up site in sites-enabled?

Changing from:

include /etc/nginx/sites-enabled/*; 

to

include /etc/nginx/sites-enabled/*.*; 

fixed my issue

Combine or merge JSON on node.js without jQuery

Here is simple solution, to merge JSON. I did the following.

  • Convert each of the JSON to strings using JSON.stringify(object).
  • Concatenate all the JSON strings using + operator.
  • Replace the pattern /}{/g with ","
  • Parse the result string back to JSON object

    var object1 = {name: "John"};
    var object2 = {location: "San Jose"};
    var merged_object = JSON.parse((JSON.stringify(object1) + JSON.stringify(object2)).replace(/}{/g,","))
    

The resulting merged JSON will be

{name: "John", location: "San Jose"}

Which encoding opens CSV files correctly with Excel on both Mac and Windows?

In my case this worked (Mac, Excel 2011, both Cyrillic and Latin characters with Czech diacritics):

  • Charset UTF-16LE (simply UTF-16 was not enough)
  • BOM "\xFF\xFE"
  • \t (tab) as separator
  • Don't forget to encode also separator and CRLFs :-)
  • Use iconv instead of mb_convert_encoding

postgresql return 0 if returned value is null

I can think of 2 ways to achieve this:

  • IFNULL():

    The IFNULL() function returns a specified value if the expression is NULL.If the expression is NOT NULL, this function returns the expression.

Syntax:

IFNULL(expression, alt_value)

Example of IFNULL() with your query:

SELECT AVG( price )
FROM(
      SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan
      WHERE listing_Type = 'AARM'
        AND u_kbalikepartnumbers_id = 1000307
        AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
        AND IFNULL( price, 0 ) > ( SELECT AVG( IFNULL( price, 0 ) )* 0.50
                                     FROM ( SELECT *, cume_dist() OVER ( ORDER BY price DESC )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) g
                                    WHERE cume_dist < 0.50
                                  )
        AND IFNULL( price, 0 ) < ( SELECT AVG( IFNULL( price, 0 ) ) *2
                                     FROM( SELECT *, cume_dist() OVER ( ORDER BY price desc )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) d
                                     WHERE cume_dist < 0.50)
     )s
HAVING COUNT(*) > 5
  • COALESCE()

    The COALESCE() function returns the first non-null value in a list.

Syntax:

COALESCE(val1, val2, ...., val_n)

Example of COALESCE() with your query:

SELECT AVG( price )
FROM(
      SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan
      WHERE listing_Type = 'AARM'
        AND u_kbalikepartnumbers_id = 1000307
        AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
        AND COALESCE( price, 0 ) > ( SELECT AVG( COALESCE( price, 0 ) )* 0.50
                                     FROM ( SELECT *, cume_dist() OVER ( ORDER BY price DESC )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) g
                                    WHERE cume_dist < 0.50
                                  )
        AND COALESCE( price, 0 ) < ( SELECT AVG( COALESCE( price, 0 ) ) *2
                                     FROM( SELECT *, cume_dist() OVER ( ORDER BY price desc )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) d
                                     WHERE cume_dist < 0.50)
     )s
HAVING COUNT(*) > 5

How to post object and List using postman

{
    "preOrderData" : [
        {
            "pname": "xyz",
            "quantity": "1",
            "unit": "Peice",
            "description": "xyz 100 gram",
            "preferred_brand": "xyz",
            "entry_date": "2020-10-05 11:11:27",
            "creation_date": "2020-10-05 11:11:27",
            "updated_date": "2020-10-05 11:11:27",
            "user": "[email protected]",
            "user_type": "individual"
        },
        {
            "productname": "abc cream",
            "quantity": "1",
            "unit": "Peice",
            "description": "abc 100 gram",
            "preferred_brand": "abccream",
            "entry_date": "2020-10-05 11:11:27",
            "creation_date": "2020-10-05 11:11:27",
            "updated_date": "2020-10-05 11:11:27",
            "user": "[email protected]",
            "user_type": "individual"
        }
    ]
}

Youtube - downloading a playlist - youtube-dl

I have tried everything above, but none could solve my problem. I fixed it by updating the old version of youtube-dl to download playlist. To update it

sudo youtube-dl -U

or

youtube-dl -U

after you have successfully updated using the above command

youtube-dl -cit https://www.youtube.com/playlist?list=PLttJ4RON7sleuL8wDpxbKHbSJ7BH4vvCk

How can I change my Cygwin home folder after installation?

I'd like to add a correction/update to the bit about $HOME taking precedence. The home directory in /etc/passwd takes precedence over everything.

I'm a long time Cygwin user and I just did a clean install of Windows 7 x64 and Cygwin V1.126. I was going nuts trying to figure out why every time I ran ssh I kept getting:

e:\>ssh foo.bar.com
Could not create directory '/home/dhaynes/.ssh'.
The authenticity of host 'foo.bar.com (10.66.19.19)' can't be established.
...

I add the HOME=c:\users\dhaynes definition in the Windows environment but still it kept trying to create '/home/dhaynes'. I tried every combo I could including setting HOME to /cygdrive/c/users/dhaynes. Googled for the error message, could not find anything, couldn't find anything on the cygwin site. I use cygwin from cmd.exe, not bash.exe but the problem was present in both.

I finally realized that the home directory in /etc/passwd was taking precedence over the $HOME environment variable. I simple re-ran 'mkpasswd -l >/etc/passwd' and that updated the home directory, now all is well with ssh.

That may be obvious to linux types with sysadmin experience but for those of us who primarily use Windows it's a bit obscure.

How to replace blank (null ) values with 0 for all records?

I used a two step process to change rows with "blank" values to "Null" values as place holders.

UPDATE [TableName] SET [TableName].[ColumnName] = "0"
WHERE ((([TableName].[ColumnName])=""));

UPDATE [TableName] SET [TableName].[ColumnName] = "Null"
WHERE ((([TableName].[ColumnName])="0"));

How to SELECT based on value of another SELECT

If you want to SELECT based on the value of another SELECT, then you probably want a "subselect":

http://beginner-sql-tutorial.com/sql-subquery.htm

For example, (from the link above):

  1. You want the first and last names from table "student_details" ...

  2. But you only want this information for those students in "science" class:

     SELECT id, first_name
     FROM student_details
     WHERE first_name IN (SELECT first_name
     FROM student_details
     WHERE subject= 'Science'); 
    

Frankly, I'm not sure this is what you're looking for or not ... but I hope it helps ... at least a little...

IMHO...

YouTube Autoplay not working

Remove the spaces before the autoplay=1:

src="https://www.youtube.com/embed/-SFcIUEvNOQ?autoplay=1&;enablejsapi=1"

How to install sklearn?

pip install numpy scipy scikit-learn

if you don't have pip, install it using

python get-pip.py

Download get-pip.py from the following link. or use curl to download it.

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

javac error: Class names are only accepted if annotation processing is explicitly requested

I was stumped by this too because I was including the .Java extension ... then I noticed the capital J.

This will also cause the "annotation processing" error:

javac myclass.Java 

Instead, it should be:

javac myclass.java 

What is a user agent stylesheet?

Some browsers use their own way to read .css files. So the right way to beat this: If you type the command line directly in the .html source code, this beats the .css file, in that way, you told the browser directly what to do and the browser is at position not to read the commands from the .css file. Remember that the commands writen in the .html file is stronger than the command in the .css.

How to resolve "Waiting for Debugger" message?

Rebooting the PC was the only thing that worked for me. It worked when I had this problem with an Android 2.2 phone, and also an Android 3.1 tablet.

"The specified Android SDK Build Tools version (26.0.0) is ignored..."

Many times as API's are updated. We forgot to update SDK Managers. For accessing recent API's one should always have highest API Level updated if possible should also have other regularly used lower level APIs to accommodate backward compatibility.
Go to build.gradle (module.app) file change compileSdkVersion buildToolsVersion targetSdkVersion, all should have the highest level of API.

Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

This means that you must declare strict mode by writing "use strict" at the beginning of the file or the function to use block-scope declarations.

EX:

function test(){
    "use strict";
    let a = 1;
} 

How can I convert a date into an integer?

var dates = dates_as_int.map(function(dateStr) {
    return new Date(dateStr).getTime();
});

=>

[1468959781804, 1469029434776, 1469199218634, 1469457574527]

Update: ES6 version:

const dates = dates_as_int.map(date => new Date(date).getTime())

Get data from fs.readFile

Use the built in promisify library (Node 8+) to make these old callback functions more elegant.

const fs = require('fs');
const util = require('util');

const readFile = util.promisify(fs.readFile);

async function doStuff() {
  try {
    const content = await readFile(filePath, 'utf8');
    console.log(content);
  } catch (e) {
    console.error(e);
  }
}

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

Thanks. Helped me a lot. Converted to Swift 3 and worked

To save: let data = UIImagePNGRepresentation(image)

To load: let image = UIImage(data: data)

How to run a class from Jar which is not the Main-Class in its Manifest file

First of all jar creates a jar, and does not run it. Try java -jar instead.

Second, why do you pass the class twice, as FQCN (com.mycomp.myproj.dir2.MainClass2) and as file (com/mycomp/myproj/dir2/MainClass2.class)?

Edit:

It seems as if java -jar requires a main class to be specified. You could try java -cp your.jar com.mycomp.myproj.dir2.MainClass2 ... instead. -cp sets the jar on the classpath and enables java to look up the main class there.

PDO closing connection

$conn=new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);
    // If this is your connection then you have to assign null
    // to your connection variable as follows:
$conn=null;
    // By this way you can close connection in PDO.

why numpy.ndarray is object is not callable in my simple for python loop

Avoid the for loopfor XY in xy: Instead read up how the numpy arrays are indexed and handled.

Numpy Indexing

Also try and avoid .txt files if you are dealing with matrices. Try to use .csv or .npy files, and use Pandas dataframework to load them just for clarity.

Convert a JSON string to object in Java ME?

I used a few of them and my favorite is,

http://code.google.com/p/json-simple/

The library is very small so it's perfect for J2ME.

You can parse JSON into Java object in one line like this,

JSONObject json = (JSONObject)new JSONParser().parse("{\"name\":\"MyNode\", \"width\":200, \"height\":100}");
System.out.println("name=" + json.get("name"));
System.out.println("width=" + json.get("width"));

How do I tar a directory of files and folders without including the directory itself?

Have a look at --transform/--xform, it gives you the opportunity to massage the file name as the file is added to the archive:

% mkdir my_directory
% touch my_directory/file1
% touch my_directory/file2
% touch my_directory/.hiddenfile1
% touch my_directory/.hiddenfile2
% tar -v -c -f my_dir.tgz --xform='s,my_directory/,,' $(find my_directory -type f)
my_directory/file2
my_directory/.hiddenfile1
my_directory/.hiddenfile2
my_directory/file1
% tar -t -f my_dir.tgz 
file2
.hiddenfile1
.hiddenfile2
file1

Transform expression is similar to that of sed, and we can use separators other than / (, in the above example).
https://www.gnu.org/software/tar/manual/html_section/tar_52.html

Reverse Contents in Array

I would use the reverse() function from the <algorithm> library.

Run it online: repl.it/@abranhe/Reverse-Array

#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
  int arr [10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

  reverse(begin(arr), end(arr));

  for(auto item:arr)
  {
    cout << item << " ";
  }
}

Output:

10 9 8 7 6 5 4 3 2 1

Hope you like this approach.

Can you set a border opacity in CSS?

Unfortunately the opacity element makes the whole element (including any text) semi-transparent. The best way to make the border semi-transparent is with the rgba color format. For example, this would give a red border with 50% opacity:

div {
    border: 1px solid rgba(255, 0, 0, .5);
    -webkit-background-clip: padding-box; /* for Safari */
    background-clip: padding-box; /* for IE9+, Firefox 4+, Opera, Chrome */
}

The problem with this approach is that some browsers do not understand the rgba format and will not display any border at all if this is the entire declaration. The solution is to provide two border declarations. The first with a fake opacity, and the second with the actual. If a browser is capable, it will use the second, if not, it will use the first.

div {
    border: 1px solid rgb(127, 0, 0);
    border: 1px solid rgba(255, 0, 0, .5);
    -webkit-background-clip: padding-box; /* for Safari */
    background-clip: padding-box; /* for IE9+, Firefox 4+, Opera, Chrome */
}

The first border declaration will be the equivalent color to a 50% opaque red border over a white background (although any graphics under the border will not bleed through).

UPDATE: I've added "background-clip: padding-box;" to this answer (per SooDesuNe's suggestion in the comments) to ensure the border remains transparent even if a solid background color is applied.

Qt. get part of QString

If you do not need to modify the substring, then you can use QStringRef. The QStringRef class is a read only wrapper around an existing QString that references a substring within the existing string. This gives much better performance than creating a new QString object to contain the sub-string. E.g.

QString myString("This is a string");
QStringRef subString(&myString, 5, 2); // subString contains "is"

If you do need to modify the substring, then left(), mid() and right() will do what you need...

QString myString("This is a string");
QString subString = myString.mid(5,2); // subString contains "is"
subString.append("n't"); // subString contains "isn't"

How do I get the name of the active user via the command line in OS X?

getting username in MAC terminal is easy...

I generally use whoami in terminal...

For example, in this case, I needed that to install Tomcat Server...

enter image description here

Inputting a default image in case the src attribute of an html <img> is not valid?

If you're using Angular/jQuery then this might help...

<img ng-src="{{item.url}}" altSrc="{{item.alt_url}}" onerror="this.src = $(this).attr('altSrc')">

Explanation

Assuming that item has a property url that might be null, when it is then the image will show up as broken. That triggers execution of onerror attribute expression, as described above. You need to override the src attribute as described above, but you will need jQuery to access your altSrc. Couldn't get it to work with vanilla JavaScript.

Might seem a little hacky but saved the day on my project.

Combining multiple commits before pushing in Git

And my way of squashing multiple push is (perhaps you pushed to your own branch many commits and now you wish to do a pull request and you don't want to clutter them with many commits which you have already pushed). The way I do that (no other simpler option as far as I can tell is).

  1. Create new branch for the sake of squash (branch from the original branch you wish to pull request to).
  2. Push the newly created branch.
  3. Merge branch with commits (already pushed) to new branch.
  4. Rebase new branch and squash.
  5. Push new branch.
  6. Create new pull request for new branch which now has single commit.

Example:

git checkout from_branch_you_wish_to_pull_request_to
git checkout -b new_branch_will_have_single_squashed_commit
git push -u new_branch_will_have_single_squashed_commit
git merge older_branch_with_all_those_multiple_commits
git rebase -i (here you squash)
git push origin new_branch_will_have_single_squashed_commit

You can now pull request into from_branch_you_wish_to_pull_request_to

How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?

Just need to add: new SimpleDateFormat("bla bla bla", Locale.US)

public static void main(String[] args) throws ParseException {
    java.util.Date fecha = new java.util.Date("Mon Dec 15 00:00:00 CST 2014");
    DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);
    Date date;
    date = (Date)formatter.parse(fecha.toString());
    System.out.println(date);        

    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    String formatedDate = cal.get(Calendar.DATE) + "/" + 
            (cal.get(Calendar.MONTH) + 1) + 
            "/" +         cal.get(Calendar.YEAR);
    System.out.println("formatedDate : " + formatedDate);
}

Redirect to Action by parameter mvc

Try this,

return RedirectToAction("ActionEventName", "Controller", new { ID = model.ID, SiteID = model.SiteID });

Here i mention you are pass multiple values or model also. That's why here i mention that.

What is the fastest factorial function in JavaScript?

This is a compact loop-based version

function factorial( _n )
{
    var _p = 1 ;
    while( _n > 0 ) { _p *= _n-- ; }
    return _p ;
}

Or you might override Math object (recursive version):

Math.factorial = function( _x )  { return _x <= 1 ? 1 : _x * Math.factorial( --_x ) ; }

Or join both approaches ...

Google Maps v3 - limit viewable area and zoom level

For some reason

if (strictBounds.contains(map.getCenter())) return;

didnt work for me (maybe a southern hemisphere issue). I had to change it to:

    function checkBounds() {
        var c = map.getCenter(),
            x = c.lng(),
            y = c.lat(),
            maxX = strictBounds.getNorthEast().lng(),
            maxY = strictBounds.getNorthEast().lat(),
            minX = strictBounds.getSouthWest().lng(),
            minY = strictBounds.getSouthWest().lat();

        if(x < minX || x > maxX || y < minY || y > maxY) {
            if (x < minX) x = minX;
            if (x > maxX) x = maxX;
            if (y < minY) y = minY;
            if (y > maxY) y = maxY;
            map.setCenter(new google.maps.LatLng(y, x));
        }
    }

Hope it will help someone.

String, StringBuffer, and StringBuilder

  • You use String when an immutable structure is appropriate; obtaining a new character sequence from a String may carry an unacceptable performance penalty, either in CPU time or memory (obtaining substrings is CPU efficient because the data is not copied, but this means a potentially much larger amount of data may remain allocated).
  • You use StringBuilder when you need to create a mutable character sequence, usually to concatenate several character sequences together.
  • You use StringBuffer in the same circumstances you would use StringBuilder, but when changes to the underlying string must be synchronized (because several threads are reading/modifyind the string buffer).

See an example here.

Check box size change with CSS

You might want to do this.

input[type=checkbox] {

 -ms-transform: scale(2); /* IE */
 -moz-transform: scale(2); /* FF */
 -webkit-transform: scale(2); /* Safari and Chrome */
 -o-transform: scale(2); /* Opera */
  padding: 10px;
}

How to host a Node.Js application in shared hosting

You should look for a hosting company that provides such feature, but standard simple static+PHP+MySQL hosting won't let you use node.js.

You need either find a hosting designed for node.js or buy a Virtual Private Server and install it yourself.

Call and receive output from Python script in Java?

I met the same problem before, also read the answers here, but doesn't found any satisfy solution can balance the compatibility, performance and well format output, the Jython can't work with extend C packages and slower than CPython. So finally I decided to invent the wheel myself, it took my 5 nights, I hope it can help you too: jpserve(https://github.com/johnhuang-cn/jpserve).

JPserve provides a simple way to call Python and exchange the result by well format JSON, few performance loss. The following is the sample code.

At first, start jpserve on Python side

>>> from jpserve.jpserve import JPServe
>>> serve = JPServe(("localhost", 8888))
>>> serve.start()

INFO:JPServe:JPServe starting...
INFO:JPServe:JPServe listening in localhost 8888

Then call Python from JAVA side:

PyServeContext.init("localhost", 8888);
PyExecutor executor = PyServeContext.getExecutor();
script = "a = 2\n"
    + "b = 3\n"
    + "_result_ = a * b";

PyResult rs = executor.exec(script);
System.out.println("Result: " + rs.getResult());

---
Result: 6

Java String split removed empty values

you may have multiple separators, including whitespace characters, commas, semicolons, etc. take those in repeatable group with []+, like:

 String[] tokens = "a , b,  ,c; ;d,      ".split( "[,; \t\n\r]+" );

you'll have 4 tokens -- a, b, c, d

leading separators in the source string need to be removed before applying this split.

as answer to question asked:

String data = "5|6|7||8|9||";
String[] split = data.split("[\\| \t\n\r]+");

whitespaces added just in case if you'll have those as separators along with |

Center a column using Twitter Bootstrap 3

To center more than one column in a Bootstrap row - and the number of cols are odd, simply add this css class to all the columns in that row:

.many-cols-centered {  // To horizontally center bootstrap odd cols, eg col-lg-9, col-md-3, works well in lg
  display:inline-block;
  float:none;
}

So in your HTML you have something like:

<div class="row text-center"> <!-- text-center centers all text in that row -->
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 many-cols-centered">
        <img src='assets/image1.jpg'>
        <h3>You See</h3>
        <p>I love coding.</p>
    </div>
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 many-cols-centered">
        <img src='assets/image2.jpg'>
        <h3>You See</h3>
        <p>I love coding.</p>
    </div>
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 many-cols-centered">
        <img src='assets/image3.jpg'>
        <h3>You See</h3>
        <p>I love coding.</p>
    </div>
</div>

How to make a <ul> display in a horizontal row

Set the display property to inline for the list you want this to apply to. There's a good explanation of displaying lists on A List Apart.

ng-change not working on a text input

When you want to edit something in Angular you need to insert an ngModel in your html

try this in your sample:

    <input type="text" name="abc" class="color" ng-model="myStyle.color">

You don't need to watch the change at all!

jQuery append() - return appended elements

// wrap it in jQuery, now it's a collection
var $elements = $(someHTML);

// append to the DOM
$("#myDiv").append($elements);

// do stuff, using the initial reference
$elements.effects("highlight", {}, 2000);

What's the best way to dedupe a table?

SELECT DISTINCT <insert all columns but the PK here> FROM foo. Create a temp table using that query (the syntax varies by RDBMS but there's typically a SELECT … INTO or CREATE TABLE AS pattern available), then blow away the old table and pump the data from the temp table back into it.

How do I deal with installing peer dependencies in Angular CLI?

NPM package libraries have a section in the package.json file named peerDependencies. For example; a library built in Angular 8, will usually list Angular 8 as a dependency. This is a true dependency for anyone running less than version 8. But for anyone running version 8, 9 or 10, it's questionable whether any concern should be pursued.

I have been safely ignoring these messages on Angular Updates, but then again we do have Unit and Cypress Tests!

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

How to add multiple columns to pandas dataframe in one assignment?

With the use of concat:

In [128]: df
Out[128]: 
   col_1  col_2
0      0      4
1      1      5
2      2      6
3      3      7

In [129]: pd.concat([df, pd.DataFrame(columns = [ 'column_new_1', 'column_new_2','column_new_3'])])
Out[129]: 
   col_1  col_2 column_new_1 column_new_2 column_new_3
0    0.0    4.0          NaN          NaN          NaN
1    1.0    5.0          NaN          NaN          NaN
2    2.0    6.0          NaN          NaN          NaN
3    3.0    7.0          NaN          NaN          NaN

Not very sure of what you wanted to do with [np.nan, 'dogs',3]. Maybe now set them as default values?

In [142]: df1 = pd.concat([df, pd.DataFrame(columns = [ 'column_new_1', 'column_new_2','column_new_3'])])
In [143]: df1[[ 'column_new_1', 'column_new_2','column_new_3']] = [np.nan, 'dogs', 3]

In [144]: df1
Out[144]: 
   col_1  col_2  column_new_1 column_new_2  column_new_3
0    0.0    4.0           NaN         dogs             3
1    1.0    5.0           NaN         dogs             3
2    2.0    6.0           NaN         dogs             3
3    3.0    7.0           NaN         dogs             3

How to determine if object is in array

Why don't you use the indexOf method of javascript arrays?

Check this out: MDN indexOf Arrays

Simply do:

carBrands.indexOf(car1);

It will return you the index (position in the array) of car1. It will return -1 if car1 was not found in the array.

http://jsfiddle.net/Fraximus/r154cd9o

Edit: Note that in the question, the requirements are to check for the same object referenced in the array, and NOT a new object. Even if the new object is identical in content to the object in the array, it is still a different object. As mentioned in the comments, objects are passed by reference in JS and the same object can exist multiple times in multiple structures.
If you want to create a new object and check if the array contains objects identical to your new one, this answer won't work (Julien's fiddle below), if you want to check for that same object's existence in the array, then this answer will work. Check out the fiddles here and in the comments.

How do I trim() a string in angularjs?

JS .trim() is supported in basically everthing, except IE 8 and below.

If you want it to work with that, then, you can use JQuery, but it'll need to be <2.0.0 (as they removed support for IE8 in the 2.x.x line).

Your other option, if you care about IE7/8 (As you mention earlier), is to add trim yourself:

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

Swift days between two NSDates

I see a couple Swift3 answers so I'll add my own:

public static func daysBetween(start: Date, end: Date) -> Int {
   Calendar.current.dateComponents([.day], from: start, to: end).day!
}

The naming feels more Swifty, it's one line, and using the latest dateComponents() method.

What is the difference between BIT and TINYINT in MySQL?

Might be wrong but:

Tinyint is an integer between 0 and 255

bit is either 1 or 0

Therefore to me bit is the choice for booleans

Why do we assign a parent reference to the child object in Java?

I know this is a very old thread but I came across the same doubt once.

So the concept of Parent parent = new Child(); has something to do with early and late binding in java.

The binding of private, static and final methods happen at the compile as they cannot be overridden and the normal method calls and overloaded methods are example of early binding.

Consider the example:

class Vehicle
{
    int value = 100;
    void start() {
        System.out.println("Vehicle Started");
    }

    static void stop() {
        System.out.println("Vehicle Stopped");
    }
}

class Car extends Vehicle {

    int value = 1000;

    @Override
    void start() {
        System.out.println("Car Started");
    }

    static void stop() {
        System.out.println("Car Stopped");
    }

    public static void main(String args[]) {

        // Car extends Vehicle
        Vehicle vehicle = new Car();
        System.out.println(vehicle.value);
        vehicle.start();
        vehicle.stop();
    }
}

Output: 100

Car Started

Vehicle Stopped

This is happening because stop() is a static method and cannot be overridden. So binding of stop() happens at compile time and start() is non-static is being overridden in child class. So, the information about type of object is available at the run time only(late binding) and hence the start() method of Car class is called.

Also in this code the vehicle.value gives us 100 as the output because variable initialization doesn't come under late binding. Method overriding is one of the ways in which java supports run time polymorphism.

  • When an overridden method is called through a superclass reference, Java determines which version(superclass/subclasses) of that method is to be executed based upon the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time.
  • At run-time, it depends on the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed

I hope this answers where Parent parent = new Child(); is important and also why you weren't able to access the child class variable using the above reference.

Get the value of bootstrap Datetimepicker in JavaScript

Either use:

$("#datetimepicker1").data("datetimepicker").getDate();

Or (from looking at the page source):

$("#datetimepicker1").find("input").val();

The returned value will be a Date (for the first example above), so you need to format it yourself:

var date = $("#datetimepicker1").data("datetimepicker").getDate(),
    formatted = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours + ":" + date.getMinutes() + ":" + date.getSeconds();
alert(formatted);

Also, you could just set the format as an attribute:

<div id="datetimepicker1" class="date">
    <input data-format="yyyy-MM-dd hh:mm:ss" type="text"></input>
</div>

and you could use the $("#datetimepicker1").find("input").val();

What does java.lang.Thread.interrupt() do?

If the targeted thread has been waiting (by calling wait(), or some other related methods that essentially do the same thing, such as sleep()), it will be interrupted, meaning that it stops waiting for what it was waiting for and receive an InterruptedException instead.

It is completely up to the thread itself (the code that called wait()) to decide what to do in this situation. It does not automatically terminate the thread.

It is sometimes used in combination with a termination flag. When interrupted, the thread could check this flag, and then shut itself down. But again, this is just a convention.

git: fatal: I don't handle protocol '??http'

My solution:

  1. Type: git clone .
  2. Copy the repository url and paste it after of git clone .
  3. Move the cursor to position between git clone and https://... .
  4. Delete space if it had between git clone and https://... until have git clonehttps://...
  5. Re-add the space and press Enter.

CSS: Position text in the middle of the page

Here's a method using display:flex:

_x000D_
_x000D_
.container {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  display: flex;_x000D_
  position: fixed;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div>centered text!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

View on Codepen
Check Browser Compatability

Volley JsonObjectRequest Post request not working

It worked for can try this for calling with Volley Json Request and Response ith Java Code .

public void callLogin(String sMethodToCall, String sUserId, String sPass) {
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
                Request.Method.POST, ConstantValues.ROOT_URL_LOCAL + sMethodToCall.toString().trim(), addJsonParams(sUserId, sPass),
//                JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, object,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("onResponse", response.toString());
                        Toast.makeText(VolleyMethods.this, response.toString(), Toast.LENGTH_LONG).show(); // Test

                        parseResponse(response);
//                        msgResponse.setText(response.toString());
//                        hideProgressDialog();
                    }
                },
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d("onErrorResponse", "Error: " + error.getMessage());
                        Toast.makeText(VolleyMethods.this, error.toString(), Toast.LENGTH_LONG).show();
//                hideProgressDialog();
                    }
                }) {

            /**
             * Passing some request headers
             */
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/json; charset=utf-8");
                return headers;
            }


        };

        requestQueue.add(jsonObjectRequest);
    }

    public JSONObject addJsonParams(String sUserId, String sPass) {
        JSONObject jsonobject = new JSONObject();
        try {
//            {"id":,"login":"secretary","password":"password"}

            ///***//
            Log.d("addJsonParams", "addJsonParams");

//            JSONObject jsonobject = new JSONObject();

//            JSONObject jsonobject_one = new JSONObject();
//
//            jsonobject_one.put("type", "event_and_offer");
//            jsonobject_one.put("devicetype", "I");
//
//            JSONObject jsonobject_TWO = new JSONObject();
//            jsonobject_TWO.put("value", "event");
//            JSONObject jsonobject = new JSONObject();
//
//            jsonobject.put("requestinfo", jsonobject_TWO);
//            jsonobject.put("request", jsonobject_one);

            jsonobject.put("id", "");
            jsonobject.put("login", sUserId); // sUserId
            jsonobject.put("password", sPass); // sPass


//            js.put("data", jsonobject.toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return jsonobject;
    }

    public void parseResponse(JSONObject response) {

        Boolean bIsSuccess = false; // Write according to your logic this is demo.
        try {
            JSONObject jObject = new JSONObject(String.valueOf(response));
            bIsSuccess = jObject.getBoolean("success");


        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(VolleyMethods.this, "" + e.toString(), Toast.LENGTH_LONG).show(); // Test
        }

    }

Want to upgrade project from Angular v5 to Angular v6

This is how I make it work.

My Environment:

Angular CLI Global : 6.0.0, Local: 1.7.4, Angular: 5.2, Typescript 2.5.3

Note: To enable ng Update you need to install Angular CLI 6.0 first npm install -g @angular/cli or npm install @angular/cli

  1. ng update //update Angular Package core/common/complier... to 6.0.0

  2. ng update @angular/cli //change angular-cli.json to angular.json

optional if you have angular-material 5.4.2, ngx-translate 9.1.1, ng-bootstrap/ng-bootstrap 1.1.1:

  1. ng update @angular/material //upgrade to 6.0.1

  2. npm install @ngx-translate/[email protected] --save //upgrade ngX translate to 10.0.1 for Angular 6

5 npm install --save @ng-bootstrap/[email protected] //for ng-bootstrap

If you use Observable and get the error:

ERROR in node_modules/rxjs/Observable.d.ts(1,15): error TS2307: Cannot find module 'rxjs-compat/Observable'. node_modules/rxjs/observable/of.d.ts(1,15): error TS2307: Cannot find module 'rxjs-compat/observable/of'.

Change: import { Observable } from "rxjs/Observable"; import { of } from 'rxjs/observable/of';

To

import { Observable, of } from "rxjs";

Angular CLI issue: https://github.com/angular/angular-cli/issues/10621

How to move the cursor word by word in the OS X Terminal

In Bash, these are bound to Esc-B and Esc-F. Bash has many, many more keyboard shortcuts; have a look at the output of bind -p to see what they are.

Objective C - Assign, Copy, Retain

  1. assign

    • assign is a default property attribute
    • assign is a property attribute tells the compiler how to synthesize the property’s setter implementation
  2. copy:

    • copy is required when the object is mutable
    • copy returns an object which you must explicitly release (e.g., in dealloc) in non-garbage collected environments
    • you need to release the object when finished with it because you are retaining the copy
  3. retain:

    • specifies the new value should be sent “-retain” on assignment and the old value sent “-release”
    • if you write retain it will auto work like strong
    • Methods like “alloc” include an implicit “retain”

Dynamically load JS inside JS

You can do it using JQuery:

$.getScript("ajax/test.js", function(data, textStatus, jqxhr) {
  console.log(data); //data returned
  console.log(textStatus); //success
  console.log(jqxhr.status); //200
  console.log('Load was performed.');
});

this link should help: http://api.jquery.com/jQuery.getScript/

Resetting MySQL Root Password with XAMPP on Localhost

For me much better way is to do it using terminal rather then PhpMyAdmin UI.

The answer is copied from "https://gist.github.com/susanBuck/39d1a384779f3d596afb19fcad6b598c" which I have tried and it works always, try it out..

  • Open C:\xampp\mysql\bin\my.ini (MySQL config file)
  • Find the line [mysqld] and right below it add skip-grant-tables. Example:

    [mysqld] skip-grant-tables port= 3306 socket = "C:/xampp/mysql/mysql.sock" basedir = "C:/xampp/mysql" tmpdir = "C:/xampp/tmp" [...etc...]

  • This should allow you to access MySQL if you don't know your password.

  • Stop and start MySQL from XAMPP to make this change take effect.
  • Next, in command line, connect to MySQL:

C:\xampp\mysql\bin\mysql.exe --user=root

  • Once in MySQL command line "select" the mysql database:

USE mysql;

  • Then, the following command will list all your MySQL users:

SELECT * FROM user \G;

  • You can scan through the rows to see what the root user's password is set to. There will be a few root users listed, with different hosts.
  • To set root user's to have a password of your choice, run this command:

UPDATE user SET password = PASSWORD('secret_pass') WHERE user = 'root';

  • -OR- To set all root user's to have a blank password, run this command:

UPDATE user SET password = '' WHERE user = 'root';

When you're done, run exit; to exit the MySQL command line.

Next, re-enable password checking by removing skip-grant-tables from C:\xampp\mysql\bin\my.ini.

Save changes, restart MySQL from XAMPP.

Update TextView Every Second

Use TextSwitcher (for nice text transition animation) and timer instead.

CSS @media print issues with background-color;

If you are looking to create "printer friendly" pages, I recommend adding "!important" to your @media print CSS. This encourages most browsers to print your background images, colors, etc.

EXAMPLES:

background:#3F6CAF url('example.png') no-repeat top left !important;
background-color: #3F6CAF !important;

Invalidating JSON Web Tokens

In this example, I am assuming the end user also has an account. If this isn't he case, then the rest of the approach is unlikely to work.

When you create the JWT, persist it in the database, associated with the account that is logging in. This does mean that just from the JWT you could pull out additional information about the user, so depending on the environment, this may or may not be OK.

On every request after, not only do you perform the standard validation that (I hope) comes with what ever framework you use (that validates the JWT is valid), it also includes soemthing like the user ID or another token (that needs to match that in the database).

When you log out, delete the cookie (if using) and invalidate the JWT (string) from the database. If the cookie can't be deleted from the client side, then at least the log out process will ensure the token is destroyed.

I found this approach, coupled with another unique identifier (so there are 2 persist items in the database and are available to the front end) with the session to be very resilient

Recommended way to embed PDF in HTML?

Probably the best approach is to use the PDF.JS library. It's a pure HTML5/JavaScript renderer for PDF documents without any third-party plugins.

Online demo: http://mozilla.github.com/pdf.js/web/viewer.html

GitHub: https://github.com/mozilla/pdf.js

how to stop a running script in Matlab

Consider having multiple matlab sessions. Keep the main session window (the pretty one with all the colours, file manager, command history, workspace, editor etc.) for running stuff that you know will terminate.

Stuff that you are experimenting with, say you are messing with ode suite and you get lots of warnings: matrix singular, because you altered some parameter and didn't predict what would happen, run in a separate session:

dos('matlab -automation -r &')

You can kill that without having to restart the whole of Matlab.

What's the easy way to auto create non existing dir in ansible

AFAIK, the only way this could be done is by using the state=directory option. While template module supports most of copy options, which in turn supports most file options, you can not use something like state=directory with it. Moreover, it would be quite confusing (would it mean that {{project_root}}/conf/code.conf is a directory ? or would it mean that {{project_root}}/conf/ should be created first.

So I don't think this is possible right now without adding a previous file task.

- file: 
    path: "{{project_root}}/conf"
    state: directory
    recurse: yes

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

In case you are using NodeJS/Express as back-end and ReactJS/axios as front-end within a development environment in MacOS, you need to run both sides under https. Below is what it finally worked for me (after many hours of deep dive & testing):

Step 1: Create an SSL certificate

Just follow the steps from How to get HTTPS working on your local development environment in 5 minutes

You will end up with a couple of files to be used as credentials to run the https server and ReactJS web:

server.key & server.crt

You need to copy them in the root folders of both the front and back ends (in a Production environment, you might consider copying them in ./ssh for the back-end).

Step 2: Back-end setup

I read a lot of answers proposing the use of 'cors' package or even setting ('Access-Control-Allow-Origin', '*'), which is like saying: "Hackers are welcome to my website". Just do like this:

import express from 'express';
const emailRouter = require('./routes/email');  // in my case, I was sending an email through a form in ReactJS
const fs = require('fs');
const https = require('https');

const app = express();
const port = 8000;

// CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests
app.all('*', (req, res, next) => {
    res.header("Access-Control-Allow-Origin", "https://localhost:3000");
    next();
});

// Routes definition
app.use('/email', emailRouter);

// HTTPS server
const credentials = {
  key: fs.readFileSync('server.key'),
  cert: fs.readFileSync('server.crt')
};

const httpsServer = https.createServer(credentials, app);
httpsServer.listen(port, () => {
    console.log(`Back-end running on port ${port}`);
});

In case you want to test if the https is OK, you can replace the httpsServer constant by the one below:

https.createServer(credentials, (req: any, res: any) => {
  res.writeHead(200);
  res.end("hello world from SSL\n");
}).listen(port, () => {
  console.log(`HTTPS server listening on port ${port}...`);
});

And then access it from a web browser: https://localhost:8000/

Step 3: Front-end setup

This is the axios request from the ReactJS front-end:

    await axios.get(`https://localhost:8000/email/send`, {
        params: {/* whatever data you want to send */ },
        headers: {
            'Content-Type': 'application/json',
        }
    })

And now, you need to launch your ReactJS web in https mode using the credentials for SSL we already created. Type this in your MacOS terminal:

HTTPS=true SSL_CRT_FILE=server.crt SSL_KEY_FILE=server.key npm start

At this point, you are sending a request from an https connection at port 3000 from your front-end, to be received by an https connection at port 8000 by your back-end. CORS should be happy with this ;)

Valid characters in a Java class name

You can have almost any character, including most Unicode characters! The exact definition is in the Java Language Specification under section 3.8: Identifiers.

An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. ...

Letters and digits may be drawn from the entire Unicode character set, ... This allows programmers to use identifiers in their programs that are written in their native languages.

An identifier cannot have the same spelling (Unicode character sequence) as a keyword (§3.9), boolean literal (§3.10.3), or the null literal (§3.10.7), or a compile-time error occurs.

However, see this question for whether or not you should do that.