Programs & Examples On #Service operations

How to upgrade Angular CLI project?

Solution that worked for me:

  • Delete node_modules and dist folder
  • (in cmd)>> ng update --all --force
  • (in cmd)>> npm install typescript@">=3.4.0 and <3.5.0" --save-dev --save-exact
  • (in cmd)>> npm install --save core-js
  • Commenting import 'core-js/es7/reflect'; in polyfill.ts
  • (in cmd)>> ng serve

How to 'restart' an android application programmatically

Checkout intent properties like no history , clear back stack etc ... Intent.setFlags

Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);

Error: Uncaught (in promise): Error: Cannot match any routes Angular 2

I also had the same issue. Tried all ways and it didn't work out until I added the following in app.module.ts

import { Ng4LoadingSpinnerModule } from 'ng4-loading-spinner';

And add the following in your imports in app.module.ts

Ng4LoadingSpinnerModule.forRoot()

This case might be rare but I hope this helps someone out there

Twitter Bootstrap 3: How to center a block

It's new in the Bootstrap 3.0.1 release, so make sure you have the latest (10/29)...

Demo: http://bootply.com/91632

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="row">_x000D_
    <div class="center-block" style="width:200px;background-color:#ccc;">...</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What browsers support HTML5 WebSocket API?

Client side

  • Hixie-75:
    • Chrome 4.0 + 5.0
    • Safari 5.0.0
  • HyBi-00/Hixie-76:
  • HyBi-07+:
  • HyBi-10:
    • Chrome 14.0 + 15.0
    • Firefox 7.0 + 8.0 + 9.0 + 10.0 - prefixed: MozWebSocket
    • IE 10 (from Windows 8 developer preview)
  • HyBi-17/RFC 6455
    • Chrome 16
    • Firefox 11
    • Opera 12.10 / Opera Mobile 12.1

Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.

See caniuse for the current status of WebSockets support in desktop and mobile browsers.

See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.


Server side

It depends on which language you use.

In Java/Java EE:

Some other Java implementations:

In C#:

In PHP:

In Python:

In C:

In Node.js:

  • Socket.io : Socket.io also has serverside ports for Python, Java, Google GO, Rack
  • sockjs : sockjs also has serverside ports for Python, Java, Erlang and Lua
  • WebSocket-Node - Pure JavaScript Client & Server implementation of HyBi-10.

Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :

  • Support for Ruby(JRuby), Java, Groovy, Javascript(Rhino/Nashorn), Scala, ...
  • True threading. (unlike Node.js)
  • Understands multiple network protocols out of the box including: TCP, SSL, UDP, HTTP, HTTPS, Websockets, SockJS as fallback for WebSockets

Pusher.com is a Websocket cloud service accessible through a REST API.

DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.

Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.

For other language implementations, see the Wikipedia article for more information.

The RFC for Websockets : RFC6455

Does VBA contain a comment block syntax?

prefix the comment with a single-quote. there is no need for an "end" tag.

'this is a comment

Extend to multiple lines using the line-continuation character, _:

'this is a multi-line _
   comment

This is an option in the toolbar to select a line(s) of code and comment/uncomment:

enter image description here

How do I detect whether a Python variable is a function?

Whatever function is a class so you can take the name of the class of instance x and compare:


if(x.__class__.__name__ == 'function'):
     print "it's a function"

Accuracy Score ValueError: Can't Handle mix of binary and continuous target

Just use

y_pred = (y_pred > 0.5)
accuracy_score(y_true, y_pred, normalize=False)

Find which version of package is installed with pip

import pkg_resources
packages = [dist.project_name for dist in pkg_resources.working_set]
try:
   for count, item in enumerate(packages):
      print(item, pkg_resources.get_distribution(item).version)
except:
    pass here

The indentations might not be perfect. The reason I am using a Try- Except block is that few library names will throw errors because of parsing the library names to process the versions. even though packages variable will contain all the libraries install in your environment.

How to use `@ts-ignore` for a block

If you don't need typesafe, just bring block to a new separated file and change the extension to .js,.jsx

ToList().ForEach in Linq

You shouldn't use ForEach in that way. Read Lippert's “foreach” vs “ForEach”

If you want to be cruel with yourself (and the world), at least don't create useless List

employees.All(p => {
    collection.AddRange(p.Departments);
    p.Departments.All(u => { u.SomeProperty = null; return true; } );
    return true;
});

Note that the result of the All expression is a bool value that we are discarding (we are using it only because it "cycles" all the elements)

I'll repeat. You shouldn't use ForEach to change objects. LINQ should be used in a "functional" way (you can create new objects but you can't change old objects nor you can create side-effects). And what you are writing is creating so many useless List only to gain two lines of code...

How do I get 'date-1' formatted as mm-dd-yyyy using PowerShell?

This is the most simple solution for me:

just the current date

$tStamp = Get-Date -format yyyy_MM_dd_HHmmss

current date with some months added

$tStamp = Get-Date (get-date).AddMonths(6).Date -Format yyyyMMdd

Brackets.io: Is there a way to auto indent / format <html>

I've been playing around with the preferences and added the following to my brackets.json file (access in Menu Bar: Debug: "Open Preferences File").

"closeTags": { "dontCloseTags": ["br", "hr", "img", "input", "link", "meta", "area", "base", "col", "command", "embed", "keygen", "param", "source", "track", "wbr"], "indentTags": ["ul", "ol", "div", "section", "table", "tr"], }

  • dontCloseTags are tags such as <br> which shouldn't be closed.
  • indentTags are tags that you want to automatically create a new indented line - add more as needed!
  • (any tags that aren't in above arrays will self-close on the same line)

Excel to JSON javascript code?

The answers are working fine with xls format but, in my case, it didn't work for xlsx format. Thus I added some code here. it works both xls and xlsx format.

I took the sample from the official sample link.

Hope it may help !

function fileReader(oEvent) {
        var oFile = oEvent.target.files[0];
        var sFilename = oFile.name;

        var reader = new FileReader();
        var result = {};

        reader.onload = function (e) {
            var data = e.target.result;
            data = new Uint8Array(data);
            var workbook = XLSX.read(data, {type: 'array'});
            console.log(workbook);
            var result = {};
            workbook.SheetNames.forEach(function (sheetName) {
                var roa = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {header: 1});
                if (roa.length) result[sheetName] = roa;
            });
            // see the result, caution: it works after reader event is done.
            console.log(result);
        };
        reader.readAsArrayBuffer(oFile);
}

// Add your id of "File Input" 
$('#fileUpload').change(function(ev) {
        // Do something 
        fileReader(ev);
}

Parse usable Street Address, City, State, Zip from a string

I think outsourcing the problem is the best bet: send it to the Google (or Yahoo) geocoder. The geocoder returns not only the lat/long (which aren't of interest here), but also a rich parsing of the address, with fields filled in that you didn't send (including ZIP+4 and county).

For example, parsing "1600 Amphitheatre Parkway, Mountain View, CA" yields

{
  "name": "1600 Amphitheatre Parkway, Mountain View, CA, USA",
  "Status": {
    "code": 200,
    "request": "geocode"
  },
  "Placemark": [
    {
      "address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
      "AddressDetails": {
        "Country": {
          "CountryNameCode": "US",
          "AdministrativeArea": {
            "AdministrativeAreaName": "CA",
            "SubAdministrativeArea": {
              "SubAdministrativeAreaName": "Santa Clara",
              "Locality": {
                "LocalityName": "Mountain View",
                "Thoroughfare": {
                  "ThoroughfareName": "1600 Amphitheatre Pkwy"
                },
                "PostalCode": {
                  "PostalCodeNumber": "94043"
                }
              }
            }
          }
        },
        "Accuracy": 8
      },
      "Point": {
        "coordinates": [-122.083739, 37.423021, 0]
      }
    }
  ]
}

Now that's parseable!

equals vs Arrays.equals in Java

array1.equals(array2) is the same as array1 == array2, i.e. is it the same array. As @alf points out it's not what most people expect.

Arrays.equals(array1, array2) compares the contents of the arrays.


Similarly array.toString() may not be very useful and you need to use Arrays.toString(array).

AngularJS accessing DOM elements inside directive template

You could write a directive for this, which simply assigns the (jqLite) element to the scope using an attribute-given name.

Here is the directive:

app.directive("ngScopeElement", function () {
  var directiveDefinitionObject = {

    restrict: "A",

    compile: function compile(tElement, tAttrs, transclude) {
      return {
          pre: function preLink(scope, iElement, iAttrs, controller) {
            scope[iAttrs.ngScopeElement] = iElement;
          }
        };
    }
  };

  return directiveDefinitionObject;
});

Usage:

app.directive("myDirective", function() {
    return {
        template: '<div><ul ng-scope-element="list"><li ng-repeat="item in items"></ul></div>',
        link: function(scope, element, attrs) {
            scope.list[0] // scope.list is the jqlite element, 
                          // scope.list[0] is the native dom element
        }
    }
});

Some remarks:

  • Due to the compile and link order for nested directives you can only access scope.list from myDirectives postLink-Function, which you are very likely using anyway
  • ngScopeElement uses a preLink-function, so that directives nested within the element having ng-scope-element can already access scope.list
  • not sure how this behaves performance-wise

Truncate a string straight JavaScript

in case you want to truncate by word.

_x000D_
_x000D_
function limit(str, limit, end) {_x000D_
_x000D_
      limit = (limit)? limit : 100;_x000D_
      end = (end)? end : '...';_x000D_
      str = str.split(' ');_x000D_
      _x000D_
      if (str.length > limit) {_x000D_
        var cutTolimit = str.slice(0, limit);_x000D_
        return cutTolimit.join(' ') + ' ' + end;_x000D_
      }_x000D_
_x000D_
      return str.join(' ');_x000D_
    }_x000D_
_x000D_
    var limit = limit('ILorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus metus magna, maximus a dictum et, hendrerit ac ligula. Vestibulum massa sapien, venenatis et massa vel, commodo elementum turpis. Nullam cursus, enim in semper luctus, odio turpis dictum lectus', 20);_x000D_
_x000D_
    console.log(limit);
_x000D_
_x000D_
_x000D_

Connecting to SQL Server using windows authentication

This worked for me:

in web.config file;

<add name="connectionstring name " connectionstring="server=SQLserver name; database= databasename; integrated security = true"/>

unable to set private key file: './cert.pem' type PEM

I had the same issue, eventually I found a solution that works without splitting the file, by following Petter Ivarrson's answer

My problem was when converting .p12 certificate to .pem. I used:

openssl pkcs12 -in cert.p12 -out cert.pem

This converts and exports all certificates (CA + CLIENT) together with a private key into one file.

The problem was when I tried to verify if the hashes of certificate and key are matching by running:

// Get certificate HASH
openssl x509 -noout -modulus -in cert.pem | openssl md5

// Get private key HASH
openssl rsa -noout -modulus -in cert.pem | openssl md5

This displayed different hashes and that was the reason CURL failed. See here: https://michaelheap.com/curl-58-unable-to-set-private-key-file-server-key-type-pem/

I guess that was because all certificates are inside a file (CA + CLIENT) and CURL takes CA certificate instead of CLIENT one. Because CA is first in the list.

So the solution was to export only CLIENT certificate together with private key:

openssl pkcs12 -in cert.p12 -out cert.pem -clcerts
``

Now when I re-run the verification:
```sh
openssl x509 -noout -modulus -in cert.pem | openssl md5
openssl rsa -noout -modulus -in cert.pem | openssl md5

HASHES MATCHED !!!

So I was able to make a curl request by running

curl -ivk --cert ./cert.pem:KeyChoosenByMeWhenIrunOpenSSL https://thesite.com

without problems!!!

That being said... I think the best solution is to split the certificates into separate file and use them separately like Petter Ivarsson wrote:

curl --insecure --key key.pem --cacert ca.pem --cert client.pem:KeyChoosenByMeWhenIrunOpenSSL https://thesite.com

Iterate through string array in Java

    String[] nameArray= {"John", "Paul", "Ringo", "George"};
    int numberOfItems = nameArray.length;
    for (int i=0; i<numberOfItems; i++)
    {
        String name = nameArray[i];
        System.out.println("Hello " + name);
    }

Bind failed: Address already in use

I was also facing that problem, but I resolved it. Make sure that both the programs for client-side and server-side are on different projects in your IDE, in my case NetBeans. Then assuming you're using localhost, I recommend you to implement both the programs as two different projects.

CSS selector for first element with class

Could you try something like this:

.red:first-of-type {
    border: 5px solid red;
}

you also can use this for last element (if you need it):

.red:last-of-type {
    border: 5px solid red;
}

How to catch exception correctly from http.request()?

The RxJS functions need to be specifically imported. An easy way to do this is to import all of its features with import * as Rx from "rxjs/Rx"

Then make sure to access the Observable class as Rx.Observable.

RAW POST using cURL in PHP

Implementation with Guzzle library:

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

$httpClient = new Client();

$response = $httpClient->post(
    'https://postman-echo.com/post',
    [
        RequestOptions::BODY => 'POST raw request content',
        RequestOptions::HEADERS => [
            'Content-Type' => 'application/x-www-form-urlencoded',
        ],
    ]
);

echo(
    $response->getBody()->getContents()
);

PHP CURL extension:

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
    CURLOPT_URL => 'https://postman-echo.com/post',
    CURLOPT_RETURNTRANSFER => true,

    /**
     * Specify POST method
     */
    CURLOPT_POST => true,

    /**
     * Specify request content
     */
    CURLOPT_POSTFIELDS => 'POST raw request content',
]);

$response = curl_exec($curlHandler);

curl_close($curlHandler);

echo($response);

Source code

Split data frame string column into multiple columns

Here is another base R solution. We can use read.table but since it accepts only one-byte sep argument and here we have multi-byte separator we can use gsub to replace the multibyte separator to any one-byte separator and use that as sep argument in read.table

cbind(before[1], read.table(text = gsub('_and_', '\t', before$type), 
                 sep = "\t", col.names = paste0("type_", 1:2)))

#  attr type_1 type_2
#1    1    foo    bar
#2   30    foo  bar_2
#3    4    foo    bar
#4    6    foo  bar_2

In this case, we can also make it shorter by replacing it with default sep argument so we don't have to mention it explicitly

cbind(before[1], read.table(text = gsub('_and_', ' ', before$type), 
                 col.names = paste0("type_", 1:2)))

python object() takes no parameters error

I struggled for a while about this. Stupid rule for __init__. It is two "_" together to be "__"

How to debug Angular JavaScript Code

You can add 'debugger' in your code and reload the app, which puts the breakpoint there and you can 'step over' , or run.

var service = {
user_id: null,
getCurrentUser: function() {
  debugger; // Set the debugger inside 
            // this function
  return service.user_id;
}

Object comparison in JavaScript

I have modified a bit the code above. for me 0 !== false and null !== undefined. If you do not need such strict check remove one "=" sign in "this[p] !== x[p]" inside the code.

Object.prototype.equals = function(x){
    for (var p in this) {
        if(typeof(this[p]) !== typeof(x[p])) return false;
        if((this[p]===null) !== (x[p]===null)) return false;
        switch (typeof(this[p])) {
            case 'undefined':
                if (typeof(x[p]) != 'undefined') return false;
                break;
            case 'object':
                if(this[p]!==null && x[p]!==null && (this[p].constructor.toString() !== x[p].constructor.toString() || !this[p].equals(x[p]))) return false;
                break;
            case 'function':
                if (p != 'equals' && this[p].toString() != x[p].toString()) return false;
                break;
            default:
                if (this[p] !== x[p]) return false;
        }
    }
    return true;
}

Then I have tested it with next objects:

var a = {a: 'text', b:[0,1]};
var b = {a: 'text', b:[0,1]};
var c = {a: 'text', b: 0};
var d = {a: 'text', b: false};
var e = {a: 'text', b:[1,0]};
var f = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
var g = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
var h = {a: 'text', b:[1,0], f: function(){ this.a = this.b; }};
var i = {
    a: 'text',
    c: {
        b: [1, 0],
        f: function(){
            this.a = this.b;
        }
    }
};
var j = {
    a: 'text',
    c: {
        b: [1, 0],
        f: function(){
            this.a = this.b;
        }
    }
};
var k = {a: 'text', b: null};
var l = {a: 'text', b: undefined};

a==b expected true; returned true

a==c expected false; returned false

c==d expected false; returned false

a==e expected false; returned false

f==g expected true; returned true

h==g expected false; returned false

i==j expected true; returned true

d==k expected false; returned false

k==l expected false; returned false

How to see the actual Oracle SQL statement that is being executed

-- i use something like this, with concepts and some code stolen from asktom.
-- suggestions for improvements are welcome

WITH
sess AS
(
SELECT *
FROM V$SESSION
WHERE USERNAME = USER
ORDER BY SID
)
SELECT si.SID,
si.LOCKWAIT,
si.OSUSER,
si.PROGRAM,
si.LOGON_TIME,
si.STATUS,
(
SELECT ROUND(USED_UBLK*8/1024,1)
FROM V$TRANSACTION,
sess
WHERE sess.TADDR = V$TRANSACTION.ADDR
AND sess.SID = si.SID

) rollback_remaining,

(
SELECT (MAX(DECODE(PIECE, 0,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 1,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 2,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 3,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 4,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 5,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 6,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 7,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 8,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 9,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 10,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 11,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 12,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 13,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 14,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 15,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 16,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 17,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 18,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 19,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 20,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 21,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 22,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 23,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 24,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 25,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 26,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 27,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 28,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 29,SQL_TEXT,NULL)))
FROM V$SQLTEXT_WITH_NEWLINES
WHERE ADDRESS = SI.SQL_ADDRESS AND
PIECE < 30
) SQL_TEXT
FROM sess si;

'Source code does not match the bytecode' when debugging on a device

You can created AVD, select API Level equal your tagetApi andr compileApi, it works for me.

Complex JSON nesting of objects and arrays

First, choosing a data structure(xml,json,yaml) usually includes only a readability/size problem. For example

Json is very compact, but no human being can read it easily, very hard do debug,

Xml is very large, but everyone can easily read/debug it,

Yaml is in between Xml and json.

But if you want to work with Javascript heavily and/or your software makes a lot of data transfer between browser-server, you should use Json, because it is pure javascript and very compact. But don't try to write it in a string, use libraries to generate the code you needed from an object.

Hope this helps.

How to roundup a number to the closest ten?

the second argument in ROUNDUP, eg =ROUNDUP(12345.6789,3) refers to the negative of the base-10 column with that power of 10, that you want rounded up. eg 1000 = 10^3, so to round up to the next highest 1000, use ,-3)

=ROUNDUP(12345.6789,-4) = 20,000
=ROUNDUP(12345.6789,-3) = 13,000
=ROUNDUP(12345.6789,-2) = 12,400
=ROUNDUP(12345.6789,-1) = 12,350
=ROUNDUP(12345.6789,0) = 12,346
=ROUNDUP(12345.6789,1) = 12,345.7
=ROUNDUP(12345.6789,2) = 12,345.68
=ROUNDUP(12345.6789,3) = 12,345.679

So, to answer your question: if your value is in A1, use =ROUNDUP(A1,-1)

Activity restart on rotation Android

The way I have found to do this is use the onRestoreInstanceState and the onSaveInstanceState events to save something in the Bundle (even if you dont need any variables saved, just put something in there so the Bundle isn't empty). Then, on the onCreate method, check to see if the Bundle is empty, and if it is, then do the initialization, if not, then do it.

How to play .mp4 video in videoview in android?

MP4 is just a container - the video and audio stream inside it will both be encoded in different formats.

Android natively only supports certain types of formats. This is the list here.

Make sure the video and audio encoding type is supported. Just because it says "mp4" doesn't automatically mean it should be playable.

Where is svcutil.exe in Windows 7?

With latest version of windows (e.g. Windows 10, other servers), type/search for "Developers Command prompt.." It will pop up the relevant command prompt for the Visual Studio version.

e.g. Developer Command Prompt for VS 2015

More here https://msdn.microsoft.com/en-us/library/ms229859(v=vs.110).aspx

How do I run a terminal inside of Vim?

Assuming your version of vim supports +term command first, set shell for vim to use in one command (e.g. set=/usr/bin/zsh), and then run the command +term (i.e. bo 15vs +term). you may have to do some additional maneuvering of your windows (i.e. deleting one and rotating), but you'll have your terminal.

Change the background color of a pop-up dialog

You can use a custom style:

  <!-- Alert Dialog -->
  <style name="ThemeOverlay.MaterialComponents.MaterialAlertDialog_Background" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
    <!-- Background Color-->
    <item name="android:background">@color/.....</item>
    <!-- Text Color for title and message -->
    <item name="colorOnSurface">@color/......</item>
    <!-- Style for positive button -->
    <item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
    <!-- Style for negative button -->
    <item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
  </style>

  <style name="PositiveButtonStyle" parent="@style/Widget.MaterialComponents.Button">
    <!-- text color for the button -->
    <item name="android:textColor">@color/.....</item>
    <!-- Background tint for the button -->
    <item name="backgroundTint">@color/primaryDarkColor</item>
  </style>

And just use the default MaterialAlertDialogBuilder:

    new MaterialAlertDialogBuilder(AlertDialogActivity.this,
        R.style.ThemeOverlay_MaterialComponents_MaterialAlertDialog_Background)
        .setTitle("Dialog")
        .setMessage("Message...  ....")
        .setPositiveButton("Ok", /* listener = */ null)
        .show();

enter image description here

Byte Array to Image object

From Database.
Blob blob = resultSet.getBlob("pictureBlob");               
byte [] data = blob.getBytes( 1, ( int ) blob.length() );
BufferedImage img = null;
try {
img = ImageIO.read(new ByteArrayInputStream(data));
} catch (IOException e) {
    e.printStackTrace();
}
drawPicture(img);  //  void drawPicture(Image img);

What is the best way to extract the first word from a string in Java?

import org.apache.commons.lang3.StringUtils;

...
StringUtils.substringBefore("Grigory Kislin", " ")

Can't Autowire @Repository annotated interface in Spring Boot

I had a similar issue where I was receiving NoSuchBeanDefinitionException in Spring Boot (basically while working on CRUD repository), I had to put the below annotations on the main class:

@SpringBootApplication   
@EnableAutoConfiguration
@ComponentScan(basePackages={"<base package name>"})
@EnableJpaRepositories(basePackages="<repository package name>")
@EnableTransactionManagement
@EntityScan(basePackages="<entity package name>")

Also, make sure you have the @Component annotations in place on the implementations.

How to remove the arrow from a select element in Firefox

Important Update:

As of Firefox V35 the appearance property now works !!

From firefox's official release notes on V35:

Using -moz-appearance with the none value on a combobox now remove the dropdown button (bug 649849).

So now in order to hide the default arrow - it's as easy as adding the following rules on our select element:

select {
   -webkit-appearance: none;
   -moz-appearance: none;
   appearance: none;
}

DEMO

_x000D_
_x000D_
select {_x000D_
  margin: 50px;_x000D_
  border: 1px solid #111;_x000D_
  background: transparent;_x000D_
  width: 150px;_x000D_
  padding: 5px;_x000D_
  font-size: 16px;_x000D_
  border: 1px solid #ccc;_x000D_
  height: 34px;_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
  appearance: none;_x000D_
}
_x000D_
<select>_x000D_
  <option>Apples</option>_x000D_
  <option selected>Pineapples</option>_x000D_
  <option>Chocklate</option>_x000D_
  <option>Pancakes</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error

    public static void ExportToExcel(DataGridView dgView)
    {
        Microsoft.Office.Interop.Excel.Application excelApp = null;
        try
        {
            // instantiating the excel application class
            excelApp = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook currentWorkbook = excelApp.Workbooks.Add(Type.Missing);
            Microsoft.Office.Interop.Excel.Worksheet currentWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)currentWorkbook.ActiveSheet;
            currentWorksheet.Columns.ColumnWidth = 18;


            if (dgView.Rows.Count > 0)
            {
                currentWorksheet.Cells[1, 1] = DateTime.Now.ToString("s");
                int i = 1;
                foreach (DataGridViewColumn dgviewColumn in dgView.Columns)
                {
                    // Excel work sheet indexing starts with 1
                    currentWorksheet.Cells[2, i] = dgviewColumn.Name;
                    ++i;
                }
                Microsoft.Office.Interop.Excel.Range headerColumnRange = currentWorksheet.get_Range("A2", "G2");
                headerColumnRange.Font.Bold = true;
                headerColumnRange.Font.Color = 0xFF0000;
                //headerColumnRange.EntireColumn.AutoFit();
                int rowIndex = 0;
                for (rowIndex = 0; rowIndex < dgView.Rows.Count; rowIndex++)
                {
                    DataGridViewRow dgRow = dgView.Rows[rowIndex];
                    for (int cellIndex = 0; cellIndex < dgRow.Cells.Count; cellIndex++)
                    {
                        currentWorksheet.Cells[rowIndex + 3, cellIndex + 1] = dgRow.Cells[cellIndex].Value;
                    }
                }
                Microsoft.Office.Interop.Excel.Range fullTextRange = currentWorksheet.get_Range("A1", "G" + (rowIndex + 1).ToString());
                fullTextRange.WrapText = true;
                fullTextRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
            }
            else
            {
                string timeStamp = DateTime.Now.ToString("s");
                timeStamp = timeStamp.Replace(':', '-');
                timeStamp = timeStamp.Replace("T", "__");
                currentWorksheet.Cells[1, 1] = timeStamp;
                currentWorksheet.Cells[1, 2] = "No error occured";
            }
            using (SaveFileDialog exportSaveFileDialog = new SaveFileDialog())
            {
                exportSaveFileDialog.Title = "Select Excel File";
                exportSaveFileDialog.Filter = "Microsoft Office Excel Workbook(*.xlsx)|*.xlsx";

                if (DialogResult.OK == exportSaveFileDialog.ShowDialog())
                {
                    string fullFileName = exportSaveFileDialog.FileName;
                   // currentWorkbook.SaveCopyAs(fullFileName);
                    // indicating that we already saved the workbook, otherwise call to Quit() will pop up
                    // the save file dialogue box

                    currentWorkbook.SaveAs(fullFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, System.Reflection.Missing.Value, Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
                    currentWorkbook.Saved = true;
                    MessageBox.Show("Error memory exported successfully", "Exported to Excel", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            if (excelApp != null)
            {
                excelApp.Quit();
            }
        }



    }

What good technology podcasts are out there?

It's not software, but I frequently watch the Tekzilla podcasts. Love me some Veronica Belmont / Patrick Norton!

Also, all of the others already mentioned - Stack Overflow, TWiT, etc.

Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables?

I am just going to put this here. If you are looking for a compact function without using Arrays and you have no issue with mutability/immutability :

var g =x=>{/*your code goes here*/x-1>0?g(x-1):null};
 

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

In this particular use case, you don't really want to abort the merge, just resolve the conflict in a particular way.

There is no particular need to reset and perform a merge with a different strategy, either. The conflicts have been correctly highlighted by git and the requirement to accept the other sides changes is only for this one file.

For an unmerged file in a conflict git makes available the common base, local and remote versions of the file in the index. (This is where they are read from for use in a 3-way diff tool by git mergetool.) You can use git show to view them.

# common base:
git show :1:_widget.html.erb

# 'ours'
git show :2:_widget.html.erb

# 'theirs'
git show :3:_widget.html.erb

The simplest way to resolve the conflict to use the remote version verbatim is:

git show :3:_widget.html.erb >_widget.html.erb
git add _widget.html.erb

Or, with git >= 1.6.1:

git checkout --theirs _widget.html.erb

SQL Server: Cannot insert an explicit value into a timestamp column

Assume Table1 and Table2 have three columns A, B and TimeStamp. I want to insert from Table1 into Table2.

This fails with the timestamp error:

Insert Into Table2
Select Table1.A, Table1.B, Table1.TimeStamp From Table1

This works:

Insert Into Table2
Select Table1.A, Table1.B, null From Table1

Vuejs: Event on route change

If you are using v2.2.0 then there is one more option available to detect changes in $routes.

To react to params changes in the same component, you can watch the $route object:

const User = {
  template: '...',
  watch: {
    '$route' (to, from) {
      // react to route changes...
    }
  }
}

Or, use the beforeRouteUpdate guard introduced in 2.2:

const User = {
  template: '...',
  beforeRouteUpdate (to, from, next) {
    // react to route changes...
    // don't forget to call next()
  }
}

Reference: https://router.vuejs.org/en/essentials/dynamic-matching.html

How to get duplicate items from a list using LINQ?

Here's another option:

var list = new List<string> { "6", "1", "2", "4", "6", "5", "1" };

var set = new HashSet<string>();
var duplicates = list.Where(x => !set.Add(x));

Pass array to where in Codeigniter Active Record

$this->db->where_in('id', ['20','15','22','42','86']);

Reference: where_in

Set background image according to screen resolution

Put into css file:

html { background: url(images/bg.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } 

URL images/bg.jpg is your background image

List all employee's names and their managers by manager name using an inner join

Your query is close you need to join using the mgr and the empid

on e1.mgr = e2.empid

So the full query is:

select e1.ename Emp,
  e2.eName Mgr
from employees e1
inner join employees e2
  on e1.mgr = e2.empid

See SQL Fiddle with Demo

If you want to return all rows including those without a manager then you would change it to a LEFT JOIN (for example the president):

select e1.ename Emp,
  e2.eName Mgr
from employees e1
left join employees e2
  on e1.mgr = e2.empid

See SQL Fiddle with Demo

The president in your sample data will return a null value for the manager because they do not have a manager.

How to create a sticky footer that plays well with Bootstrap 3

Sticky footer solutions that rely upon fixed-height footers are falling out of favour in with responsive approaches (where the height of the footer often changes at different break points). The simplest responsive sticky footer solution I've seen involves using display: table on a top-level container, e.g.:

http://galengidman.com/2014/03/25/responsive-flexible-height-sticky-footers-in-css/

http://timothy-long.com/responsive-sticky-footer/

http://www.visualdecree.co.uk/posts/2013/12/17/responsive-sticky-footers/

Set colspan dynamically with jquery

How about

$([your selector]).attr('colspan',3);

I would imagine that to work but have no way to test at the moment. Using .attr() would be the usual jQuery way of setting attributes of elements in the wrapped set.

As has been mentioned in another answer, in order to get this to work would require removing the td elements that have no text in them from the DOM. It may be easier to do this all server side

EDIT:

As was mentioned in the comments, there is a bug in attempting to set colspan using attr() in IE, but the following works in IE6 and FireFox 3.0.13.

Working Demo

notice the use of the attribute colSpan and not colspan - the former works in both IE and Firefox, but the latter does not work in IE. Looking at jQuery 1.3.2 source, it would appear that attr() attempts to set the attribute as a property of the element if

  1. it exists as a property on the element (colSpan exists as a property and defaults to 1 on <td> HTMLElements in IE and FireFox)
  2. the document is not xml and
  3. the attribute is none of href, src or style

using colSpan as opposed to colspan works with attr() because the former is a property defined on the element whereas the latter is not.

the fall-through for attr() is to attempt to use setAttribute() on the element in question, setting the value to a string, but this causes problems in IE (bug #1070 in jQuery)

// convert the value to a string (all browsers do this but IE) see #1070
elem.setAttribute( name, "" + value ); 

In the demo, for each row, the text in each cell is evaluated. If the text is a blank string, then the cell is removed and a counter incremented. The first cell in the row that does not have class="colTime" has a colspan attribute set to the value of the counter + 1 (for the span it occupies itself).

After this, for each row, the text in the cell with class="colspans" is set to the colspan attribute values of each cell in the row from left to right.

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #000; font: 16px Helvetica, Arial; color: #fff; }
td { text-align: center; }
</style>
</head>
<body>
<table  class="tblSimpleAgenda" cellpadding="5" cellspacing="0">
 <tbody>
        <tr>
            <th align="left">Time</th>
            <th align="left">Room 1</th>
            <th align="left">Room 2</th>
            <th align="left">Room 3</th> 
            <th align="left">Colspans (L -> R)</th>
        </tr>
        <tr valign="top">
            <td class="colTime">09:00 – 10:00</td>
            <td class="col1"></td>
            <td class="col2">Meeting 2</td>
            <td class="col3"></td>
            <td class="colspans">holder</td>
        </tr>

        <tr valign="top">
            <td class="colTime">10:00 – 10:45</td>
            <td class="col1">Meeting 1</td>
            <td class="col2">Meeting 2</td>
            <td class="col3">Meeting 3</td>    
             <td class="colspans">holder</td> 
        </tr>

        <tr valign="top">
            <td class="colTime">11:00 – 11:45</td>
            <td class="col1">Meeting 1</td>
            <td class="col2">Meeting 2</td>
            <td class="col3">Meeting 3</td>
            <td class="colspans">holder</td>     
        </tr>

        <tr valign="top">
            <td class="colTime">11:00 – 11:45</td>
            <td class="col1">Meeting 1</td>
            <td class="col2">Meeting 2</td>
            <td class="col3"></td>
            <td class="colspans">holder</td>     
        </tr>
</tbody>
</table>

</body>
</html>

jQuery code

$(function() {

  $('table.tblSimpleAgenda tr').each(function() {
    var tr = this;
    var counter = 0;

    $('td', tr).each(function(index, value) {
      var td = $(this);

      if (td.text() == "") {
        counter++;
        td.remove();
      }
    });

    if (counter !== 0) {
      $('td:not(.colTime):first', tr)
        .attr('colSpan', '' + parseInt(counter + 1,10) + '');
    }
  });

  $('td.colspans').each(function(){
    var td = $(this);
    var colspans = [];

    td.siblings().each(function() {
      colspans.push(($(this).attr('colSpan')) == null ? 1 : $(this).attr('colSpan'));
    });

    td.text(colspans.join(','));
  });

});

This is just a demonstration to show that attr() can be used, but to be aware of it's implementation and the cross-browser quirks that come with it. I've also made some assumptions about your table layout in the demo (i.e. apply the colspan to the first "non-Time" cell in each row), but hopefully you get the idea.

How to get TimeZone from android mobile?

On my device TimeZone.getDefault() is always returning UTC time zone.

I need to do this to get user configured time zone :

TimeZone.setDefault(null)
val tz = TimeZone.getDefault()

It will return user selected timezone.

ps command doesn't work in docker container

In case you can't install the procps package (don't have proper permissions) you can use /proc directory.

The first few directories (named as numbers) are PIDs of your processes. Inside directories, you can find additional information useful to decipher which process is connected to each PID. For example, you can use the cat command to view "cmdline" file to check which process is connected to PID.

$ ls /proc
1 10 11 ...

$ ls -1 /proc/22
attr
autogroup
auxv
cgroup
clear_refs
cmdline
...

$ cat /proc/22/cmdline 
/bin/sh

What is a Subclass

Think of a class as a description of the members of a set of things. All of the members of that set have common characteristics (methods and properties).

A subclass is a class that describes the members of a particular subset of the original set. They share many of characteristics of the main class, but may have properties or methods that are unique to members of the subclass.

You declare that one class is subclass of another via the "extends" keyword in Java.

public class B extends A
{
...
}

B is a subclass of A. Instances of class B will automatically exhibit many of the same properties as instances of class A.

This is the main concept of inheritance in Object-Oriented programming.

Extension mysqli is missing, phpmyadmin doesn't work

Just restart the apache2 and mysql:

  • apache2: sudo /etc/init.d/apache2 restart

  • mysql: sudo /etc/init.d/mysql restart

then refresh your browser, enjoy phpmyadmin :)

Java: How to convert a File object to a String object in java?

Readin file with file inputstream and append file content to string.

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class CopyOffileInputStream {

    public static void main(String[] args) {

        //File file = new File("./store/robots.txt");
        File file = new File("swingloggingsscce.log");

        FileInputStream fis = null;
        String str = "";

        try {
            fis = new FileInputStream(file);
            int content;
            while ((content = fis.read()) != -1) {
                // convert to char and display it
                str += (char) content;
            }

            System.out.println("After reading file");
            System.out.println(str);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

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())

Importing CSV with line breaks in Excel 2007

This is for Excel 2016:

Just had the same problem with line breaks inside a csv file with the Excel Wizard.

Afterwards I was trying it with the "New Query" Feature: Data -> New Query -> From File -> From CSV -> Choose the File -> Import -> Load

It was working perfectly and a very quick workaround for all of you that have the same problem.

Printing 2D array in matrix format

Your can do it like this in short hands.

        int[,] values=new int[2,3]{{2,4,5},{4,5,2}};

        for (int i = 0; i < values.GetLength(0); i++)
        {
            for (int k = 0; k < values.GetLength(1); k++) {
                Console.Write(values[i,k]);
            }

            Console.WriteLine();
        }

How to use onClick event on react Link component?

I don't believe this is a good pattern to use in general. Link will run your onClick event and then navigate to the route, so there will be a slight delay navigating to the new route. A better strategy is to navigate to the new route with the 'to' prop as you have done, and in the new component's componentDidMount() function you can fire your hello function or any other function. It will give you the same result, but with a much smoother transition between routes.

For context, I noticed this while updating my redux store with an onClick event on Link like you have here, and it caused a ~.3 second blank-white-screen delay before mounting the new route's component. There was no api call involved, so I was surprised the delay was so big. However, if you're just console logging 'hello' the delay might not be noticeable.

Defining constant string in Java?

You can use

 public static final String HELLO = "hello";

if you have many string constants, you can use external property file / simple "constant holder" class

Download File Using Javascript/jQuery

To improve Imagine Breaker 's answer, this is supported on FF & IE :

var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

function downloadURI(uri, name) {
    var link = document.createElement("a");
    link.download = name;
    link.href = uri;
    link.dispatchEvent(evt);
}

In other words, just use a dispatchEvent function instead of click();

Python convert object to float

  • You can use pandas.Series.astype
  • You can do something like this :

    weather["Temp"] = weather.Temp.astype(float)
    
  • You can also use pd.to_numeric that will convert the column from object to float

  • For details on how to use it checkout this link :http://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.to_numeric.html
  • Example :

    s = pd.Series(['apple', '1.0', '2', -3])
    print(pd.to_numeric(s, errors='ignore'))
    print("=========================")
    print(pd.to_numeric(s, errors='coerce'))
    
  • Output:

    0    apple
    1      1.0
    2        2
    3       -3
    =========================
    dtype: object
    0    NaN
    1    1.0
    2    2.0
    3   -3.0
    dtype: float64
    
  • In your case you can do something like this:

    weather["Temp"] = pd.to_numeric(weather.Temp, errors='coerce')
    
  • Other option is to use convert_objects
  • Example is as follows

    >> pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
    
    0     1
    1     2
    2     3
    3     4
    4   NaN
    dtype: float64
    
  • You can use this as follows:

    weather["Temp"] = weather.Temp.convert_objects(convert_numeric=True)
    
  • I have showed you examples because if any of your column won't have a number then it will be converted to NaN... so be careful while using it.

The identity used to sign the executable is no longer valid

I had this problem and tried everything here but it didn't help. Then I noticed that the cord I was using was a little frayed, so I tried a new cord and it worked.

How to generate range of numbers from 0 to n in ES2015 only?

You can also do it with a one liner with step support like this one:

((from, to, step) => ((add, arr, v) => add(arr, v, add))((arr, v, add) => v < to ? add(arr.concat([v]), v + step, add) : arr, [], from))(0, 10, 1)

The result is [0, 1, 2, 3, 4, 5, 6 ,7 ,8 ,9].

Bash script plugin for Eclipse?

It works for me in Oxygen.

1) Go to Help > Eclipse Marketplace... and search for "DLTK". You'll find something like "Shell Script (DLTK) 5.8.0". Install it and reboot Eclipse.

(Or drag'n'drop "Install" button from this web page to your Eclipse: https://marketplace.eclipse.org/content/shell-script-dltk)

Shell Script (DLTK)

2) Right-click on the shell/batch file in Project Explorer > Open With > Other... and select Shell Script Editor. You can also associate the editor with all files of that extension.

Shell script editor

How does Subquery in select statement work in oracle

It's simple-

SELECT empname,
       empid,
       (SELECT COUNT (profileid)
          FROM profile
         WHERE profile.empid = employee.empid)
           AS number_of_profiles
  FROM employee;

It is even simpler when you use a table join like this:

  SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
    FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;

Explanation for the subquery:

Essentially, a subquery in a select gets a scalar value and passes it to the main query. A subquery in select is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null to the main query. Moreover, a subquery can access columns from the from clause of the main query, as shown in my query where employee.empid is passed from the outer query to the inner query.


Edit:

When you use a subquery in a select clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.


Explanation for the left join

A left join is very handy, especially when you want to replace the select subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN keyword.

For more information read Oracle Docs on subqueries and left join or left outer join.

Struct with template variables in C++

The problem is you can't template a typedef, also there is no need to typedef structs in C++.

The following will do what you need

template <typename T> 
struct array { 
  size_t x; 
  T *ary; 
}; 

Run an Ansible task only when the variable contains a specific string

None of the above answers worked for me in ansible 2.3.0.0, but the following does:

when: variable1 | search("value")

In ansible 2.9 this is deprecated in favor of using ~ concatenation for variable replacement:

when: "variable1.find('v=' ~ value) == -1"

http://jinja.pocoo.org/docs/dev/templates/#other-operators

Other options:

when: "inventory_hostname in groups[sync_source]"

Clearing coverage highlighting in Eclipse

On 4.2 eclipse it seems to be impossible to remove the eCobertura highlights. Sadly eCobertura plugins seems to be not maintained anymore. However if you start writing into the class, its gone. So type a space, and then undo, and its gone.

When should I use h:outputLink instead of h:commandLink?

The <h:outputLink> renders a fullworthy HTML <a> element with the proper URL in the href attribute which fires a bookmarkable GET request. It cannot directly invoke a managed bean action method.

<h:outputLink value="destination.xhtml">link text</h:outputLink>

The <h:commandLink> renders a HTML <a> element with an onclick script which submits a (hidden) POST form and can invoke a managed bean action method. It's also required to be placed inside a <h:form>.

<h:form>
    <h:commandLink value="link text" action="destination" />
</h:form>

The ?faces-redirect=true parameter on the <h:commandLink>, which triggers a redirect after the POST (as per the Post-Redirect-Get pattern), only improves bookmarkability of the target page when the link is actually clicked (the URL won't be "one behind" anymore), but it doesn't change the href of the <a> element to be a fullworthy URL. It still remains #.

<h:form>
    <h:commandLink value="link text" action="destination?faces-redirect=true" />
</h:form>

Since JSF 2.0, there's also the <h:link> which can take a view ID (a navigation case outcome) instead of an URL. It will generate a HTML <a> element as well with the proper URL in href.

<h:link value="link text" outcome="destination" />

So, if it's for pure and bookmarkable page-to-page navigation like the SO username link, then use <h:outputLink> or <h:link>. That's also better for SEO since bots usually doesn't cipher POST forms nor JS code. Also, UX will be improved as the pages are now bookmarkable and the URL is not "one behind" anymore.

When necessary, you can do the preprocessing job in the constructor or @PostConstruct of a @RequestScoped or @ViewScoped @ManagedBean which is attached to the destination page in question. You can make use of @ManagedProperty or <f:viewParam> to set GET parameters as bean properties.

See also:

How to update primary key

First, we choose stable (not static) data columns to form a Primary Key, precisely because updating Keys in a Relational database (in which the references are by Key) is something we wish to avoid.

  1. For this issue, it doesn't matter if the Key is a Relational Key ("made up from the data"), and thus has Relational Integrity, Power, and Speed, or if the "key" is a Record ID, with none of that Relational Integrity, Power, and Speed. The effect is the same.

  2. I state this because there are many posts by the clueless ones, who suggest that this is the exact reason that Record IDs are somehow better than Relational Keys.

  3. The point is, the Key or Record ID is migrated to wherever a reference is required.

Second, if you have to change the value of the Key or Record ID, well, you have to change it. Here is the OLTP Standard-compliant method. Note that the high-end vendors do not allow "cascade update".

  • Write a proc. Foo_UpdateCascade_tr @ID, where Foo is the table name

  • Begin a Transaction

  • First INSERT-SELECT a new row in the parent table, from the old row, with the new Key or RID value

  • Second, for all child tables, working top to bottom, INSERT-SELECT the new rows, from the old rows, with the new Key or RID value

  • Third, DELETE the rows in the child tables that have the old Key or RID value, working bottom to top

  • Last, DELETE the row in the parent table that has the old Key or RID value

  • Commit the Transaction

Re the Other Answers

The other answers are incorrect.

  • Disabling constraints and then enabling them, after UPDATing the required rows (parent plus all children) is not something that a person would do in an online production environment, if they wish to remain employed. That advice is good for single-user databases.

  • The need to change the value of a Key or RID is not indicative of a design flaw. It is an ordinary need. That is mitigated by choosing stable (not static) Keys. It can be mitigated, but it cannot be eliminated.

  • A surrogate substituting a natural Key, will not make any difference. In the example you have given, the "key" is a surrogate. And it needs to be updated.

    • Please, just surrogate, there is no such thing as a "surrogate key", because each word contradicts the other. Either it is a Key (made up from the data) xor it isn't. A surrogate is not made up from the data, it is explicitly non-data. It has none of the properties of a Key.
  • There is nothing "tricky" about cascading all the required changes. Refer to the steps given above.

  • There is nothing that can be prevented re the universe changing. It changes. Deal with it. And since the database is a collection of facts about the universe, when the universe changes, the database will have to change. That is life in the big city, it is not for new players.

  • People getting married and hedgehogs getting buried are not a problem (despite such examples being used to suggest that it is a problem). Because we do not use Names as Keys. We use small, stable Identifiers, such as are used to Identify the data in the universe.

    • Names, descriptions, etc, exist once, in one row. Keys exist wherever they have been migrated. And if the "key" is a RID, then the RID too, exists wherever it has been migrated.
  • Don't update the PK! is the second-most hilarious thing I have read in a while. Add a new column is the most.

SQL Server® 2016, 2017 and 2019 Express full download

Download the developer edition. There you can choose Express as license when installing.

enter image description here

Importing large sql file to MySql via command line

You can import .sql file using the standard input like this:

mysql -u <user> -p<password> <dbname> < file.sql

Note: There shouldn't space between <-p> and <password>

Reference: http://dev.mysql.com/doc/refman/5.0/en/mysql-batch-commands.html

Note for suggested edits: This answer was slightly changed by suggested edits to use inline password parameter. I can recommend it for scripts but you should be aware that when you write password directly in the parameter (-p<password>) it may be cached by a shell history revealing your password to anyone who can read the history file. Whereas -p asks you to input password by standard input.

How to replace all occurrences of a string in Javascript?

There is now a finished proposal for integrating String.prototype.replaceAll into the official specification. Eventually, developers will not have to come up with their own implementations for replaceAll - instead, modern Javascript engines will support it natively.

The proposal is at stage 4, which means that everything is complete, and all that's left is for browsers to start implementing it.

It has shipped in the latest versions of Chrome, Firefox, and Safari.

Here are the implementation details:

Per the current TC39 consensus, String.prototype.replaceAll behaves identically to String.prototype.replace in all cases, except for the following two cases:

  1. If searchValue is a string, String.prototype.replace only replaces a single occurrence of the searchValue, whereas String.prototype.replaceAll replaces all occurrences of the searchValue (as if .split(searchValue).join(replaceValue) or a global & properly-escaped regular expression had been used).
  2. If searchValue is a non-global regular expression, String.prototype.replace replaces a single match, whereas String.prototype.replaceAll throws an exception. This is done to avoid the inherent confusion between the lack of a global flag (which implies "do NOT replace all") and the name of the method being called (which strongly suggests "replace all").

Notably, String.prototype.replaceAll behaves just like String.prototype.replace if searchValue is a global regular expression.

You can see a spec-compliant polyfill here.

In supported environments, the following snippet will log foo-bar-baz, without throwing an error:

_x000D_
_x000D_
const str = 'foo bar baz';
console.log(
  str.replaceAll(' ', '-')
);
_x000D_
_x000D_
_x000D_

Using Javascript: How to create a 'Go Back' link that takes the user to a link if there's no history for the tab or window?

this seems to do the trick:

function goBackOrGoToUrl() {    

    window.history.back();
    window.location = "http://example.com";

}

Call history.back() and then change the location. If the browser is able to go back in history it won't be able to get to the next statement. If it's not able to go back, it'll go to the location specified.

execJs: 'Could not find a JavaScript runtime' but execjs AND therubyracer are in Gemfile

I had this problem when using RubyMine (6.3.3). One day I tried to run my code, but it didn't work and complained about no JavaScript runtime found. I was able to run rails s though. The fix for me was creating a new Run configuration. Seems really bizarre that the Run configuration would become corrupt.

How do you get the path to the Laravel Storage folder?

For Laravel version >=5.1

storage_path()

The storage_path function returns the fully qualified path to the storage directory:

$path = storage_path();

You may also use the storage_path function to generate a fully qualified path to a given file relative to the storage directory:

$app_path = storage_path('app');
$file_path = storage_path('app/file.txt');

Source: Laravel Doc

create multiple tag docker image

docker build  -t name1:tag1 -t name2:tag2 -f Dockerfile.ui .

How to plot a histogram using Matplotlib in Python with a list of data?

This is a very round-about way of doing it but if you want to make a histogram where you already know the bin values but dont have the source data, you can use the np.random.randint function to generate the correct number of values within the range of each bin for the hist function to graph, for example:

import numpy as np
import matplotlib.pyplot as plt

data = [np.random.randint(0, 9, *desired y value*), np.random.randint(10, 19, *desired y value*), etc..]
plt.hist(data, histtype='stepfilled', bins=[0, 10, etc..])

as for labels you can align x ticks with bins to get something like this:

#The following will align labels to the center of each bar with bin intervals of 10
plt.xticks([5, 15, etc.. ], ['Label 1', 'Label 2', etc.. ])

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

To be highly positive you work with the actual email body (yet, still with the possibility you're not parsing the right part), you have to skip attachments, and focus on the plain or html part (depending on your needs) for further processing.

As the before-mentioned attachments can and very often are of text/plain or text/html part, this non-bullet-proof sample skips those by checking the content-disposition header:

b = email.message_from_string(a)
body = ""

if b.is_multipart():
    for part in b.walk():
        ctype = part.get_content_type()
        cdispo = str(part.get('Content-Disposition'))

        # skip any text/plain (txt) attachments
        if ctype == 'text/plain' and 'attachment' not in cdispo:
            body = part.get_payload(decode=True)  # decode
            break
# not multipart - i.e. plain text, no attachments, keeping fingers crossed
else:
    body = b.get_payload(decode=True)

BTW, walk() iterates marvelously on mime parts, and get_payload(decode=True) does the dirty work on decoding base64 etc. for you.

Some background - as I implied, the wonderful world of MIME emails presents a lot of pitfalls of "wrongly" finding the message body. In the simplest case it's in the sole "text/plain" part and get_payload() is very tempting, but we don't live in a simple world - it's often surrounded in multipart/alternative, related, mixed etc. content. Wikipedia describes it tightly - MIME, but considering all these cases below are valid - and common - one has to consider safety nets all around:

Very common - pretty much what you get in normal editor (Gmail,Outlook) sending formatted text with an attachment:

multipart/mixed
 |
 +- multipart/related
 |   |
 |   +- multipart/alternative
 |   |   |
 |   |   +- text/plain
 |   |   +- text/html
 |   |      
 |   +- image/png
 |
 +-- application/msexcel

Relatively simple - just alternative representation:

multipart/alternative
 |
 +- text/plain
 +- text/html

For good or bad, this structure is also valid:

multipart/alternative
 |
 +- text/plain
 +- multipart/related
      |
      +- text/html
      +- image/jpeg

Hope this helps a bit.

P.S. My point is don't approach email lightly - it bites when you least expect it :)

Difference between numpy dot() and Python 3.5+ matrix multiplication @

Here is a comparison with np.einsum to show how the indices are projected

np.allclose(np.einsum('ijk,ijk->ijk', a,b), a*b)        # True 
np.allclose(np.einsum('ijk,ikl->ijl', a,b), a@b)        # True
np.allclose(np.einsum('ijk,lkm->ijlm',a,b), a.dot(b))   # True

How can I get the current class of a div with jQuery?

Just get the class attribute:

var div1Class = $('#div1').attr('class');

Example

<div id="div1" class="accordion accordion_active">

To check the above div for classes contained in it

var a = ("#div1").attr('class'); 
console.log(a);

console output

accordion accordion_active

Is there a "null coalescing" operator in JavaScript?

If || as a replacement of C#'s ?? isn't good enough in your case, because it swallows empty strings and zeros, you can always write your own function:

 function $N(value, ifnull) {
    if (value === null || value === undefined)
      return ifnull;
    return value;
 }

 var whatIWant = $N(someString, 'Cookies!');

How can I trigger a JavaScript event click

IE9+

function triggerEvent(el, type){
    var e = document.createEvent('HTMLEvents');
    e.initEvent(type, false, true);
    el.dispatchEvent(e);
}

Usage example:

var el = document.querySelector('input[type="text"]');
triggerEvent(el, 'mousedown');

Source: https://plainjs.com/javascript/events/trigger-an-event-11/

Dropping Unique constraint from MySQL table

my table name is buyers which has a unique constraint column emp_id now iam going to drop the emp_id

step 1: exec sp_helpindex buyers, see the image file

step 2: copy the index address

enter image description here

step3: alter table buyers drop constraint [UQ__buyers__1299A860D9793F2E] alter table buyers drop column emp_id

note:

Blockquote

instead of buyers change it to your table name :)

Blockquote

thats all column name emp_id with constraints is dropped!

How to get URL parameters with Javascript?

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

So you can use:

myvar = getURLParameter('myvar');

Convert string to variable name in JavaScript

let me make it more clear

function changeStringToVariable(variable, value){
window[variable]=value
}
changeStringToVariable("name", "john doe");
console.log(name);
//this outputs: john doe
let file="newFile";
changeStringToVariable(file, "text file");
console.log(newFile);
//this outputs: text file

asterisk : Unable to connect to remote asterisk (does /var/run/asterisk.ctl exist?)

I had this problem today. It had nothing to do with any of the posted answers. I tried them all. My problem was a misconfiguration with the zaptel.conf (running old asterisk!). I had commented out some span details trying to troubleshoot a PRI issue. When the server got rebooted this issue presented itself. I was able to discover this by looking at the wanrouter messages in the logs. I noticed there were 3 errors, and the corresponding line numbers, once I corrected these issues, and ran an #asterisk -vvvvc the server came back up and everything worked.

What is the difference between a "line feed" and a "carriage return"?

Both of these are primary from the old printing days.

Carriage return is from the days of the teletype printers/old typewriters, where literally the carriage would return to the next line, and push the paper up. This is what we now call \r.

Line feed LF signals the end of the line, it signals that the line has ended - but doesn't move the cursor to the next line. In other words, it doesn't "return" the cursor/printer head to the next line.

For more sundry details, the mighty wikipedia to the rescue.

how does int main() and void main() work

Neither main() or void main() are standard C. The former is allowed as it has an implicit int return value, making it the same as int main(). The purpose of main's return value is to return an exit status to the operating system.

In standard C, the only valid signatures for main are:

int main(void)

and

int main(int argc, char **argv)

The form you're using: int main() is an old style declaration that indicates main takes an unspecified number of arguments. Don't use it - choose one of those above.

How to use awk sort by column 3

  1. Use awk to put the user ID in front.
  2. Sort
  3. Use sed to remove the duplicate user ID, assuming user IDs do not contain any spaces.

    awk -F, '{ print $3, $0 }' user.csv | sort | sed 's/^.* //'
    

How to convert Java String into byte[]?

The object your method decompressGZIP() needs is a byte[].

So the basic, technical answer to the question you have asked is:

byte[] b = string.getBytes();
byte[] b = string.getBytes(Charset.forName("UTF-8"));
byte[] b = string.getBytes(StandardCharsets.UTF_8); // Java 7+ only

However the problem you appear to be wrestling with is that this doesn't display very well. Calling toString() will just give you the default Object.toString() which is the class name + memory address. In your result [B@38ee9f13, the [B means byte[] and 38ee9f13 is the memory address, separated by an @.

For display purposes you can use:

Arrays.toString(bytes);

But this will just display as a sequence of comma-separated integers, which may or may not be what you want.

To get a readable String back from a byte[], use:

String string = new String(byte[] bytes, Charset charset);

The reason the Charset version is favoured, is that all String objects in Java are stored internally as UTF-16. When converting to a byte[] you will get a different breakdown of bytes for the given glyphs of that String, depending upon the chosen charset.

Carry Flag, Auxiliary Flag and Overflow Flag in Assembly

Carry Flag

The rules for turning on the carry flag in binary/integer math are two:

  1. The carry flag is set if the addition of two numbers causes a carry out of the most significant (leftmost) bits added. 1111 + 0001 = 0000 (carry flag is turned on)

  2. The carry (borrow) flag is also set if the subtraction of two numbers requires a borrow into the most significant (leftmost) bits subtracted. 0000 - 0001 = 1111 (carry flag is turned on) Otherwise, the carry flag is turned off (zero).

    • 0111 + 0001 = 1000 (carry flag is turned off [zero])
    • 1000 - 0001 = 0111 (carry flag is turned off [zero])

In unsigned arithmetic, watch the carry flag to detect errors.

In signed arithmetic, the carry flag tells you nothing interesting.

Overflow Flag

The rules for turning on the overflow flag in binary/integer math are two:

  1. If the sum of two numbers with the sign bits off yields a result number with the sign bit on, the "overflow" flag is turned on. 0100 + 0100 = 1000 (overflow flag is turned on)

  2. If the sum of two numbers with the sign bits on yields a result number with the sign bit off, the "overflow" flag is turned on. 1000 + 1000 = 0000 (overflow flag is turned on)

Otherwise the "overflow" flag is turned off

  • 0100 + 0001 = 0101 (overflow flag is turned off)
  • 0110 + 1001 = 1111 (overflow flag turned off)
  • 1000 + 0001 = 1001 (overflow flag turned off)
  • 1100 + 1100 = 1000 (overflow flag is turned off)

Note that you only need to look at the sign bits (leftmost) of the three numbers to decide if the overflow flag is turned on or off.

If you are doing two's complement (signed) arithmetic, overflow flag on means the answer is wrong - you added two positive numbers and got a negative, or you added two negative numbers and got a positive.

If you are doing unsigned arithmetic, the overflow flag means nothing and should be ignored.

For more clarification please refer: http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt

jQuery function to get all unique elements from an array?

Paul Irish has a "Duck Punching" method (see example 2) that modifies jQuery's $.unique() method to return unique elements of any type:

(function($){
    var _old = $.unique;
    $.unique = function(arr){
        // do the default behavior only if we got an array of elements
        if (!!arr[0].nodeType){
            return _old.apply(this,arguments);
        } else {
            // reduce the array to contain no dupes via grep/inArray
            return $.grep(arr,function(v,k){
                return $.inArray(v,arr) === k;
            });
        }
    };
})(jQuery);

Visual Studio Code - Convert spaces to tabs

If you want to use tabs instead of spaces

Try this:

  1. Go to File ? Preferences ? Settings or just press Ctrl + ,
  2. In the Search settings bar on top insert editor.insertSpaces
  3. You will see something like this: Editor: Insert Spaces and it will be probably checked. Just uncheck it as show in image below

Editor: Insert Spaces

  1. Reload Visual Studio Code (Press F1 ? type reload window ? press Enter)

If it doesn't worked try this:

It's probably because of installed plugin JS-CSS-HTML Formatter

(You can check it by going to File ? Preferences ? Extensions or just pressing Ctrl + Shift + X, in the Enabled list you will find JS-CSS-HTML Formatter)

If so you can modify this plugin:

  1. Press F1 ? type Formatter config ? press Enter (it will open the file formatter.json)
  2. Modify the file like this:
 4|    "indent_size": 1,
 5|    "indent_char": "\t"
——|
24|    "indent_size": 1,
25|    "indentCharacter": "\t",
26|    "indent_char": "\t",
——|
34|    "indent_size": 1,
35|    "indent_char": "\t",
36|    "indent_character": "\t"
  1. Save it (Go to File ? Save or just press Ctrl + S)
  2. Reload Visual Studio Code (Press F1 ? type reload window ? press Enter)

Cannot create PoolableConnectionFactory

I had the same problem with localhost in the source URL. I resolved with 127.0.0.1 instead of localhost.

How to add data into ManyToMany field?

There's a whole page of the Django documentation devoted to this, well indexed from the contents page.

As that page states, you need to do:

my_obj.categories.add(fragmentCategory.objects.get(id=1))

or

my_obj.categories.create(name='val1')

what is the difference between OLE DB and ODBC data sources?

ODBC works only for relational databases, it can't works with non-relational databases such as Ms Excel files. Where Olebd can do everything.

Python: Ignore 'Incorrect padding' error when base64 decoding

There are two ways to correct the input data described here, or, more specifically and in line with the OP, to make Python module base64's b64decode method able to process the input data to something without raising an un-caught exception:

  1. Append == to the end of the input data and call base64.b64decode(...)
  2. If that raises an exception, then

    i. Catch it via try/except,

    ii. (R?)Strip any = characters from the input data (N.B. this may not be necessary),

    iii. Append A== to the input data (A== through P== will work),

    iv. Call base64.b64decode(...) with those A==-appended input data

The result from Item 1. or Item 2. above will yield the desired result.

Caveats

This does not guarantee the decoded result will be what was originally encoded, but it will (sometimes?) give the OP enough to work with:

Even with corruption I want to get back to the binary because I can still get some useful info from the ASN.1 stream").

See What we know and Assumptions below.

TL;DR

From some quick tests of base64.b64decode(...)

  1. it appears that it ignores non-[A-Za-z0-9+/] characters; that includes ignoring =s unless they are the last character(s) in a parsed group of four, in which case the =s terminate the decoding (a=b=c=d= gives the same result as abc=, and a==b==c== gives the same result as ab==).

  2. It also appears that all characters appended are ignored after the point where base64.b64decode(...) terminates decoding e.g. from an = as the fourth in a group.

As noted in several comments above, there are either zero, or one, or two, =s of padding required at the end of input data for when the [number of parsed characters to that point modulo 4] value is 0, or 3, or 2, respectively. So, from items 3. and 4. above, appending two or more =s to the input data will correct any [Incorrect padding] problems in those cases.

HOWEVER, decoding cannot handle the case where the [total number of parsed characters modulo 4] is 1, because it takes a least two encoded characters to represent the first decoded byte in a group of three decoded bytes. In uncorrupted encoded input data, this [N modulo 4]=1 case never happens, but as the OP stated that characters may be missing, it could happen here. That is why simply appending =s will not always work, and why appending A== will work when appending == does not. N.B. Using [A] is all but arbitrary: it adds only cleared (zero) bits to the decoded, which may or not be correct, but then the object here is not correctness but completion by base64.b64decode(...) sans exceptions.

What we know from the OP and especially subsequent comments is

  • It is suspected that there are missing data (characters) in the Base64-encoded input data
  • The Base64 encoding uses the standard 64 place-values plus padding: A-Z; a-z; 0-9; +; /; = is padding. This is confirmed, or at least suggested, by the fact that openssl enc ... works.

Assumptions

  • The input data contain only 7-bit ASCII data
  • The only kind of corruption is missing encoded input data
  • The OP does not care about decoded output data at any point after that corresponding to any missing encoded input data

Github

Here is a wrapper to implement this solution:

https://github.com/drbitboy/missing_b64

Call javascript from MVC controller action

You can call a controller action from a JavaScript function but not vice-versa. How would the server know which client to target? The server simply responds to requests.

An example of calling a controller action from JavaScript (using the jQuery JavaScript library) in the response sent to the client.

$.ajax({
           type: "POST",
           url: "/Controller/Action", // the URL of the controller action method
           data: null, // optional data
           success: function(result) {
                // do something with result
           },                
           error : function(req, status, error) {
                // do something with error   
           }
       });

Split Strings into words with multiple word boundary delimiters

Here is my go at a split with multiple deliminaters:

def msplit( str, delims ):
  w = ''
  for z in str:
    if z not in delims:
        w += z
    else:
        if len(w) > 0 :
            yield w
        w = ''
  if len(w) > 0 :
    yield w

How do I strip all spaces out of a string in PHP?

If you want to remove all whitespace:

$str = preg_replace('/\s+/', '', $str);

See the 5th example on the preg_replace documentation. (Note I originally copied that here.)

Edit: commenters pointed out, and are correct, that str_replace is better than preg_replace if you really just want to remove the space character. The reason to use preg_replace would be to remove all whitespace (including tabs, etc.).

What is /var/www/html?

In the most shared hosts you can't set it.

On a VPS or dedicated server, you can set it, but everything has its price.

On shared hosts, in general you receive a Linux account, something such as /home/(your username)/, and the equivalent of /var/www/html turns to /home/(your username)/public_html/ (or something similar, such as /home/(your username)/www)

If you're accessing your account via FTP, you automatically has accessing the your */home/(your username)/ folder, just find the www or public_html and put your site in it.

If you're using absolute path in the code, bad news, you need to refactor it to use relative paths in the code, at least in a shared host.

How to convert answer into two decimal point

Try using the Format function:

Private Sub btncalc_Click(ByVal sender As System.Object,
                          ByVal e As System.EventArgs) Handles btncalc.Click
  txtA.Text = Format(Val(txtD.Text) / Val(txtC.Text) * 
                     Val(txtF.Text) / Val(txtE.Text), "0.00")
  txtB.Text = Format(Val(txtA.Text) * 1000 / Val(txtG.Text), "0.00")
End Sub

tar: add all files and directories in current directory INCLUDING .svn and so on

A good question. In ZSH you can use the globbing modifier (D), which stands for "dotfiles". Compare:

ls $HOME/*

and

ls $HOME/*(D)

This correctly excludes the special directory entries . and ... In Bash you can use .* to include the dotfiles explicitly:

ls $HOME/* $HOME/.*

But that includes . and .. as well, so it's not what you were looking for. I'm sure there's some way to make * match dotfiles in bash, too.

postgres: upgrade a user to be a superuser?

$ su - postgres
$ psql
$ \du; for see the user on db
select the user that do you want be superuser and:
$ ALTER USER "user" with superuser;

How to resize datagridview control when form resizes

Unless I am misunderstanding what you are asking you can do this on the properties for your data grid view. You need to set the Anchor property to the sides you want it locked to.

SVN- How to commit multiple files in a single shot

I've had no issues committing a few files like this:

svn commit fileDir1/ fileDir2/ -m "updated!"

Java 8 Distinct by property

An alternative would be to place the persons in a map using the name as a key:

persons.collect(Collectors.toMap(Person::getName, p -> p, (p, q) -> p)).values();

Note that the Person that is kept, in case of a duplicate name, will be the first encontered.

List directory tree structure in python?

For those who are still looking for an answer. Here is a recursive approach to get the paths in a dictionary.

import os


def list_files(startpath):
    for root, dirs, files in os.walk(startpath):
        dir_content = []
        for dir in dirs:
            go_inside = os.path.join(startpath, dir)
            dir_content.append(list_files(go_inside))
        files_lst = []
        for f in files:
            files_lst.append(f)
        return {'name': root, 'files': files_lst, 'dirs': dir_content}

fix java.net.SocketTimeoutException: Read timed out

I don't think it's enough merely to get the response. I think you need to read it (get the entity and read it via EntityUtils.consume()).

e.g. (from the doc)

     System.out.println("<< Response: " + response.getStatusLine());
     System.out.println(EntityUtils.toString(response.getEntity()));

What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?

  1. return None or return can be used to exit out of a function or program, both does the same thing
  2. quit() function can be used, although use of this function is discouraged for making real world applications and should be used only in interpreter.
    import site
    
    def func():
        print("Hi")
        quit()
        print("Bye")
  1. exit() function can be used, similar to quit() but the use is discouraged for making real world applications.
import site
    
    def func():
        print("Hi")
        exit()
        print("Bye")
  1. sys.exit([arg]) function can be used and need to import sys module for that, this function can be used for real world applications unlike the other two functions.
import sys 
  height = 150
  
if height < 165: # in cm 
      
    # exits the program 
    sys.exit("Height less than 165")     
else: 
    print("You ride the rollercoaster.") 
  1. os._exit(n) function can be used to exit from a process, and need to import os module for that.

HTML image bottom alignment inside DIV container

Flexboxes can accomplish this by using align-items: flex-end; with display: flex; or display: inline-flex;

div#imageContainer {
    height: 160px;  
    align-items: flex-end;
    display: flex;

    /* This is the default value, so you only need to explicitly set it if it's already being set to something else elsewhere. */
    /*flex-direction: row;*/
}

JSFiddle example

CSS-Tricks has a good guide for flexboxes

Python not working in the command line of git bash

I am windows 10 user and I have installed GIT in my system by just accepting the defaults.

After reading the above answers, I got 2 solutions for my own and these 2 solutions perfectly works on GIT bash and facilitates me to execute Python statements on GIT bash.

I am attaching 3 images of my GIT bash terminal. 1st with problem and the latter 2 as solutions.

PROBLEM - Cursor is just waiting after hitting python command

enter image description here

SOLUTION 1

Execute winpty <path-to-python-installation-dir>/python.exe on GIT bash terminal.

Note: Do not use C:\Users\Admin like path style in GIT bash, instead use /C/Users/Admin.

In my case, I executed winpty /C/Users/SJV/Anaconda2/python.exe command on GIT bash

Or if you do not know your username then execute winpty /C/Users/$USERNAME/Anaconda2/python.exe

enter image description here

SOLUTION 2

Just type python -i and that is it.

enter image description here

Thanks.

Passing an array to a query using a WHERE clause

ints:

$query = "SELECT * FROM `$table` WHERE `$column` IN(".implode(',',$array).")";

strings:

$query = "SELECT * FROM `$table` WHERE `$column` IN('".implode("','",$array)."')";

Buiding Hadoop with Eclipse / Maven - Missing artifact jdk.tools:jdk.tools:jar:1.6

This worked for me:

    <dependency>
        <groupId>jdk.tools</groupId>
        <artifactId>jdk.tools</artifactId>
        <version>1.7.0_05</version>
        <scope>system</scope>
        <systemPath>${JAVA_HOME}/lib/tools.jar</systemPath>
    </dependency>

Search for an item in a Lua list

You could use something like a set from Programming in Lua:

function Set (list)
  local set = {}
  for _, l in ipairs(list) do set[l] = true end
  return set
end

Then you could put your list in the Set and test for membership:

local items = Set { "apple", "orange", "pear", "banana" }

if items["orange"] then
  -- do something
end

Or you could iterate over the list directly:

local items = { "apple", "orange", "pear", "banana" }

for _,v in pairs(items) do
  if v == "orange" then
    -- do something
    break
  end
end

The best way to remove duplicate values from NSMutableArray in Objective-C?

need order

NSArray *yourarray = @[@"a",@"b",@"c"];
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:yourarray];
NSArray *arrayWithoutDuplicates = [orderedSet array];
NSLog(@"%@",arrayWithoutDuplicates);

or don't need order

NSSet *set = [NSSet setWithArray:yourarray];
NSArray *arrayWithoutOrder = [set allObjects];
NSLog(@"%@",arrayWithoutOrder);

Hiding the address bar of a browser (popup)

you can do it with visual Basic, put a Webbrowser control on the form, load an html that opens a popup with Location=no and it will open a new browser without address bar. Probably not what you are looking for but just thought throw it in :)

Android saving file to external storage

since android 4.4 file saving has been changed. there is

ContextCompat.getExternalFilesDirs(context, name);

it retuns an array.

when name is null

the first value is like /storage/emulated/0/Android/com.my.package/files

the second value is like /storage/extSdCard/Android/com.my.package/files

android 4.3 and less it retuns a single item array

parts of little messy code but it demonstrates how it works:

    /** Create a File for saving an image or video 
     * @throws Exception */
    private File getOutputMediaFile(int type) throws Exception{

        // Check that the SDCard is mounted
        File mediaStorageDir;
        if(internalstorage.isChecked())
        {
            mediaStorageDir = new File(getFilesDir().getAbsolutePath() );
        }
        else
        {
            File[] dirs=ContextCompat.getExternalFilesDirs(this, null);
            mediaStorageDir = new File(dirs[dirs.length>1?1:0].getAbsolutePath() );
        }


        // Create the storage directory(MyCameraVideo) if it does not exist
        if (! mediaStorageDir.exists()){

            if (! mediaStorageDir.mkdirs()){

                output.setText("Failed to create directory.");

                Toast.makeText(this, "Failed to create directory.", Toast.LENGTH_LONG).show();

                Log.d("myapp", "Failed to create directory");
                return null;
            }
        }


        // Create a media file name

        // For unique file name appending current timeStamp with file name
        java.util.Date date= new java.util.Date();
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.ENGLISH)  .format(date.getTime());

        File mediaFile;

        if(type == MEDIA_TYPE_VIDEO) {

            // For unique video file name appending current timeStamp with file name
            mediaFile = new File(mediaStorageDir.getPath() + File.separator + slpid + "_" + pwsid + "_" + timeStamp + ".mp4");

        }
        else if(type == MEDIA_TYPE_AUDIO) {

            // For unique video file name appending current timeStamp with file name
            mediaFile = new File(mediaStorageDir.getPath() + File.separator + slpid + "_" + pwsid + "_" + timeStamp + ".3gp");

        } else {
            return null;
        }

        return mediaFile;
    }



    /** Create a file Uri for saving an image or video 
     * @throws Exception */
    private  Uri getOutputMediaFileUri(int type) throws Exception{

          return Uri.fromFile(getOutputMediaFile(type));
    }

//usage:
        try {
            file=getOutputMediaFileUri(MEDIA_TYPE_AUDIO).getPath();
        } catch (Exception e1) {
            e1.printStackTrace();
            return;
        }

MySQL parameterized queries

Actually, even if your variable (SongLength) is numeric, you will still have to format it with %s in order to bind the parameter correctly. If you try to use %d, you will get an error. Here's a small excerpt from this link http://mysql-python.sourceforge.net/MySQLdb.html:

To perform a query, you first need a cursor, and then you can execute queries on it:

c=db.cursor()
max_price=5
c.execute("""SELECT spam, eggs, sausage FROM breakfast
          WHERE price < %s""", (max_price,))

In this example, max_price=5 Why, then, use %s in the string? Because MySQLdb will convert it to a SQL literal value, which is the string '5'. When it's finished, the query will actually say, "...WHERE price < 5".

Saving and Reading Bitmaps/Images from Internal memory in Android

Came across this question today and this is how I do it. Just call this function with the required parameters

public void saveImage(Context context, Bitmap bitmap, String name, String extension){
    name = name + "." + extension;
    FileOutputStream fileOutputStream;
    try {
        fileOutputStream = context.openFileOutput(name, Context.MODE_PRIVATE);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fileOutputStream);
        fileOutputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Similarly, for reading the same, use this

public Bitmap loadImageBitmap(Context context,String name,String extension){
    name = name + "." + extension
    FileInputStream fileInputStream
    Bitmap bitmap = null;
    try{
        fileInputStream = context.openFileInput(name);
        bitmap = BitmapFactory.decodeStream(fileInputStream);
        fileInputStream.close();
    } catch(Exception e) {
        e.printStackTrace();
    }
     return bitmap;
}

Angular IE Caching issue for $http

You can either append a unique querystring (I believe this is what jQuery does with the cache: false option) to the request.

$http({
    url: '...',
    params: { 'foobar': new Date().getTime() }
})

A perhaps better solution is if you have access to the server, then you can make sure that necessary headers are set to prevent caching. If you're using ASP.NET MVC this answer might help.

How to get my Android device Internal Download Folder path

if a device has an SD card, you use:

Environment.getExternalStorageState() 

if you don't have an SD card, you use:

Environment.getDataDirectory()

if there is no SD card, you can create your own directory on the device locally.

    //if there is no SD card, create new directory objects to make directory on device
        if (Environment.getExternalStorageState() == null) {
                        //create new file directory object
            directory = new File(Environment.getDataDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(Environment.getDataDirectory()
                    + "/Robotium-Screenshots/");
            /*
             * this checks to see if there are any previous test photo files
             * if there are any photos, they are deleted for the sake of
             * memory
             */
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length != 0) {
                    for (int ii = 0; ii <= dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                }
            }
            // if no directory exists, create new directory
            if (!directory.exists()) {
                directory.mkdir();
            }

            // if phone DOES have sd card
        } else if (Environment.getExternalStorageState() != null) {
            // search for directory on SD card
            directory = new File(Environment.getExternalStorageDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Robotium-Screenshots/");
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length > 0) {
                    for (int ii = 0; ii < dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                    dirFiles = null;
                }
            }
            // if no directory exists, create new directory to store test
            // results
            if (!directory.exists()) {
                directory.mkdir();
            }
        }// end of SD card checking

add permissions on your manifest.xml

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

Happy coding..

http://localhost:50070 does not work HADOOP

If you can open the http://localhost:8088/cluster but can't open http://localhost:50070/. Maybe datanode didn't start-up or namenode didn't formate.

Hadoop version 2.6.4

  • step 1:

check whether your namenode has been formated, if not type:

$ stop-all.sh
$ /path/to/hdfs namenode -format
$ start-all.sh
  • step 2:

check your namenode tmp file path, to see in /tmp, if the namenode directory is in /tmp, you need set tmp path in core-site.xml, because every time when you reboot or start your machine, the files in /tmp will be removed, you need set a tmp dir path.

add the following to it.

<property>
    <name>hadoop.tmp.dir</name>
    <value>/path/to/hadoop/tmp</value>
</property>
  • step 3:

check step 2, stop hadoop and remove the namenode tmp dir in /tmp, then type /path/to/hdfs namenode -format, and start the hadoop. The is also a tmp dir in $HADOOP_HOME

If all the above don't help, please comment below!

Restart container within pod

There are cases when you want to restart a specific container instead of deleting the pod and letting Kubernetes recreate it.

Doing a kubectl exec POD_NAME -c CONTAINER_NAME /sbin/killall5 worked for me.

(I changed the command from reboot to /sbin/killall5 based on the below recommendations.)

Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH

This can be caused by a full disk (Ubuntu/Nginx).

My situation:

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

There can be one more reason for such behavior - you delete current working directory.

For example:

# in terminal #1
cd /home/user/myJavaApp

# in terminal #2
rm -rf /home/user/myJavaApp

# in terminal #1
java -jar myJar.jar

Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

How do I script a "yes" response for installing programs?

echo y | command should work.

Also, some installers have an "auto-yes" flag. It's -y for apt-get on Ubuntu.

React passing parameter via onclick event using ES6 syntax

in function component, this works great - a new React user since 2020 :)

handleRemove = (e, id) => {
    //removeById(id);
}

return(<button onClick={(e)=> handleRemove(e, id)}></button> )

Pandas create empty DataFrame with only column names

df.to_html() has a columns parameter.

Just pass the columns into the to_html() method.

df.to_html(columns=['A','B','C','D','E','F','G'])

Error message 'Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.'

This error has no true magic bullet answer. The key is to have all the information to understand the problem. Most likely a dynamically loaded assembly is missing a referenced assembly. That assembly needs to be in the bin directory of your application.

Use this code to determine what is missing.

using System.IO;
using System.Reflection;
using System.Text;

try
{
    //The code that causes the error goes here.
}
catch (ReflectionTypeLoadException ex)
{
    StringBuilder sb = new StringBuilder();
    foreach (Exception exSub in ex.LoaderExceptions)
    {
        sb.AppendLine(exSub.Message);
        FileNotFoundException exFileNotFound = exSub as FileNotFoundException;
        if (exFileNotFound != null)
        {                
            if(!string.IsNullOrEmpty(exFileNotFound.FusionLog))
            {
                sb.AppendLine("Fusion Log:");
                sb.AppendLine(exFileNotFound.FusionLog);
            }
        }
        sb.AppendLine();
    }
    string errorMessage = sb.ToString();
    //Display or log the error based on your application.
}

How to send 500 Internal Server Error error from a PHP script

PHP 5.4 has a function called http_response_code, so if you're using PHP 5.4 you can just do:

http_response_code(500);

I've written a polyfill for this function (Gist) if you're running a version of PHP under 5.4.


To answer your follow-up question, the HTTP 1.1 RFC says:

The reason phrases listed here are only recommendations -- they MAY be replaced by local equivalents without affecting the protocol.

That means you can use whatever text you want (excluding carriage returns or line feeds) after the code itself, and it'll work. Generally, though, there's usually a better response code to use. For example, instead of using a 500 for no record found, you could send a 404 (not found), and for something like "conditions failed" (I'm guessing a validation error), you could send something like a 422 (unprocessable entity).

Extracting jar to specified directory

This worked for me.

I created a folder then changed into the folder using CD option from command prompt.

Then executed the jar from there.

d:\LS\afterchange>jar xvf ..\mywar.war

Android ListView Divider

This is a workaround, but works for me:

Created res/drawable/divider.xml as follows:

<?xml version="1.0" encoding="UTF-8"?>
<shape
  xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient android:startColor="#ffcdcdcd" android:endColor="#ffcdcdcd" android:angle="270.0" />
</shape>

And in styles.xml for listview item, I added the following lines:

    <item name="android:divider">@drawable/divider</item>
    <item name="android:dividerHeight">1px</item>

Crucial part was to include this 1px setting. Of course, drawable uses gradient (with 1px) and that's not the optimal solution. I tried using stroke but didn't get it to work. (You don't seem to use styles, so just add android:dividerHeight="1px" attribute for the ListView.

C compile error: Id returned 1 exit status

I may guess, the old instance of your program is still running. Windows does not allow to change the files which are currently "in use" and your linker cannot write the new .exe on the top of the running one. Try stopping/killing your program.

How to fix "no valid 'aps-environment' entitlement string found for application" in Xcode 4.3?

Ok, I faced the problem before. Since push notification requires serverside implementation, for me recreating profile was not an option. So I found this solution WITHOUT creating new provisioning profile.

Xcode is not properly selecting the correct provisioning profile although we are selecting it correctly.

First go to organizer. On the Devices tab, Provisioning profile from Library list, select the intended profile we are trying to use. Right click on it and then "Reveal Profile in Finder".

enter image description here

The correct profile will be selected in the opened Finder window. Note the name.

enter image description here

Now go to Xcode > Log Navigator. Select filter for "All" and "All Messages". Now in the last phase(Build Target) look for the step called "ProcessProductPackaging" expand it. Note the provisioning profile name. They should NOT match if you are having the error. enter image description here

Now in the Opened Finder window delete the rogue provisioning profile which Xcode is using. Now build again. The error should be resolved. If not repeat the process to find another rogue profile to remove it.

Hope this helps.

Maximum length of HTTP GET request

As already mentioned, HTTP itself doesn't impose any hard-coded limit on request length; but browsers have limits ranging on the 2048 character allowed in the GET method.

How to obtain the last index of a list?

the best and fast way to obtain last index of a list is using -1 for number of index , for example:

my_list = [0, 1, 'test', 2, 'hi']
print(my_list[-1])

out put is : 'hi'. index -1 in show you last index or first index of the end.

ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration

Tip #2

Can't you use the classical 2> redirection operator.

(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) 2> $NULL
if(!$?){
   'foo'
}

I don't like errors so I avoid them at all costs.

Remove Trailing Spaces and Update in Columns in SQL Server

If you are using SQL Server (starting with vNext) or Azure SQL Database then you can use the below query.

SELECT TRIM(ColumnName) from TableName;

For other SQL SERVER Database you can use the below query.

SELECT LTRIM(RTRIM(ColumnName)) from TableName

LTRIM - Removes spaces from the left

example: select LTRIM(' test ') as trim = 'test '

RTRIM - Removes spaces from the right

example: select RTRIM(' test ') as trim = ' test'

How to use '-prune' option of 'find' in sh?

If you read all the good answers here my understanding now is that the following all return the same results:

find . -path ./dir1\*  -prune -o -print

find . -path ./dir1  -prune -o -print

find . -path ./dir1\*  -o -print
#look no prune at all!

But the last one will take a lot longer as it still searches out everything in dir1. I guess the real question is how to -or out unwanted results without actually searching them.

So I guess prune means don't decent past matches but mark it as done...

http://www.gnu.org/software/findutils/manual/html_mono/find.html "This however is not due to the effect of the ‘-prune’ action (which only prevents further descent, it doesn't make sure we ignore that item). Instead, this effect is due to the use of ‘-o’. Since the left hand side of the “or” condition has succeeded for ./src/emacs, it is not necessary to evaluate the right-hand-side (‘-print’) at all for this particular file."

Why does pycharm propose to change method to static

I can imagine following advantages of having a class method defined as static one:

  • you can call the method just using class name, no need to instantiate it.

remaining advantages are probably marginal if present at all:

  • might run a bit faster
  • save a bit of memory

ADB device list is empty

This helped me at the end:

Quick guide:

  • Download Google USB Driver

  • Connect your device with Android Debugging enabled to your PC

  • Open Device Manager of Windows from System Properties.

  • Your device should appear under Other devices listed as something like Android ADB Interface or 'Android Phone' or similar. Right-click that and click on Update Driver Software...

  • Select Browse my computer for driver software

  • Select Let me pick from a list of device drivers on my computer

  • Double-click Show all devices

  • Press the Have disk button

  • Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf

  • Select Android ADB Interface from the list of device types.

  • Press the Yes button

  • Press the Install button

  • Press the Close button

Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.

Saving a select count(*) value to an integer (SQL Server)

[update] -- Well, my own foolishness provides the answer to this one. As it turns out, I was deleting the records from myTable before running the select COUNT statement.

How did I do that and not notice? Glad you asked. I've been testing a sql unit testing platform (tsqlunit, if you're interested) and as part of one of the tests I ran a truncate table statement, then the above. After the unit test is over everything is rolled back, and records are back in myTable. That's why I got a record count outside of my tests.

Sorry everyone...thanks for your help.

Apply jQuery datepicker to multiple instances

The obvious answer would be to generate different ids, a separate id for each text box, something like

[int i=0]
<% Using Html.BeginForm()%>
<% For Each item In Model.MyRecords%>
[i++]
<%=Html.TextBox("my_date[i]")%> <br/>
<% Next%>
<% End Using%>

I don't know ASP.net so I just added some general C-like syntax code within square brackets. Translating it to actual ASP.net code shouldn't be a problem.

Then, you have to find a way to generate as many

$('#my_date[i]').datepicker();

as items in your Model.MyRecords. Again, within square brackets is your counter, so your jQuery function would be something like:

<script type="text/javascript">
    $(function() {
        $('#my_date1').datepicker();
        $('#my_date2').datepicker();
        $('#my_date3').datepicker();
        ...
    });
</script>

Space between Column's children in Flutter

The same way SizedBox is used above for the purpose of code readability, you can use the Padding widget in the same manner and not have to make it a parent widget to any of the Column's children

Column(
  children: <Widget>[
    FirstWidget(),
    Padding(padding: EdgeInsets.only(top: 40.0)),
    SecondWidget(),
  ]
)

Escape curly brace '{' in String.Format

Use double braces {{ or }} so your code becomes:

sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}", 
prop.Type, prop.Name));

// For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
// public Foo Bar { get; private set; }

Include in SELECT a column that isn't actually in the database

You may want to use:

SELECT Name, 'Unpaid' AS Status FROM table;

The SELECT clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:

SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ] 
<select_list> 

Where the expression can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.

What is the difference between 127.0.0.1 and localhost

There is nothing different. One is easier to remember than the other. Generally, you define a name to associate with an IP address. You don't have to specify localhost for 127.0.0.1, you could specify any name you want.

Static Final Variable in Java

For the primitive types, the 'final static' will be a proper declaration to declare a constant. A non-static final variable makes sense when it is a constant reference to an object. In this case each instance can contain its own reference, as shown in JLS 4.5.4.

See Pavel's response for the correct answer.

How should the ViewModel close the form?

I used attached behaviours to close the window. Bind a "signal" property on your ViewModel to the attached behaviour (I actually use a trigger) When it's set to true, the behaviour closes the window.

http://adammills.wordpress.com/2009/07/01/window-close-from-xaml/

How to query values from xml nodes?

Try this:

SELECT RawXML.value('(/GrobXmlFile//Grob//ReportHeader//OrganizationReportReferenceIdentifier/node())[1]','varchar(50)') AS ReportIdentifierNumber,
       RawXML.value('(/GrobXmlFile//Grob//ReportHeader//OrganizationNumber/node())[1]','int') AS OrginazationNumber
FROM Batches

What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS?

I am deploying VB6 IIS Applications to my remote dedicated server with 75 folders. The reason I was getting this error is the Default Document was not set on one of the folders, an oversight, so the URL hitting that folder did not know which page to server up, and thus threw the error mentioned in this thread.

Where do I call the BatchNormalization function in Keras?

Keras now supports the use_bias=False option, so we can save some computation by writing like

model.add(Dense(64, use_bias=False))
model.add(BatchNormalization(axis=bn_axis))
model.add(Activation('tanh'))

or

model.add(Convolution2D(64, 3, 3, use_bias=False))
model.add(BatchNormalization(axis=bn_axis))
model.add(Activation('relu'))

Postgres: How to convert a json string to text?

Mr. Curious was curious about this as well. In addition to the #>> '{}' operator, in 9.6+ one can get the value of a jsonb string with the ->> operator:

select to_jsonb('Some "text"'::TEXT)->>0;
  ?column?
-------------
 Some "text"
(1 row)

If one has a json value, then the solution is to cast into jsonb first:

select to_json('Some "text"'::TEXT)::jsonb->>0;
  ?column?
-------------
 Some "text"
(1 row)

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

On top of @unutbu answer, you could coerce pandas numpy object array to native (float64) type, something along the line

import pandas as pd
pd.to_numeric(df['tester'], errors='coerce')

Specify errors='coerce' to force strings that can't be parsed to a numeric value to become NaN. Column type would be dtype: float64, and then isnan check should work

How to get diff between all files inside 2 folders that are on the web?

You urls are not in the same repository, so you can't do it with the svn diff command.

svn: 'http://svn.boost.org/svn/boost/sandbox/boost/extension' isn't in the same repository as 'http://cloudobserver.googlecode.com/svn'

Another way you could do it, is export each repos using svn export, and then use the diff command to compare the 2 directories you exported.

// Export repositories
svn export http://svn.boost.org/svn/boost/sandbox/boost/extension/ repos1
svn export http://cloudobserver.googlecode.com/svn/branches/v0.4/Boost.Extension.Tutorial/libs/boost/extension/ repos2

// Compare exported directories
diff repos1 repos2 > file.diff

How to make Toolbar transparent?

Just add android:background="@android:color/transparent" like below in your appbar layout

<android.support.design.widget.AppBarLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:background="@android:color/transparent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>`

Check if a string is palindrome

bool IsPalindrome(const char* psz)
{
    int i = 0;
    int j;

    if ((psz == NULL) || (psz[0] == '\0'))
    {
        return false;
    }

    j = strlen(psz) - 1;
    while (i < j)
    {
        if (psz[i] != psz[j])
        {
            return false;
        }
        i++;
        j--;
    }
    return true;

}

// STL string version:

bool IsPalindrome(const string& str)
{
    if (str.empty())
        return false;

    int i = 0;                // first characters
    int j = str.length() - 1; // last character

    while (i < j)
    {
        if (str[i] != str[j])
        {
            return false;
        }
        i++;
        j--;
    }
    return true;
}

How to find Current open Cursors in Oracle

1)your id should have sys dba access 2)

select sum(a.value) total_cur, avg(a.value) avg_cur, max(a.value) max_cur, 
 s.username, s.machine
 from v$sesstat a, v$statname b, v$session s 
 where a.statistic# = b.statistic# and s.sid=a.sid
 and b.name = 'opened cursors current' 
 group by s.username, s.machine
 order by 1 desc;

Fetching data from MySQL database to html dropdown list

To do this you want to loop through each row of your query results and use this info for each of your drop down's options. You should be able to adjust the code below fairly easily to meet your needs.

// Assume $db is a PDO object
$query = $db->query("YOUR QUERY HERE"); // Run your query

echo '<select name="DROP DOWN NAME">'; // Open your drop down box

// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
   echo '<option value="'.$row['something'].'">'.$row['something'].'</option>';
}

echo '</select>';// Close your drop down box

How do I use 3DES encryption/decryption in Java?

Your code was fine except for the Base 64 encoding bit (which you mentioned was a test), the reason the output may not have made sense is that you were displaying a raw byte array (doing toString() on a byte array returns its internal Java reference, not the String representation of the contents). Here's a version that's just a teeny bit cleaned up and which prints "kyle boon" as the decoded string:

import java.security.MessageDigest;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class TripleDESTest {

    public static void main(String[] args) throws Exception {

        String text = "kyle boon";

        byte[] codedtext = new TripleDESTest().encrypt(text);
        String decodedtext = new TripleDESTest().decrypt(codedtext);

        System.out.println(codedtext); // this is a byte array, you'll just see a reference to an array
        System.out.println(decodedtext); // This correctly shows "kyle boon"
    }

    public byte[] encrypt(String message) throws Exception {
        final MessageDigest md = MessageDigest.getInstance("md5");
        final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
                .getBytes("utf-8"));
        final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        for (int j = 0, k = 16; j < 8;) {
            keyBytes[k++] = keyBytes[j++];
        }

        final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
        final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
        final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);

        final byte[] plainTextBytes = message.getBytes("utf-8");
        final byte[] cipherText = cipher.doFinal(plainTextBytes);
        // final String encodedCipherText = new sun.misc.BASE64Encoder()
        // .encode(cipherText);

        return cipherText;
    }

    public String decrypt(byte[] message) throws Exception {
        final MessageDigest md = MessageDigest.getInstance("md5");
        final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
                .getBytes("utf-8"));
        final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        for (int j = 0, k = 16; j < 8;) {
            keyBytes[k++] = keyBytes[j++];
        }

        final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
        final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
        final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        decipher.init(Cipher.DECRYPT_MODE, key, iv);

        // final byte[] encData = new
        // sun.misc.BASE64Decoder().decodeBuffer(message);
        final byte[] plainText = decipher.doFinal(message);

        return new String(plainText, "UTF-8");
    }
}

How to transform array to comma separated words string?

Make your array a variable and use implode.

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

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

How to write a cron that will run a script every day at midnight?

Quick guide to setup a cron job

Create a new text file, example: mycronjobs.txt

For each daily job (00:00, 03:45), save the schedule lines in mycronjobs.txt

00 00 * * * ruby path/to/your/script.rb
45 03 * * * path/to/your/script2.sh

Send the jobs to cron (everytime you run this, cron deletes what has been stored and updates with the new information in mycronjobs.txt)

crontab mycronjobs.txt

Extra Useful Information

See current cron jobs

crontab -l

Remove all cron jobs

crontab -r

CSS selector - element with a given child

I agree that it is not possible in general.

The only thing CSS3 can do (which helped in my case) is to select elements that have no children:

table td:empty
{
   background-color: white;
}

Or have any children (including text):

table td:not(:empty)
{
   background-color: white;
}

implementing merge sort in C++

Based on the code here: http://cplusplus.happycodings.com/algorithms/code17.html

// Merge Sort

#include <iostream>
using namespace std;

int a[50];
void merge(int,int,int);
void merge_sort(int low,int high)
{
 int mid;
 if(low<high)
 {
  mid = low + (high-low)/2; //This avoids overflow when low, high are too large
  merge_sort(low,mid);
  merge_sort(mid+1,high);
  merge(low,mid,high);
 }
}
void merge(int low,int mid,int high)
{
 int h,i,j,b[50],k;
 h=low;
 i=low;
 j=mid+1;

 while((h<=mid)&&(j<=high))
 {
  if(a[h]<=a[j])
  {
   b[i]=a[h];
   h++;
  }
  else
  {
   b[i]=a[j];
   j++;
  }
  i++;
 }
 if(h>mid)
 {
  for(k=j;k<=high;k++)
  {
   b[i]=a[k];
   i++;
  }
 }
 else
 {
  for(k=h;k<=mid;k++)
  {
   b[i]=a[k];
   i++;
  }
 }
 for(k=low;k<=high;k++) a[k]=b[k];
}
int main()
{
 int num,i;

cout<<"*******************************************************************
*************"<<endl;
 cout<<"                             MERGE SORT PROGRAM
"<<endl;

cout<<"*******************************************************************
*************"<<endl;
 cout<<endl<<endl;
 cout<<"Please Enter THE NUMBER OF ELEMENTS you want to sort [THEN 
PRESS
ENTER]:"<<endl;
 cin>>num;
 cout<<endl;
 cout<<"Now, Please Enter the ( "<< num <<" ) numbers (ELEMENTS) [THEN
PRESS ENTER]:"<<endl;
 for(i=1;i<=num;i++)
 {
  cin>>a[i] ;
 }
 merge_sort(1,num);
 cout<<endl;
 cout<<"So, the sorted list (using MERGE SORT) will be :"<<endl;
 cout<<endl<<endl;

 for(i=1;i<=num;i++)
 cout<<a[i]<<"  ";

 cout<<endl<<endl<<endl<<endl;
return 1;

}

MySQL remove all whitespaces from the entire column

Just use the following sql, you are done:

SELECT replace(CustomerName,' ', '') FROM Customers;

you can test this sample over here: W3School

How to select all records from one table that do not exist in another table?

I don't have enough rep points to vote up froadie's answer. But I have to disagree with the comments on Kris's answer. The following answer:

SELECT name
FROM table2
WHERE name NOT IN
    (SELECT name 
     FROM table1)

Is FAR more efficient in practice. I don't know why, but I'm running it against 800k+ records and the difference is tremendous with the advantage given to the 2nd answer posted above. Just my $0.02.

How to redirect Valgrind's output to a file?

valgrind --log-file="filename"

How to make a round button?

Round button in Android

You can make a ImageButton with circular background image.

How do I get the value of a textbox using jQuery?

Use the .val() method.

Also I think you meant to use $("#txtEmail") as $("txtEmail") returns elements of type <txtEmail> which you probably don't have.

See here at the jQuery documentation.

Also jQuery val() method.

cannot redeclare block scoped variable (typescript)

The best explanation I could get is from Tamas Piro's post.

TLDR; TypeScript uses the DOM typings for the global execution environment. In your case there is a 'co' property on the global window object.

To solve this:

  1. Rename the variable, or
  2. Use TypeScript modules, and add an empty export{}:
export {};

or

  1. Configure your compiler options by not adding DOM typings:

Edit tsconfig.json in the TypeScript project directory.

{
    "compilerOptions": {
        "lib": ["es6"]
      }
}

Java Singleton and Synchronization

You can also use static code block to instantiate the instance at class load and prevent the thread synchronization issues.

public class MySingleton {

  private static final MySingleton instance;

  static {
     instance = new MySingleton();
  }

  private MySingleton() {
  }

  public static MySingleton getInstance() {
    return instance;
  }

}

How do I get rid of the "cannot empty the clipboard" error?

check this tip. worked for here http://mobeer.blogspot.com/2009/01/excel-2007-cannot-empty-clipboard.html:

This might save somebody some time and headaches if google picks it up. I was getting a 'Cannot empty the Clipboard' error every time I moved cells around in Excel - eventually I mucked around with the settings and made it go away. Here's how; In the excel main menu (glass globe w/logo), click Excel options, then Advanced, then turn off 'Show paste options buttons'

How exciting was this as my first post of the year?

Update: I still haven't found a permanent solution but I found another thing that seems to help. In Excel 2007, from the "home" tab, the first thing on the left is the clipboard tool panel. Expand the panel to view the clipboard and in the clipboard you might find "cannot empty clipboard" as an entry. Empty the clipboard, keep the panel open for a second or two while you do a few cut and pastes/drags etc. and then the bogey seems to go away.

I call this the cable dance because back in the day I had a printer that only worked if you unplugged the cable, shook it out and plugged it back in.

Write objects into file with Node.js

If you're geting [object object] then use JSON.stringify

fs.writeFile('./data.json', JSON.stringify(obj) , 'utf-8');

It worked for me.

Spark dataframe: collect () vs select ()

Select is used for projecting some or all fields of a dataframe. It won't give you an value as an output but a new dataframe. Its a transformation.

What does servletcontext.getRealPath("/") mean and when should I use it

Introduction

The ServletContext#getRealPath() is intented to convert a web content path (the path in the expanded WAR folder structure on the server's disk file system) to an absolute disk file system path.

The "/" represents the web content root. I.e. it represents the web folder as in the below project structure:

YourWebProject
 |-- src
 |    :
 |
 |-- web
 |    |-- META-INF
 |    |    `-- MANIFEST.MF
 |    |-- WEB-INF
 |    |    `-- web.xml
 |    |-- index.jsp
 |    `-- login.jsp
 :    

So, passing the "/" to getRealPath() would return you the absolute disk file system path of the /web folder of the expanded WAR file of the project. Something like /path/to/server/work/folder/some.war/ which you should be able to further use in File or FileInputStream.

Note that most starters don't seem to see/realize that you can actually pass the whole web content path to it and that they often use

String absolutePathToIndexJSP = servletContext.getRealPath("/") + "index.jsp"; // Wrong!

or even

String absolutePathToIndexJSP = servletContext.getRealPath("") + "index.jsp"; // Wronger!

instead of

String absolutePathToIndexJSP = servletContext.getRealPath("/index.jsp"); // Right!

Don't ever write files in there

Also note that even though you can write new files into it using FileOutputStream, all changes (e.g. new files or edited files) will get lost whenever the WAR is redeployed; with the simple reason that all those changes are not contained in the original WAR file. So all starters who are attempting to save uploaded files in there are doing it wrong.

Moreover, getRealPath() will always return null or a completely unexpected path when the server isn't configured to expand the WAR file into the disk file system, but instead into e.g. memory as a virtual file system.

getRealPath() is unportable; you'd better never use it

Use getRealPath() carefully. There are actually no sensible real world use cases for it. Based on my 20 years of Java EE experience, there has always been another way which is much better and more portable than getRealPath().

If all you actually need is to get an InputStream of the web resource, better use ServletContext#getResourceAsStream() instead, this will work regardless of the way how the WAR is expanded. So, if you for example want an InputStream of index.jsp, then do not do:

InputStream input = new FileInputStream(servletContext.getRealPath("/index.jsp")); // Wrong!

But instead do:

InputStream input = servletContext.getResourceAsStream("/index.jsp"); // Right!

Or if you intend to obtain a list of all available web resource paths, use ServletContext#getResourcePaths() instead.

Set<String> resourcePaths = servletContext.getResourcePaths("/");

You can obtain an individual resource as URL via ServletContext#getResource(). This will return null when the resource does not exist.

URL resource = servletContext.getResource(path);

Or if you intend to save an uploaded file, or create a temporary file, then see the below "See also" links.

See also:

The type WebMvcConfigurerAdapter is deprecated

I have been working on Swagger equivalent documentation library called Springfox nowadays and I found that in the Spring 5.0.8 (running at present), interface WebMvcConfigurer has been implemented by class WebMvcConfigurationSupport class which we can directly extend.

import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

public class WebConfig extends WebMvcConfigurationSupport { }

And this is how I have used it for setting my resource handling mechanism as follows -

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
            .addResourceLocations("classpath:/META-INF/resources/");

    registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");
}

How do I link a JavaScript file to a HTML file?

To include an external Javascript file you use the <script> tag. The src attribute points to the location of your Javascript file within your web project.

<script src="some.js" type="text/javascript"></script>

JQuery is simply a Javascript file, so if you download a copy of the file you can include it within your page using a script tag. You can also include Jquery from a content distribution network such as the one hosted by Google.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

mySQL convert varchar to date

select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m'); 

or

select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m'); 

hard to tell from your example

How to see if a directory exists or not in Perl?

Use -d (full list of file tests)

if (-d "cgi-bin") {
    # directory called cgi-bin exists
}
elsif (-e "cgi-bin") {
    # cgi-bin exists but is not a directory
}
else {
    # nothing called cgi-bin exists
}

As a note, -e doesn't distinguish between files and directories. To check if something exists and is a plain file, use -f.

Passing an array by reference

The following creates a generic function, taking an array of any size and of any type by reference:

template<typename T, std::size_t S>
void my_func(T (&arr)[S]) {
   // do stuff
}

play with the code.

How to read data from java properties file using Spring Boot

i would suggest the following way:

@PropertySource(ignoreResourceNotFound = true, value = "classpath:otherprops.properties")
@Controller
public class ClassA {
    @Value("${myName}")
    private String name;

    @RequestMapping(value = "/xyz")
    @ResponseBody
    public void getName(){
        System.out.println(name);
    }
}

Here your new properties file name is "otherprops.properties" and the property name is "myName". This is the simplest implementation to access properties file in spring boot version 1.5.8.

How do I test which class an object is in Objective-C?

if you want to get the name of the class simply call:-

id yourObject= [AnotherClass returningObject];

NSString *className=[yourObject className];

NSLog(@"Class name is : %@",className);

How to show one layout on top of the other programmatically in my case?

The answer, given by Alexandru is working quite nice. As he said, it is important that this "accessor"-view is added as the last element. Here is some code which did the trick for me:

        ...

        ...

            </LinearLayout>

        </LinearLayout>

    </FrameLayout>

</LinearLayout>

<!-- place a FrameLayout (match_parent) as the last child -->
<FrameLayout
    android:id="@+id/icon_frame_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout>

</TabHost>

in Java:

final MaterialDialog materialDialog = (MaterialDialog) dialogInterface;

FrameLayout frameLayout = (FrameLayout) materialDialog
        .findViewById(R.id.icon_frame_container);

frameLayout.setOnTouchListener(
        new OnSwipeTouchListener(ShowCardActivity.this) {

Error inflating class android.support.v7.widget.Toolbar?

I faced with same problem. Solution that worked for me. If you use v7.Toolbar you must use theme extended from Theme.AppCompat.* You can't use theme extended from android:Theme.Material.* because they have different style attributes.

Hope it will helpful.

Insert current date in datetime format mySQL

Just use with your timezone :

date_default_timezone_set('Asia/Kolkata');      
$date=date("Y/m/d h:i:sa");

Get file from project folder java

If you are trying to load a file which is not in the same directory as your Java class, you've got to use the runtime directory structure rather than the one which appears at design time.

To find out what the runtime directory structure is, check your {root project dir}/target/classes directory. This directory is accessible via the "." URL.

Based on user4284592's answer, the following worked for me:

ClassLoader cl = getClass().getClassLoader();
File file = new File(cl.getResource("./docs/doc.pdf").getFile());

with the following directory structure:

{root dir}/target/classes/docs/doc.pdf

Here's an explanation, so you don't just blindly copy and paste my code:

  • java.lang.ClassLoader is an object that is responsible for loading classes. Every Class object contains a reference to the ClassLoader that defined it and can fetch it with getClassLoader() method.
  • ClassLoader's getResource method finds the resource with the given name. A resource is some data that can be accessed by class code in a way that is independent of the location of the code.

Creating a BLOB from a Base64 string in JavaScript

Here is a more minimal method without any dependencies or libraries.
It requires the new fetch API. (Can I use it?)

_x000D_
_x000D_
var url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="

fetch(url)
.then(res => res.blob())
.then(console.log)
_x000D_
_x000D_
_x000D_

With this method you can also easily get a ReadableStream, ArrayBuffer, text, and JSON.
(fyi this also works with node-fetch in Node)

As a function:

const b64toBlob = (base64, type = 'application/octet-stream') => 
  fetch(`data:${type};base64,${base64}`).then(res => res.blob())

I did a simple performance test towards Jeremy's ES6 sync version.
The sync version will block UI for a while. keeping the devtool open can slow the fetch performance

_x000D_
_x000D_
document.body.innerHTML += '<input autofocus placeholder="try writing">'
// get some dummy gradient image
var img=function(){var a=document.createElement("canvas"),b=a.getContext("2d"),c=b.createLinearGradient(0,0,1500,1500);a.width=a.height=3000;c.addColorStop(0,"red");c.addColorStop(1,"blue");b.fillStyle=c;b.fillRect(0,0,a.width,a.height);return a.toDataURL()}();


async function perf() {
  
  const blob = await fetch(img).then(res => res.blob())
  // turn it to a dataURI
  const url = img
  const b64Data = url.split(',')[1]

  // Jeremy Banks solution
  const b64toBlob = (b64Data, contentType = '', sliceSize=512) => {
    const byteCharacters = atob(b64Data);
    const byteArrays = [];
    
    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
      const slice = byteCharacters.slice(offset, offset + sliceSize);
      
      const byteNumbers = new Array(slice.length);
      for (let i = 0; i < slice.length; i++) {
        byteNumbers[i] = slice.charCodeAt(i);
      }
      
      const byteArray = new Uint8Array(byteNumbers);
      
      byteArrays.push(byteArray);
    }
    
    const blob = new Blob(byteArrays, {type: contentType});
    return blob;
  }

  // bench blocking method
  let i = 500
  console.time('blocking b64')
  while (i--) {
    await b64toBlob(b64Data)
  }
  console.timeEnd('blocking b64')
  
  // bench non blocking
  i = 500

  // so that the function is not reconstructed each time
  const toBlob = res => res.blob()
  console.time('fetch')
  while (i--) {
    await fetch(url).then(toBlob)
  }
  console.timeEnd('fetch')
  console.log('done')
}

perf()
_x000D_
_x000D_
_x000D_

Select specific row from mysql table

SET @customerID=0;
SELECT @customerID:=@customerID+1 AS customerID
FROM CUSTOMER ;

you can obtain the dataset from SQL like this and populate it into a java data structure (like a List) and then make the necessary sorting over there. (maybe with the help of a comparable interface)

What is the standard exception to throw in Java for not supported/implemented operations?

Differentiate between the two cases you named:

How to sort a HashSet?

Elements in HashSet can't be sorted. Whenever you put elements into HashSet, it can mess up the ordering of the whole set. It is deliberately designed like that for performance. When you don't care about the order, HashSet will be the most efficient set for fast insertion and search.

TreeSet will sort all the elements automatically every time you insert an element.

Perhaps, what you are trying to do is to sort just once. In that case, TreeSet is not the best option because it needs to determine the placing of newly added elements all the time.

The most efficient solution is to use ArrayList. Create a new list and add all the elements then sort it once. If you want to retain only unique elements (remove all duplicates like set does, then put the list into a LinkedHashSet, it will retain the order you have already sorted)

List<Integer> list = new ArrayList<>();
list.add(6);
list.add(4);
list.add(4);
list.add(5);
Collections.sort(list);
Set<Integer> unique = new LinkedHashSet<>(list); // 4 5 6
// The above line is not copying the objects! It only copies references.

Now, you've gotten a sorted set if you want it in a list form then convert it into list.

Auto-indent in Notepad++

Menu TextFX ? TextFX Edit ? Reindent C++ code

enter image description here

But, Notepad++ doesn't come with this "Text FX Character" plugin. You will need to install it via

Plugins ? Plugin Manager ? Show Plugin Manager.

To add shortcut for Indentation.

Click on Settings ? Shortcut Mapper... set the shortcut key you prefer. I prefer Ctrl + =.

Enter image description here