Programs & Examples On #Verification

Verification checks whether a product complies with specifications and further fixed conditions.

ssh remote host identification has changed

If you are trying to connect to running docker container on port 2222 with the command and you get the error

mian@tdowrick2~$ ssh pos@localhost -p 2222

Then to solve this problem, on your local computer (i.e. host machine not container) go to cd ~/.ssh/ and open known_hosts file with text editor. Remove the line starting with [localhost]:2222 and save the file. Now try to ssh again

mian@tdowrick2~$ ssh pos@localhost -p 2222

Error will disappear but you have to do it each time the container restart.

Validate SSL certificates with Python

Here's an example script which demonstrates certificate validation:

import httplib
import re
import socket
import sys
import urllib2
import ssl

class InvalidCertificateException(httplib.HTTPException, urllib2.URLError):
    def __init__(self, host, cert, reason):
        httplib.HTTPException.__init__(self)
        self.host = host
        self.cert = cert
        self.reason = reason

    def __str__(self):
        return ('Host %s returned an invalid certificate (%s) %s\n' %
                (self.host, self.reason, self.cert))

class CertValidatingHTTPSConnection(httplib.HTTPConnection):
    default_port = httplib.HTTPS_PORT

    def __init__(self, host, port=None, key_file=None, cert_file=None,
                             ca_certs=None, strict=None, **kwargs):
        httplib.HTTPConnection.__init__(self, host, port, strict, **kwargs)
        self.key_file = key_file
        self.cert_file = cert_file
        self.ca_certs = ca_certs
        if self.ca_certs:
            self.cert_reqs = ssl.CERT_REQUIRED
        else:
            self.cert_reqs = ssl.CERT_NONE

    def _GetValidHostsForCert(self, cert):
        if 'subjectAltName' in cert:
            return [x[1] for x in cert['subjectAltName']
                         if x[0].lower() == 'dns']
        else:
            return [x[0][1] for x in cert['subject']
                            if x[0][0].lower() == 'commonname']

    def _ValidateCertificateHostname(self, cert, hostname):
        hosts = self._GetValidHostsForCert(cert)
        for host in hosts:
            host_re = host.replace('.', '\.').replace('*', '[^.]*')
            if re.search('^%s$' % (host_re,), hostname, re.I):
                return True
        return False

    def connect(self):
        sock = socket.create_connection((self.host, self.port))
        self.sock = ssl.wrap_socket(sock, keyfile=self.key_file,
                                          certfile=self.cert_file,
                                          cert_reqs=self.cert_reqs,
                                          ca_certs=self.ca_certs)
        if self.cert_reqs & ssl.CERT_REQUIRED:
            cert = self.sock.getpeercert()
            hostname = self.host.split(':', 0)[0]
            if not self._ValidateCertificateHostname(cert, hostname):
                raise InvalidCertificateException(hostname, cert,
                                                  'hostname mismatch')


class VerifiedHTTPSHandler(urllib2.HTTPSHandler):
    def __init__(self, **kwargs):
        urllib2.AbstractHTTPHandler.__init__(self)
        self._connection_args = kwargs

    def https_open(self, req):
        def http_class_wrapper(host, **kwargs):
            full_kwargs = dict(self._connection_args)
            full_kwargs.update(kwargs)
            return CertValidatingHTTPSConnection(host, **full_kwargs)

        try:
            return self.do_open(http_class_wrapper, req)
        except urllib2.URLError, e:
            if type(e.reason) == ssl.SSLError and e.reason.args[0] == 1:
                raise InvalidCertificateException(req.host, '',
                                                  e.reason.args[1])
            raise

    https_request = urllib2.HTTPSHandler.do_request_

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print "usage: python %s CA_CERT URL" % sys.argv[0]
        exit(2)

    handler = VerifiedHTTPSHandler(ca_certs = sys.argv[1])
    opener = urllib2.build_opener(handler)
    print opener.open(sys.argv[2]).read()

How much should a function trust another function

Such debugging is part of the development process and should not be the issue at runtime.

Methods don't trust other methods. They all trust you. That is the process of developing. Fix all bugs. Then methods don't have to "trust". There should be no doubt.

So, write it as it should be. Do not make methods check wether other methods are working correctly. That should be tested by the developer when they wrote that function. If you suspect a method to be not doing what you want, debug it.

How to delete items from a dictionary while iterating over it?

You could first build a list of keys to delete, and then iterate over that list deleting them.

dict = {'one' : 1, 'two' : 2, 'three' : 3, 'four' : 4}
delete = []
for k,v in dict.items():
    if v%2 == 1:
        delete.append(k)
for i in delete:
    del dict[i]

How to quickly and conveniently create a one element arraylist

Collections.singletonList(object)

the list created by this method is immutable.

Why is it not advisable to have the database and web server on the same machine?

I can speak from first hand experience that it is often a good idea to place the web server and database on different machines. If you have an application that is resource intensive, it can easily cause the CPU cycles on the machine to peak, essentially bringing the machine to a halt. However, if your application has limited use of the database, it would probably be no big deal to have them share a server.

What's the difference between unit, functional, acceptance, and integration tests?

Unit Testing - As the name suggests, this method tests at the object level. Individual software components are tested for any errors. Knowledge of the program is needed for this test and the test codes are created to check if the software behaves as it is intended to.

Functional Testing - Is carried out without any knowledge of the internal working of the system. The tester will try to use the system by just following requirements, by providing different inputs and testing the generated outputs. This test is also known as closed-box testing or black-box.

Acceptance Testing - This is the last test that is conducted before the software is handed over to the client. It is carried out to ensure that the developed software meets all the customer requirements. There are two types of acceptance testing - one that is carried out by the members of the development team, known as internal acceptance testing (Alpha testing), and the other that is carried out by the customer or end user known as (Beta testing)

Integration Testing - Individual modules that are already subjected to unit testing are integrated with one another. Generally the two approachs are followed :

1) Top-Down
2) Bottom-Up

How do I block comment in Jupyter notebook?

I add the same situation and went in a couple of stackoverfow, github and tutorials showing complex solutions. Nothing simple though! Some with "Hold the alt key and move the mouse while the cursor shows a cross" which is not for laptop users (at least for me), some others with configuration files...

I found it after a good sleep night. My environment is laptop, ubuntu and Jupyter/Ipython 5.1.0 :

Just select/highlight one line, a block or something, and then "Ctrl"+"/" and it's magic :)

How do I get user IP address in django?

In my case none of above works, so I have to check uwsgi + django source code and pass static param in nginx and see why/how, and below is what I have found.

Env info:
python version: 2.7.5
Django version: (1, 6, 6, 'final', 0)
nginx version: nginx/1.6.0
uwsgi: 2.0.7

Env setting info:
nginx as reverse proxy listening at port 80 uwsgi as upstream unix socket, will response to the request eventually

Django config info:

USE_X_FORWARDED_HOST = True # with or without this line does not matter

nginx config:

uwsgi_param      X-Real-IP              $remote_addr;
// uwsgi_param   X-Forwarded-For        $proxy_add_x_forwarded_for;
// uwsgi_param   HTTP_X_FORWARDED_FOR   $proxy_add_x_forwarded_for;

// hardcode for testing
uwsgi_param      X-Forwarded-For        "10.10.10.10";
uwsgi_param      HTTP_X_FORWARDED_FOR   "20.20.20.20";

getting all the params in django app:

X-Forwarded-For :       10.10.10.10
HTTP_X_FORWARDED_FOR :  20.20.20.20

Conclusion:

So basically, you have to specify exactly the same field/param name in nginx, and use request.META[field/param] in django app.

And now you can decide whether to add a middleware (interceptor) or just parse HTTP_X_FORWARDED_FOR in certain views.

Twitter API returns error 215, Bad Authentication Data

Be sure that you have read AND write access for application in twitter

ActiveRecord: size vs count

I recommended using the size function.

class Customer < ActiveRecord::Base
  has_many :customer_activities
end

class CustomerActivity < ActiveRecord::Base
  belongs_to :customer, counter_cache: true
end

Consider these two models. The customer has many customer activities.

If you use a :counter_cache on a has_many association, size will use the cached count directly, and not make an extra query at all.

Consider one example: in my database, one customer has 20,000 customer activities and I try to count the number of records of customer activities of that customer with each of count, length and size method. here below the benchmark report of all these methods.

            user     system      total        real
Count:     0.000000   0.000000   0.000000 (  0.006105)
Size:      0.010000   0.000000   0.010000 (  0.003797)
Length:    0.030000   0.000000   0.030000 (  0.026481)

so I found that using :counter_cache Size is the best option to calculate the number of records.

jQuery: select all elements of a given class, except for a particular Id

Use the :not selector.

$(".thisclass:not(#thisid)").doAction();

If you have multiple ids or selectors just use the comma delimiter, in addition:

(".thisclass:not(#thisid,#thatid)").doAction();

A simple jQuery form validation script

You can simply use the jQuery Validate plugin as follows.

jQuery:

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            field1: {
                required: true,
                email: true
            },
            field2: {
                required: true,
                minlength: 5
            }
        }
    });

});

HTML:

<form id="myform">
    <input type="text" name="field1" />
    <input type="text" name="field2" />
    <input type="submit" />
</form>

DEMO: http://jsfiddle.net/xs5vrrso/

Options: http://jqueryvalidation.org/validate

Methods: http://jqueryvalidation.org/category/plugin/

Standard Rules: http://jqueryvalidation.org/category/methods/

Optional Rules available with the additional-methods.js file:

maxWords
minWords
rangeWords
letterswithbasicpunc
alphanumeric
lettersonly
nowhitespace
ziprange
zipcodeUS
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
phonesUK
postcodeUK
strippedminlength
email2 (optional TLD)
url2 (optional TLD)
creditcardtypes
ipv4
ipv6
pattern
require_from_group
skip_or_fill_minimum
accept
extension

javascript Unable to get property 'value' of undefined or null reference

You can't access element like you did (document.frm_new_user_request). You have to use the function getElementById:

document.getElementById("frm_new_user_request")

So getting a value from an input could look like this:

var value = document.getElementById("frm_new_user_request").value

Also you can use some JavaScript framework, e.g. jQuery, which simplifies operations with DOM (Document Object Model) and also hides differences between various browsers from you.

Getting a value from an input using jQuery would look like this:

  • input with ID "element": var value = $("#element).value
  • input with class "element": var value = $(".element).value

Uncaught Typeerror: cannot read property 'innerHTML' of null

Update:

The question doesn't ask for jquery. So lets do it without jquery:

document.addEventListener("DOMContentLoaded", function(event) { 
    //Do work
});

Note this method will not work on IE8.

Old Answer:

You are calling this script before DOM is ready. If you write this code into jquery's $(function() method it will work.

How to write multiple conditions of if-statement in Robot Framework

The below code worked fine:

Run Keyword if    '${value1}' \ \ == \ \ '${cost1}' \ and \ \ '${value2}' \ \ == \ \ 'cost2'    LOG    HELLO

How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?

Hoisted from the comments

2020 comment: rather than using regex, we now have URLSearchParams, which does all of this for us, so no custom code, let alone regex, are necessary anymore.

Mike 'Pomax' Kamermans

Browser support is listed here https://caniuse.com/#feat=urlsearchparams


I would suggest an alternative regex, using sub-groups to capture name and value of the parameters individually and re.exec():

function getUrlParams(url) {
  var re = /(?:\?|&(?:amp;)?)([^=&#]+)(?:=?([^&#]*))/g,
      match, params = {},
      decode = function (s) {return decodeURIComponent(s.replace(/\+/g, " "));};

  if (typeof url == "undefined") url = document.location.href;

  while (match = re.exec(url)) {
    params[decode(match[1])] = decode(match[2]);
  }
  return params;
}

var result = getUrlParams("http://maps.google.de/maps?f=q&source=s_q&hl=de&geocode=&q=Frankfurt+am+Main&sll=50.106047,8.679886&sspn=0.370369,0.833588&ie=UTF8&ll=50.116616,8.680573&spn=0.35972,0.833588&z=11&iwloc=addr");

result is an object:

{
  f: "q"
  geocode: ""
  hl: "de"
  ie: "UTF8"
  iwloc: "addr"
  ll: "50.116616,8.680573"
  q: "Frankfurt am Main"
  sll: "50.106047,8.679886"
  source: "s_q"
  spn: "0.35972,0.833588"
  sspn: "0.370369,0.833588"
  z: "11"
}

The regex breaks down as follows:

(?:            # non-capturing group
  \?|&         #   "?" or "&"
  (?:amp;)?    #   (allow "&amp;", for wrongly HTML-encoded URLs)
)              # end non-capturing group
(              # group 1
  [^=&#]+      #   any character except "=", "&" or "#"; at least once
)              # end group 1 - this will be the parameter's name
(?:            # non-capturing group
  =?           #   an "=", optional
  (            #   group 2
    [^&#]*     #     any character except "&" or "#"; any number of times
  )            #   end group 2 - this will be the parameter's value
)              # end non-capturing group

The multi-part identifier could not be bound

SELECT DISTINCT
        phuongxa.maxa ,
        quanhuyen.mahuyen ,
        phuongxa.tenxa ,
        quanhuyen.tenhuyen ,
        ISNULL(dkcd.tong, 0) AS tongdkcd
FROM    phuongxa ,
        quanhuyen
        LEFT OUTER JOIN ( SELECT    khaosat.maxa ,
                                    COUNT(*) AS tong
                          FROM      khaosat
                          WHERE     CONVERT(DATETIME, ngaylap, 103) BETWEEN 'Sep 1 2011'
                                                              AND
                                                              'Sep 5 2011'
                          GROUP BY  khaosat.maxa
                        ) AS dkcd ON dkcd.maxa = maxa
WHERE   phuongxa.maxa <> '99'
        AND LEFT(phuongxa.maxa, 2) = quanhuyen.mahuyen
ORDER BY maxa;

BAT file to map to network drive without running as admin

I tried to create a mapped network driver via 'net use' with admin privilege but failed, it does not show. And if I add it through UI, it disappeared after reboot, now I made that through powershell. So, I think you can run powershell scripts from a .bat file, and the script is

New-PSDrive -Name "P" -PSProvider "FileSystem" -Root "\\Server01\Public"

add -persist at the end, you will create a persisted mapped network drive

New-PSDrive -Name "P" -PSProvider "FileSystem" -Root "\\Server01\Scripts" -Persist

for more details, refer New-PSDrive - Microsoft Docs

How to rename HTML "browse" button of an input type=file?

You can do it with a simple css/jq workaround: Create a fake button which triggers the browse button that is hidden.

HTML

<input type="file"/>
<button>Open</button>

CSS

input { display: none }

jQuery

$( 'button' ).click( function(e) {
    e.preventDefault(); // prevents submitting
    $( 'input' ).trigger( 'click' );
} );

demo

What is Shelving in TFS?

If you're using Gated builds, when a build is triggered, it creates a shelveset of your workspace that is submitted for build. If the build fails, the shelveset is rejected. If the build is successful, a changeset is created and committed to TFS. In either event, the person doing that check-in/build will have to reconcile the workspace, which is as simple as performing a Get Latest.

Measuring text height to be drawn on Canvas ( Android )

You must use Rect.width() and Rect.Height() which returned from getTextBounds() instead. That works for me.

How to change the port of Tomcat from 8080 to 80?

If someone is looking for, how to change the tomcat port number in Eclipse IDE user following are the steps.

1.In the Servers view, double click on the server name: enter image description here

2.That will open a configuration page for Tomcat as follows: enter image description here

3.Notice the port numbers are shown in the table on the right. Click to edit, for example: enter image description here

4.That will change port number for HTTP from 8080 to 80. Press Ctrl + S to save the change and restart the server. We can spot the change of port number in the Console view: enter image description here

This all content were taken from below link, please refer that link for further information thanks. http://www.codejava.net/servers/tomcat/how-to-change-port-numbers-for-tomcat-in-eclipse

Bootstrap 3.0 Popovers and tooltips

I use this on all my pages to enable tooltip

$(function () { $("[data-toggle='tooltip']").tooltip(); });

Flutter - The method was called on null

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

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

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

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

Facebook Access Token for Pages

  1. Go to the Graph API Explorer
  2. Choose your app from the dropdown menu
  3. Click "Get Access Token"
  4. Choose the manage_pages permission (you may need the user_events permission too, not sure)
  5. Now access the me/accounts connection and copy your page's access_token
  6. Click on your page's id
  7. Add the page's access_token to the GET fields
  8. Call the connection you want (e.g.: PAGE_ID/events)

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

mAddTaskButton is null because you never initialize it with:

mAddTaskButton = (Button) findViewById(R.id.addTaskButton);

before you call mAddTaskButton.setOnClickListener().

How npm start runs a server on port 8000

To change the port

npm start --port 8000

Check if user is using IE

i've used this

function notIE(){
    var ua = window.navigator.userAgent;
    if (ua.indexOf('Edge/') > 0 || 
        ua.indexOf('Trident/') > 0 || 
        ua.indexOf('MSIE ') > 0){
       return false;
    }else{
        return true;                
    }
}

Speed up rsync with Simultaneous/Concurrent File Transfers?

I've developed a python package called: parallel_sync

https://pythonhosted.org/parallel_sync/pages/examples.html

Here is a sample code how to use it:

from parallel_sync import rsync
creds = {'user': 'myusername', 'key':'~/.ssh/id_rsa', 'host':'192.168.16.31'}
rsync.upload('/tmp/local_dir', '/tmp/remote_dir', creds=creds)

parallelism by default is 10; you can increase it:

from parallel_sync import rsync
creds = {'user': 'myusername', 'key':'~/.ssh/id_rsa', 'host':'192.168.16.31'}
rsync.upload('/tmp/local_dir', '/tmp/remote_dir', creds=creds, parallelism=20)

however note that ssh typically has the MaxSessions by default set to 10 so to increase it beyond 10, you'll have to modify your ssh settings.

How to delete all files and folders in a folder by cmd call

One easy one-line option is to create an empty directory somewhere on your file system, and then use ROBOCOPY (http://technet.microsoft.com/en-us/library/cc733145.aspx) with the /MIR switch to remove all files and subfolders. By default, robocopy does not copy security, so the ACLs in your root folder should remain intact.

Also probably want to set a value for the retry switch, /r, because the default number of retries is 1 million.

robocopy "C:\DoNotDelete_UsedByScripts\EmptyFolder" "c:\temp\MyDirectoryToEmpty" /MIR /r:3

Format of the initialization string does not conform to specification starting at index 0

For the one other unfortunate soul that is managing a legacy webforms application that uses an inline sqldatasource, along with connection strings stored in web.config, then you may get this error if you access your connection string like <%APSDataConnectionString%> instead of <%$ ConnectionStrings:MyConnectionString %>. This happened to us when upgrading .NET from 3.5 to 4.x.

<asp:DropDownList ID="ddl" runat="server" DataSourceID="SqlDataSource1"
  DataTextField="value" DataValueField="id"></asp:DropDownList>                
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
  ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
  SelectCommand="select id, value from a_table">
</asp:SqlDataSource>

Jackson overcoming underscores in favor of camel-case

There are few answers here indicating both strategies for 2 different versions of Jackson library below:

For Jackson 2.6.*

ObjectMapper objMapper = new ObjectMapper(new JsonFactory()); // or YAMLFactory()
objMapper.setNamingStrategy(
     PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);

For Jackson 2.7.*

ObjectMapper objMapper = new ObjectMapper(new JsonFactory()); // or YAMLFactory()
objMapper.setNamingStrategy(
     PropertyNamingStrategy.SNAKE_CASE);

Get Insert Statement for existing row in MySQL

You can create a SP with the code below - it supports NULLS as well.

select 'my_table_name' into @tableName;

/*find column names*/
select GROUP_CONCAT(column_name SEPARATOR ', ') from information_schema.COLUMNS
where table_schema =DATABASE()
and table_name = @tableName
group by table_name
into @columns
;

/*wrap with IFNULL*/
select replace(@columns,',',',IFNULL(') into @selectColumns;
select replace(@selectColumns,',IFNULL(',',\'~NULL~\'),IFNULL(') into @selectColumns;

select concat('IFNULL(',@selectColumns,',\'~NULL~\')') into @selectColumns;

/*RETRIEVE COLUMN DATA FIELDS BY PK*/
SELECT
  CONCAT(
    'SELECT CONCAT_WS(','''\'\',\'\''',' ,
    @selectColumns,
    ') AS all_columns FROM ',@tableName, ' where id = 5 into @values;'
    )
INTO @sql;

PREPARE stmt FROM @sql;
EXECUTE stmt;

/*Create Insert Statement*/
select CONCAT('insert into ',@tableName,' (' , @columns ,') values (\'',@values,'\')') into @prepared;

/*UNWRAP NULLS*/
select replace(@prepared,'\'~NULL~\'','NULL') as statement;

printf \t option

A tab is a tab. How many spaces it consumes is a display issue, and depends on the settings of your shell.

If you want to control the width of your data, then you could use the width sub-specifiers in the printf format string. Eg. :

printf("%5d", 2);

It's not a complete solution (if the value is longer than 5 characters, it will not be truncated), but might be ok for your needs.

If you want complete control, you'll probably have to implement it yourself.

How to flip background image using CSS?

You can flip both vertical and horizontal at the same time

    -moz-transform: scaleX(-1) scaleY(-1);
    -o-transform: scaleX(-1) scaleY(-1);
    -webkit-transform: scaleX(-1) scaleY(-1);
    transform: scaleX(-1) scaleY(-1);

And with the transition property you can get a cool flip

    -webkit-transition: transform .4s ease-out 0ms;
    -moz-transition: transform .4s ease-out 0ms;
    -o-transition: transform .4s ease-out 0ms;
    transition: transform .4s ease-out 0ms;
    transition-property: transform;
    transition-duration: .4s;
    transition-timing-function: ease-out;
    transition-delay: 0ms;

Actually it flips the whole element, not just the background-image

SNIPPET

_x000D_
_x000D_
function flip(){_x000D_
 var myDiv = document.getElementById('myDiv');_x000D_
 if (myDiv.className == 'myFlipedDiv'){_x000D_
  myDiv.className = '';_x000D_
 }else{_x000D_
  myDiv.className = 'myFlipedDiv';_x000D_
 }_x000D_
}
_x000D_
#myDiv{_x000D_
  display:inline-block;_x000D_
  width:200px;_x000D_
  height:20px;_x000D_
  padding:90px;_x000D_
  background-color:red;_x000D_
  text-align:center;_x000D_
  -webkit-transition:transform .4s ease-out 0ms;_x000D_
  -moz-transition:transform .4s ease-out 0ms;_x000D_
  -o-transition:transform .4s ease-out 0ms;_x000D_
  transition:transform .4s ease-out 0ms;_x000D_
  transition-property:transform;_x000D_
  transition-duration:.4s;_x000D_
  transition-timing-function:ease-out;_x000D_
  transition-delay:0ms;_x000D_
}_x000D_
.myFlipedDiv{_x000D_
  -moz-transform:scaleX(-1) scaleY(-1);_x000D_
  -o-transform:scaleX(-1) scaleY(-1);_x000D_
  -webkit-transform:scaleX(-1) scaleY(-1);_x000D_
  transform:scaleX(-1) scaleY(-1);_x000D_
}
_x000D_
<div id="myDiv">Some content here</div>_x000D_
_x000D_
<button onclick="flip()">Click to flip</button>
_x000D_
_x000D_
_x000D_

MySql Error: 1364 Field 'display_name' doesn't have default value

Also, I had this issue using Laravel, but fixed by changing my database schema to allow "null" inputs on a table where I plan to collect the information from separate forms:

public function up()
{

    Schema::create('trip_table', function (Blueprint $table) {
        $table->increments('trip_id')->unsigned();
        $table->time('est_start');
        $table->time('est_end');
        $table->time('act_start')->nullable();
        $table->time('act_end')->nullable();
        $table->date('Trip_Date');
        $table->integer('Starting_Miles')->nullable();
        $table->integer('Ending_Miles')->nullable();
        $table->string('Bus_id')->nullable();
        $table->string('Event');
        $table->string('Desc')->nullable();
        $table->string('Destination');
        $table->string('Departure_location');
        $table->text('Drivers_Comment')->nullable();
        $table->string('Requester')->nullable();
        $table->integer('driver_id')->nullable();
        $table->timestamps();
    });

}

The ->nullable(); Added to the end. This is using Laravel. Hope this helps someone, thanks!

How to get PID of process by specifying process name and store it in a variable to use further?

Another possibility would be to use pidof it usually comes with most distributions. It will return you the PID of a given process by using it's name.

pidof process_name

This way you could store that information in a variable and execute kill -9 on it.

#!/bin/bash
pid=`pidof process_name`
kill -9 $pid

C# how to change data in DataTable?

You should probably set the property dt.Columns["columnName"].ReadOnly = false; before.

How to know if two arrays have the same values

Array.prototype.compare = function(testArr) {
    if (this.length != testArr.length) return false;
    for (var i = 0; i < testArr.length; i++) {
        if (this[i].compare) { //To test values in nested arrays
            if (!this[i].compare(testArr[i])) return false;
        }
        else if (this[i] !== testArr[i]) return false;
    }
    return true;
}

var array1 = [2, 4];
var array2 = [4, 2];
if(array1.sort().compare(array2.sort())) {
    doSomething();
} else {
    doAnotherThing();
}

Maybe?

"continue" in cursor.forEach()

In my opinion the best approach to achieve this by using the filter method as it's meaningless to return in a forEach block; for an example on your snippet:

// Fetch all objects in SomeElements collection
var elementsCollection = SomeElements.find();
elementsCollection
.filter(function(element) {
  return element.shouldBeProcessed;
})
.forEach(function(element){
  doSomeLengthyOperation();
});

This will narrow down your elementsCollection and just keep the filtred elements that should be processed.

Downloading a picture via urllib and python

import urllib
f = open('00000001.jpg','wb')
f.write(urllib.urlopen('http://www.gunnerkrigg.com//comics/00000001.jpg').read())
f.close()

Can I do a max(count(*)) in SQL?

     select top 1 yr,count(*)  from movie
join casting on casting.movieid=movie.id
join actor on casting.actorid = actor.id
where actor.name = 'John Travolta'
group by yr order by 2 desc

Run git pull over all subdirectories

Run the following from the parent directory, plugins in this case:

find . -type d -depth 1 -exec git --git-dir={}/.git --work-tree=$PWD/{} pull origin master \;

To clarify:

  • find . searches the current directory
  • -type d to find directories, not files
  • -depth 1 for a maximum depth of one sub-directory
  • -exec {} \; runs a custom command for every find
  • git --git-dir={}/.git --work-tree=$PWD/{} pull git pulls the individual directories

To play around with find, I recommend using echo after -exec to preview, e.g.:

find . -type d -depth 1 -exec echo git --git-dir={}/.git --work-tree=$PWD/{} status \;

Note: if the -depth 1 option is not available, try -mindepth 1 -maxdepth 1.

Execute jQuery function after another function completes

You could also use custom events:

function Typer() {
    // Some stuff

    $(anyDomElement).trigger("myCustomEvent");
}


$(anyDomElement).on("myCustomEvent", function() {
    // Some other stuff
});

Error: fix the version conflict (google-services plugin)

For fire base to install properly all the versions of the fire base compiles must be in same version so

compile 'com.google.firebase:firebase-messaging:11.0.4' 
compile 'com.google.android.gms:play-services-maps:11.0.4' 
compile 'com.google.android.gms:play-services-location:11.0.4'

this is the correct way to do it.

How to run docker-compose up -d at system start up?

You should be able to add:

restart: always 

to every service you want to restart in the docker-compose.yml file.

See: https://github.com/compose-spec/compose-spec/blob/master/spec.md#restart

What is the difference between Html.Hidden and Html.HiddenFor

Html.Hidden and Html.HiddenFor used to generate name-value pairs which waited by action method in controller. Sample Usage(*):

@using (Html.BeginForm("RemoveFromCart", "Cart")) {
                    @Html.Hidden("ProductId", line.Product.ProductID)
                    @Html.HiddenFor(x => x.ReturnUrl)
                    <input class="btn btn-sm btn-warning"
                           type="submit" value="Remove" />
                }

If your action method wait for "ProductId" you have to generate this name in form via using (Html.Hidden or Html.HiddenFor) For the case it is not possible to generate this name with strongly typed model you simple write this name with a string thats "ProductId".

public ViewResult RemoveFromCart(int productId, string returnUrl){...}

If I had written Html.HiddenFor(x => line.Product.ProductID), the helper would render a hidden field with the name "line.Product.ProductID". The name of the field would not match the names of the parameters for the "RemoveFromCart" action method which waiting the name of "ProductId". This would prevent the default model binders from working, so the MVC Framework would not be able to call the method.

*Adam Freeman (Apress - Pro ASP.Net MVC 5)

Android: Vertical alignment for multi line EditText (Text area)

I think you can use layout:weight = 5 instead android:lines = 5 because when you port your app to smaller device - it does it nicely.. well, both attributes will accomplish your job..

How to update ruby on linux (ubuntu)?

On Ubuntu 12.04 (Precise Pangolin), I got this working with the following command:

sudo apt-get install ruby1.9.1
sudo apt-get install ruby1.9.3

How to get a resource id with a known resource name?

It will be something like:

R.drawable.resourcename

Make sure you don't have the Android.R namespace imported as it can confuse Eclipse (if that's what you're using).

If that doesn't work, you can always use a context's getResources method ...

Drawable resImg = this.context.getResources().getDrawable(R.drawable.resource);

Where this.context is intialised as an Activity, Service or any other Context subclass.

Update:

If it's the name you want, the Resources class (returned by getResources()) has a getResourceName(int) method, and a getResourceTypeName(int)?

Update 2:

The Resources class has this method:

public int getIdentifier (String name, String defType, String defPackage) 

Which returns the integer of the specified resource name, type & package.

scale Image in an UIButton to AspectFit?

I have a method that does it for me. The method takes UIButton and makes the image aspect fit.

-(void)makeImageAspectFitForButton:(UIButton*)button{
    button.imageView.contentMode=UIViewContentModeScaleAspectFit;
    button.contentHorizontalAlignment=UIControlContentHorizontalAlignmentFill;
    button.contentVerticalAlignment=UIControlContentVerticalAlignmentFill;
}

UL or DIV vertical scrollbar

You need to set a height on the DIV. Otherwise it will keep expanding indefinitely.

Convert Array to Object

A quick and dirty one:

var obj = {},
  arr = ['a','b','c'],
  l = arr.length; 

while( l && (obj[--l] = arr.pop() ) ){};

Best way to track onchange as-you-type in input type="text"?

To track each try this example and before that completely reduce cursor blink rate to zero.

_x000D_
_x000D_
<body>_x000D_
//try onkeydown,onkeyup,onkeypress_x000D_
<input type="text" onkeypress="myFunction(this.value)">_x000D_
<span> </span>_x000D_
<script>_x000D_
function myFunction(val) {_x000D_
//alert(val);_x000D_
var mySpan = document.getElementsByTagName("span")[0].innerHTML;_x000D_
mySpan += val+"<br>";_x000D_
document.getElementsByTagName("span")[0].innerHTML = mySpan;_x000D_
}_x000D_
</script>_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

onblur : event generates on exit

onchange : event generates on exit if any changes made in inputtext

onkeydown: event generates on any key press (for key holding long times also)

onkeyup : event generates on any key release

onkeypress: same as onkeydown (or onkeyup) but won't react for ctrl,backsace,alt other

Enter key press behaves like a Tab in Javascript

Easiest way to solve this problem with the focus function of JavaScript as follows:

You can copy and try it @ home!

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>

    <input id="input1" type="text" onkeypress="pressEnter()" />
    <input id="input2" type="text" onkeypress="pressEnter2()" />
    <input id="input3" type="text"/>

    <script type="text/javascript">
    function pressEnter() {
      // Key Code for ENTER = 13
      if ((event.keyCode == 13)) {
        document.getElementById("input2").focus({preventScroll:false});
      }
    }
    function pressEnter2() {
      if ((event.keyCode == 13)) {
        document.getElementById("input3").focus({preventScroll:false});
      }
    }
    </script>

  </body>
</html>

rails + MySQL on OSX: Library not loaded: libmysqlclient.18.dylib

Thanks. A Homebrew upgrade made my Rails apps have issues on my Mac. I reinstalled MySQL (5.7) from source, then I had to do this

sudo ln -s /usr/local/mysql-5.7.28-macos10.14-x86_64/lib/libmysqlclient.20.dylib /usr/lib/libmysqlclient.20bdylib

based on what I read above, and in my Gemfile

gem 'mysql2', '0.5.3'

and in database.yml

adapter: mysql2

Find files with size in Unix

Assuming you have GNU find:

find . -size +10000k -printf '%s %f\n'

If you want a constant width for the size field, you can do something like:

find . -size +10000k -printf '%10s %f\n'

Note that -size +1000k selects files of at least 10,240,000 bytes (k is 1024, not 1000). You said in a comment that you want files bigger than 1M; if that's 1024*1024 bytes, then this:

find . -size +1M ...

will do the trick -- except that it will also print the size and name of files that are exactly 1024*1024 bytes. If that matters, you could use:

find . -size +1048575c ...

You need to decide just what criterion you want.

Get the short Git version hash

A really simple way is to:

git describe --always

adding line break

string[] abcd = obj.show(); 

Response.Write(string.join("</br>", abcd));

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

Compiling an application for use in highly radioactive environments

This is an extremely broad subject. Basically, you can't really recover from memory corruption, but you can at least try to fail promptly. Here are a few techniques you could use:

  • checksum constant data. If you have any configuration data which stays constant for a long time (including hardware registers you have configured), compute its checksum on initialization and verify it periodically. When you see a mismatch, it's time to re-initialize or reset.

  • store variables with redundancy. If you have an important variable x, write its value in x1, x2 and x3 and read it as (x1 == x2) ? x2 : x3.

  • implement program flow monitoring. XOR a global flag with a unique value in important functions/branches called from the main loop. Running the program in a radiation-free environment with near-100% test coverage should give you the list of acceptable values of the flag at the end of the cycle. Reset if you see deviations.

  • monitor the stack pointer. In the beginning of the main loop, compare the stack pointer with its expected value. Reset on deviation.

Angular ReactiveForms: Producing an array of checkbox values?

My solution - solved it for Angular 5 with Material View
The connection is through the

formArrayName="notification"

(change)="updateChkbxArray(n.id, $event.checked, 'notification')"

This way it can work for multiple checkboxes arrays in one form. Just set the name of the controls array to connect each time.

_x000D_
_x000D_
constructor(_x000D_
  private fb: FormBuilder,_x000D_
  private http: Http,_x000D_
  private codeTableService: CodeTablesService) {_x000D_
_x000D_
  this.codeTableService.getnotifications().subscribe(response => {_x000D_
      this.notifications = response;_x000D_
    })_x000D_
    ..._x000D_
}_x000D_
_x000D_
_x000D_
createForm() {_x000D_
  this.form = this.fb.group({_x000D_
    notification: this.fb.array([])..._x000D_
  });_x000D_
}_x000D_
_x000D_
ngOnInit() {_x000D_
  this.createForm();_x000D_
}_x000D_
_x000D_
updateChkbxArray(id, isChecked, key) {_x000D_
  const chkArray = < FormArray > this.form.get(key);_x000D_
  if (isChecked) {_x000D_
    chkArray.push(new FormControl(id));_x000D_
  } else {_x000D_
    let idx = chkArray.controls.findIndex(x => x.value == id);_x000D_
    chkArray.removeAt(idx);_x000D_
  }_x000D_
}
_x000D_
<div class="col-md-12">_x000D_
  <section class="checkbox-section text-center" *ngIf="notifications  && notifications.length > 0">_x000D_
    <label class="example-margin">Notifications to send:</label>_x000D_
    <p *ngFor="let n of notifications; let i = index" formArrayName="notification">_x000D_
      <mat-checkbox class="checkbox-margin" (change)="updateChkbxArray(n.id, $event.checked, 'notification')" value="n.id">{{n.description}}</mat-checkbox>_x000D_
    </p>_x000D_
  </section>_x000D_
</div>
_x000D_
_x000D_
_x000D_

At the end you are getting to save the form with array of original records id's to save/update. The UI View

The relevat part of the json of the form

Will be happy to have any remarks for improvement.

Today`s date in an excel macro

Here's an example that puts the Now() value in column A.

Sub move()
    Dim i As Integer
    Dim sh1 As Worksheet
    Dim sh2 As Worksheet
    Dim nextRow As Long
    Dim copyRange As Range
    Dim destRange As Range

    Application.ScreenUpdating = False

        Set sh1 = ActiveWorkbook.Worksheets("Sheet1")
        Set sh2 = ActiveWorkbook.Worksheets("Sheet2")
        Set copyRange = sh1.Range("A1:A5")

        i = Application.WorksheetFunction.CountA(sh2.Range("B:B")) + 4

        Set destRange = sh2.Range("B" & i)

        destRange.Resize(1, copyRange.Rows.Count).Value = Application.Transpose(copyRange.Value)
        destRange.Offset(0, -1).Value = Format(Now(), "MMM-DD-YYYY")

        copyRange.Clear

    Application.ScreenUpdating = True

End Sub

There are better ways of getting the last row in column B than using a While loop, plenty of examples around here. Some are better than others but depend on what you're doing and what your worksheet structure looks like. I used one here which assumes that column B is ALL empty except the rows/records you're moving. If that's not the case, or if B1:B3 have some values in them, you'd need to modify or use another method. Or you could just use your loop, but I'd search for alternatives :)

ICommand MVVM implementation

I have written this article about the ICommand interface.

The idea - creating a universal command that takes two delegates: one is called when ICommand.Execute (object param) is invoked, the second checks the status of whether you can execute the command (ICommand.CanExecute (object param)).

Requires the method to switching event CanExecuteChanged. It is called from the user interface elements for switching the state CanExecute() command.

public class ModelCommand : ICommand
{
    #region Constructors

    public ModelCommand(Action<object> execute)
        : this(execute, null) { }

    public ModelCommand(Action<object> execute, Predicate<object> canExecute)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

    #endregion

    #region ICommand Members

    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        return _canExecute != null ? _canExecute(parameter) : true;
    }

    public void Execute(object parameter)
    {
        if (_execute != null)
            _execute(parameter);
    }

    public void OnCanExecuteChanged()
    {
        CanExecuteChanged(this, EventArgs.Empty);
    }

    #endregion

    private readonly Action<object> _execute = null;
    private readonly Predicate<object> _canExecute = null;
}

How to highlight text using javascript

Using the surroundContents() method on the Range type. Its only argument is an element which will wrap that Range.

function styleSelected() {
  bg = document.createElement("span");
  bg.style.backgroundColor = "yellow";
  window.getSelection().getRangeAt(0).surroundContents(bg);
}

react-native: command not found

In case anyone has this problem, I had a similar problem to qix, but more nuanced.

New shell terminals would default to a different version of node. I would change my terminal to the node I wanted, but when the bundle script run, it ran in a new shell, and it got the default version which did not have react-native installed.

I used nvm alias default x.x.x so that new shells would inherit the default version I wanted.

Concatenation of strings in Lua

Strings can be joined together using the concatenation operator ".."

this is the same for variables I think

Append lines to a file using a StreamWriter

Try this:

StreamWriter file2 = new StreamWriter(@"c:\file.txt", true);
file2.WriteLine(someString);
file2.Close();

Adding Git-Bash to the new Windows Terminal

This is the complete answer (GitBash + color scheme + icon + context menu)

1) Set default profile:

"globals" : 
{
    "defaultProfile" : "{00000000-0000-0000-0000-000000000001}",
    ...

2) Add GitBash profile

"profiles" : 
[
    {
        "guid": "{00000000-0000-0000-0000-000000000001}",
        "acrylicOpacity" : 0.75,
        "closeOnExit" : true,
        "colorScheme" : "GitBash",
        "commandline" : "\"%PROGRAMFILES%\\Git\\usr\\bin\\bash.exe\" --login -i -l",
        "cursorColor" : "#FFFFFF",
        "cursorShape" : "bar",
        "fontFace" : "Consolas",
        "fontSize" : 10,
        "historySize" : 9001,
        "icon" : "%PROGRAMFILES%\\Git\\mingw64\\share\\git\\git-for-windows.ico", 
        "name" : "GitBash",
        "padding" : "0, 0, 0, 0",
        "snapOnInput" : true,
        "startingDirectory" : "%USERPROFILE%",
        "useAcrylic" : false        
    },

3) Add GitBash color scheme

"schemes" : 
[
    {
        "background" : "#000000",
        "black" : "#0C0C0C",
        "blue" : "#6060ff",
        "brightBlack" : "#767676",
        "brightBlue" : "#3B78FF",
        "brightCyan" : "#61D6D6",
        "brightGreen" : "#16C60C",
        "brightPurple" : "#B4009E",
        "brightRed" : "#E74856",
        "brightWhite" : "#F2F2F2",
        "brightYellow" : "#F9F1A5",
        "cyan" : "#3A96DD",
        "foreground" : "#bfbfbf",
        "green" : "#00a400",
        "name" : "GitBash",
        "purple" : "#bf00bf",
        "red" : "#bf0000",
        "white" : "#ffffff",
        "yellow" : "#bfbf00",
        "grey" : "#bfbfbf"
    },  

4) To add a right-click context menu "Windows Terminal Here"

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\Background\shell\wt]
@="Windows terminal here"
"Icon"="C:\\Users\\{YOUR_WINDOWS_USERNAME}\\AppData\\Local\\Microsoft\\WindowsApps\\{YOUR_ICONS_FOLDER}\\icon.ico"

[HKEY_CLASSES_ROOT\Directory\Background\shell\wt\command]
@="\"C:\\Users\\{YOUR_WINDOWS_USERNAME}\\AppData\\Local\\Microsoft\\WindowsApps\\wt.exe\""
  • replace {YOUR_WINDOWS_USERNAME}
  • create icon folder, put the icon there and replace {YOUR_ICONS_FOLDER}
  • save this in a whatever_filename.reg file and run it.

Plotting using a CSV file

You can also plot to a png file using gnuplot (which is free):

terminal commands

gnuplot> set title '<title>'
gnuplot> set ylabel '<yLabel>'
gnuplot> set xlabel '<xLabel>'
gnuplot> set grid
gnuplot> set term png
gnuplot> set output '<Output file name>.png'
gnuplot> plot '<fromfile.csv>'

note: you always need to give the right extension (.png here) at set output

Then it is also possible that the ouput is not lines, because your data is not continues. To fix this simply change the 'plot' line to:

plot '<Fromfile.csv>' with line lt -1 lw 2

More line editing options (dashes and line color ect.) at: http://gnuplot.sourceforge.net/demo_canvas/dashcolor.html

  • gnuplot is available in most linux distros via the package manager (e.g. on an apt based distro, run apt-get install gnuplot)
  • gnuplot is available in windows via Cygwin
  • gnuplot is available on macOS via homebrew (run brew install gnuplot)

How to hide console window in python?

This will hide your console. Implement these lines in your code first to start hiding your console at first.

import win32gui, win32con

the_program_to_hide = win32gui.GetForegroundWindow()
win32gui.ShowWindow(the_program_to_hide , win32con.SW_HIDE)

Update May 2020 :

If you've got trouble on pip install win32con on Command Prompt, you can simply pip install pywin32.Then on your python script, execute import win32.lib.win32con as win32con instead of import win32con.

To show back your program again win32con.SW_SHOW works fine:

win32gui.ShowWindow(the_program_to_hide , win32con.SW_SHOW)

Text file in VBA: Open/Find Replace/SaveAs/Close File

I have had the same problem and came acrosse this site.

the solution to just set another "filename" in the

... for output as ... command was very simple and useful.

in addition (beyond the Application.GetSaveAsFilename() Dialog)

it is very simple to set a** new filename** just using

the replace command, so you may change the filename/extension

eg. (as from the first post)

sFileName = "C:\filelocation"
iFileNum = FreeFile

Open sFileName For Input As iFileNum
content = (...edit the content) 

Close iFileNum

now just set:

newFilename = replace(sFilename, ".txt", ".csv") to change the extension

or

newFilename = replace(sFilename, ".", "_edit.") for a differrent filename

and then just as before

iFileNum = FreeFile
Open newFileName For Output As iFileNum

Print #iFileNum, content
Close iFileNum 

I surfed over an hour to find out how to rename a txt-file,

with many different solutions, but it could be sooo easy :)

Can I draw rectangle in XML?

create resource file in drawable

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#3b5998" />
<cornersandroid:radius="15dp"/>

Output single character in C

Be careful of difference between 'c' and "c"

'c' is a char suitable for formatting with %c

"c" is a char* pointing to a memory block with a length of 2 (with the null terminator).

Find current directory and file's directory

Pathlib can be used this way to get the directory containing current script :

import pathlib
filepath = pathlib.Path(__file__).resolve().parent

Check if table exists in SQL Server

Please see the below approaches,

Approach 1: Using INFORMATION_SCHEMA.TABLES view

We can write a query like below to check if a Customers Table exists in the current database.

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'Customers')
BEGIN
    PRINT 'Table Exists'
END

Approach 2: Using OBJECT_ID() function

We can use OBJECT_ID() function like below to check if a Customers Table exists in the current database.

IF OBJECT_ID(N'dbo.Customers', N'U') IS NOT NULL
BEGIN
    PRINT 'Table Exists'
END

Approach 3: Using sys.Objects Catalog View

We can use the Sys.Objects catalog view to check the existence of the Table as shown below:

IF EXISTS(SELECT 1 FROM sys.Objects WHERE  Object_id = OBJECT_ID(N'dbo.Customers') AND Type = N'U')
BEGIN
   PRINT 'Table Exists'
END

Approach 4: Using sys.Tables Catalog View

We can use the Sys.Tables catalog view to check the existence of the Table as shown below:

 IF EXISTS(SELECT 1 FROM sys.Tables WHERE  Name = N'Customers' AND Type = N'U')
 BEGIN
      PRINT 'Table Exists'
 END

Approach 5: Avoid Using sys.sysobjects System table

We should avoid using sys.sysobjects System Table directly, direct access to it will be deprecated in some future versions of the Sql Server. As per Microsoft BOL link, Microsoft is suggesting to use the catalog views sys.objects/sys.tables instead of sys.sysobjects system table directly.

  IF EXISTS(SELECT name FROM sys.sysobjects WHERE Name = N'Customers' AND xtype = N'U')
  BEGIN
     PRINT 'Table Exists'
  END

referred from: http://sqlhints.com/2014/04/13/how-to-check-if-a-table-exists-in-sql-server/

Bold & Non-Bold Text In A Single UILabel?

I've adopted Crazy Yoghurt's answer to swift's extensions.

extension UILabel {

    func boldRange(_ range: Range<String.Index>) {
        if let text = self.attributedText {
            let attr = NSMutableAttributedString(attributedString: text)
            let start = text.string.characters.distance(from: text.string.startIndex, to: range.lowerBound)
            let length = text.string.characters.distance(from: range.lowerBound, to: range.upperBound)
            attr.addAttributes([NSFontAttributeName: UIFont.boldSystemFont(ofSize: self.font.pointSize)], range: NSMakeRange(start, length))
            self.attributedText = attr
        }
    }

    func boldSubstring(_ substr: String) {
        if let text = self.attributedText {
            var range = text.string.range(of: substr)
            let attr = NSMutableAttributedString(attributedString: text)
            while range != nil {
                let start = text.string.characters.distance(from: text.string.startIndex, to: range!.lowerBound)
                let length = text.string.characters.distance(from: range!.lowerBound, to: range!.upperBound)
                var nsRange = NSMakeRange(start, length)
                let font = attr.attribute(NSFontAttributeName, at: start, effectiveRange: &nsRange) as! UIFont
                if !font.fontDescriptor.symbolicTraits.contains(.traitBold) {
                    break
                }
                range = text.string.range(of: substr, options: NSString.CompareOptions.literal, range: range!.upperBound..<text.string.endIndex, locale: nil)
            }
            if let r = range {
                boldRange(r)
            }
        }
    }
}

May be there is not good conversion between Range and NSRange, but I didn't found something better.

C++ create string of text and variables

Have you considered using stringstreams?

#include <string>
#include <sstream>

std::ostringstream oss;
oss << "sometext" << somevar << "sometext" << somevar;
std::string var = oss.str();

specifying goal in pom.xml

The error message which you specified is nothing but you are not specifying goal for maven build.

you can specify any goal in your run configuration for maven build like clear, compile, install, package.

please following below step to resolve it.

  1. right click on your project.
  2. click 'Run as' and select 'Maven Build'
  3. edit Configuration window will open. write any goal but your problem specific write 'package' in Goal text box.
  4. click on 'Run'

How do I calculate someone's age based on a DateTime type birthday?

TimeSpan diff = DateTime.Now - birthdayDateTime;
string age = String.Format("{0:%y} years, {0:%M} months, {0:%d}, days old", diff);

I'm not sure how exactly you'd like it returned to you, so I just made a readable string.

Removing ul indentation with CSS

Remove this from #info:

    margin-left:auto;

Add this for your header:

#info p {
    text-align: center;
}

Do you need the fixed width etc.? I removed the in my opinion not necessary stuff and centered the header with text-align.

Sample
http://jsfiddle.net/Vc8CB/

Fatal error: Call to undefined function imap_open() in PHP

If your local installation is running XAMPP on Windows , That's enough : you can open the file "\xampp\php\php.ini" to activate the php exstension by removing the beginning semicolon at the line ";extension=php_imap.dll". It should be:

;extension=php_imap.dll

to

extension=php_imap.dll

"The given path's format is not supported."

Rather than using str_uploadpath + fileName, try using System.IO.Path.Combine instead:

Path.Combine(str_uploadpath, fileName);

which returns a string.

How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?

I have added below code to terminate tasks you can use it. You may change the retry numbers.

package com.xxx.test.schedulers;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import com.xxx.core.XProvLogger;

@Component
class ContextClosedHandler implements ApplicationListener<ContextClosedEvent> , ApplicationContextAware,BeanPostProcessor{


private ApplicationContext context;

public Logger logger = XProvLogger.getInstance().x;

public void onApplicationEvent(ContextClosedEvent event) {


    Map<String, ThreadPoolTaskScheduler> schedulers = context.getBeansOfType(ThreadPoolTaskScheduler.class);

    for (ThreadPoolTaskScheduler scheduler : schedulers.values()) {         
        scheduler.getScheduledExecutor().shutdown();
        try {
            scheduler.getScheduledExecutor().awaitTermination(20000, TimeUnit.MILLISECONDS);
            if(scheduler.getScheduledExecutor().isTerminated() || scheduler.getScheduledExecutor().isShutdown())
                logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has stoped");
            else{
                logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has not stoped normally and will be shut down immediately");
                scheduler.getScheduledExecutor().shutdownNow();
                logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has shut down immediately");
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    Map<String, ThreadPoolTaskExecutor> executers = context.getBeansOfType(ThreadPoolTaskExecutor.class);

    for (ThreadPoolTaskExecutor executor: executers.values()) {
        int retryCount = 0;
        while(executor.getActiveCount()>0 && ++retryCount<51){
            try {
                logger.info("Executer "+executor.getThreadNamePrefix()+" is still working with active " + executor.getActiveCount()+" work. Retry count is "+retryCount);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if(!(retryCount<51))
            logger.info("Executer "+executor.getThreadNamePrefix()+" is still working.Since Retry count exceeded max value "+retryCount+", will be killed immediately");
        executor.shutdown();
        logger.info("Executer "+executor.getThreadNamePrefix()+" with active " + executor.getActiveCount()+" work has killed");
    }
}


@Override
public void setApplicationContext(ApplicationContext context)
        throws BeansException {
    this.context = context;

}


@Override
public Object postProcessAfterInitialization(Object object, String arg1)
        throws BeansException {
    return object;
}


@Override
public Object postProcessBeforeInitialization(Object object, String arg1)
        throws BeansException {
    if(object instanceof ThreadPoolTaskScheduler)
        ((ThreadPoolTaskScheduler)object).setWaitForTasksToCompleteOnShutdown(true);
    if(object instanceof ThreadPoolTaskExecutor)
        ((ThreadPoolTaskExecutor)object).setWaitForTasksToCompleteOnShutdown(true);
    return object;
}

}

How to upload files on server folder using jsp

You can only use absolute path http://grand-shopping.com/<"some folder"> is not an absolute path.

Either you can use a path inside the application which is vurneable or you can use server specific path like in

windows -> C:/Users/puneet verma/Downloads/
linux -> /opt/Downloads/

UnmodifiableMap (Java Collections) vs ImmutableMap (Google)

Have a look at ImmutableMap JavaDoc: doc

There is information about that there:

Unlike Collections.unmodifiableMap(java.util.Map), which is a view of a separate map which can still change, an instance of ImmutableMap contains its own data and will never change. ImmutableMap is convenient for public static final maps ("constant maps") and also lets you easily make a "defensive copy" of a map provided to your class by a caller.

Get value of c# dynamic property via string

Dynamitey is an open source .net std library, that let's you call it like the dynamic keyword, but using the a string for the property name rather than the compiler doing it for you, and it ends up being equal to reflection speedwise (which is not nearly as fast as using the dynamic keyword, but this is due to the extra overhead of caching dynamically, where the compiler caches statically).

Dynamic.InvokeGet(d,"value2");

Cannot read property 'getContext' of null, using canvas

You just need to put<script src='./javascript/game.js'></script> after your <canvas>. Because the browser don't find your javascript file before the canvas

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

Xcode 10.1 Swift 4

This worked for me:

let task: URLSessionDataTask = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
...

The key was adding in the URLSessionDataTask type declaration.

React-Redux: Actions must be plain objects. Use custom middleware for async actions

The error is simply asking you to insert a Middleware in between which would help to handle async operations.

You could do that by :

npm i redux-thunk

        Inside index.js

import thunk from "redux-thunk" 
        
...createStore(rootReducers, applyMiddleware(thunk));

Now, async operations will work inside your functions.

Parse json string to find and element (key / value)

You want to convert it to an object first and then access normally making sure to cast it.

JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];

Android: how to parse URL String with spaces to URI object?

URL url = Test.class.getResource(args[0]);  // reading demo file path from                                                   
                                            // same location where class                                    
File input=null;
try {
    input = new File(url.toURI());
} catch (URISyntaxException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

Reloading module giving NameError: name 'reload' is not defined

If you don't want to use external libs, then one solution is to recreate the reload method from python 2 for python 3 as below. Use this in the top of the module (assumes python 3.4+).

import sys
if(sys.version_info.major>=3):
    def reload(MODULE):        
        import importlib
        importlib.reload(MODULE)

BTW reload is very much required if you use python files as config files and want to avoid restarts of the application.....

Make UINavigationBar transparent

If you build with the lastest beta iOS 13.4 and XCode 11.4, the accepted answer won't work anymore. I've found another way, maybe it's just a bug in the beta software, but I'm writing it down there, just in case

(swift 5)

import UIKit

class TransparentNavBar :UINavigationBar {
    override func awakeFromNib() {
        super.awakeFromNib()
        self.setBackgroundImage(UIImage(), for: .default)
        self.shadowImage = UIImage()
        self.isTranslucent = true
        self.backgroundColor = .clear
        if #available(iOS 13.0, *) {
            self.standardAppearance.backgroundColor = .clear
            self.standardAppearance.backgroundEffect = .none
            self.standardAppearance.shadowColor = .clear
        }
    }
}

How to get to Model or Viewbag Variables in a Script Tag

Use single quotation marks ('):

var val = '@ViewBag.ForSection';
alert(val);

Change priorityQueue to max priorityqueue

How about like this:

PriorityQueue<Integer> queue = new PriorityQueue<>(10, Collections.reverseOrder());
queue.offer(1);
queue.offer(2);
queue.offer(3);
//...

Integer val = null;
while( (val = queue.poll()) != null) {
    System.out.println(val);
}

The Collections.reverseOrder() provides a Comparator that would sort the elements in the PriorityQueue in a the oposite order to their natural order in this case.

How to create a GUID in Excel?

Italian version:

=CONCATENA(
    DECIMALE.HEX(CASUALE.TRA(0;4294967295);8);"-";
    DECIMALE.HEX(CASUALE.TRA(0;42949);4);"-";
    DECIMALE.HEX(CASUALE.TRA(0;42949);4);"-";
    DECIMALE.HEX(CASUALE.TRA(0;42949);4);"-";
    DECIMALE.HEX(CASUALE.TRA(0;4294967295);8);
    DECIMALE.HEX(CASUALE.TRA(0;42949);4))

Does Java have a path joining method?

One way is to get system properties that give you the path separator for the operating system, this tutorial explains how. You can then use a standard string join using the file.separator.

How to resume Fragment from BackStack if exists

I know this is quite late to answer this question but I resolved this problem by myself and thought worth sharing it with everyone.`

public void replaceFragment(BaseFragment fragment) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    final FragmentManager fManager = getSupportFragmentManager();
    BaseFragment fragm = (BaseFragment) fManager.findFragmentByTag(fragment.getFragmentTag());
    transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);

    if (fragm == null) {  //here fragment is not available in the stack
        transaction.replace(R.id.container, fragment, fragment.getFragmentTag());
        transaction.addToBackStack(fragment.getFragmentTag());
    } else { 
        //fragment was found in the stack , now we can reuse the fragment
        // please do not add in back stack else it will add transaction in back stack
        transaction.replace(R.id.container, fragm, fragm.getFragmentTag()); 
    }
    transaction.commit();
}

And in the onBackPressed()

 @Override
public void onBackPressed() {
    if(getSupportFragmentManager().getBackStackEntryCount()>1){
        super.onBackPressed();
    }else{
        finish();
    }
}

Javascript call() & apply() vs bind()?

I think the same places of them are: all of them can change the this value of a function.The differences of them are: the bind function will return a new function as a result; the call and apply methods will execute the function immediately, but apply can accept a array as params,and it will parse the array separated.And also, the bind function can be Currying.

The difference between the 'Local System' account and the 'Network Service' account?

Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.

First the actual accounts:

  • LocalService account (preferred)

    A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.

    • Name: NT AUTHORITY\LocalService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the LocalService user account
    • has minimal privileges on the local computer
    • presents anonymous credentials on the network
    • SID: S-1-5-19
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-19)

     

  • NetworkService account

    Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).

    • NT AUTHORITY\NetworkService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the NetworkService user account
    • has minimal privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers
    • SID: S-1-5-20
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-20)
    • If trying to schedule a task using it, enter NETWORK SERVICE into the Select User or Group dialog

     

  • LocalSystem account (dangerous, don't use!)

    Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)

    • Name: .\LocalSystem (can also use LocalSystem or ComputerName\LocalSystem)
    • the account has no password (any password information you provide is ignored)
    • SID: S-1-5-18
    • does not have any profile of its own (HKCU represents the default user)
    • has extensive privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers

     

Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService can still access the internet.

The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).

It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.

In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).


In Windows Server 2003 you cannot run a scheduled task as

  • NT_AUTHORITY\LocalService (aka the Local Service account), or
  • NT AUTHORITY\NetworkService (aka the Network Service account).

That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.

A service running as NetworkService presents the machine credentials on the network. This means that if your computer was called mango, it would present as the machine account MANGO$:

enter image description here

Eclipse 3.5 Unable to install plugins

I meet the same questions in 3.7 on ubuntu 12.04. My Os use a proxy 127.0.0.1,and the eclipse use another proxy 192.168.1.1.

I read the .log for info. It says !MESSAGE System property http.proxyHost is set to 127.0.0.1 but should be 192.168.1.1.

so I change the eclipse net work setting to the same as the system . At last,it works.

handle textview link click in my android app

Solution

I have implemented a small class with the help of which you can handle long clicks on TextView itself and Taps on the links in the TextView.

Layout

TextView android:id="@+id/text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:autoLink="all"/>

TextViewClickMovement.java

import android.content.Context;
import android.text.Layout;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Patterns;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.TextView;

public class TextViewClickMovement extends LinkMovementMethod {

    private final String TAG = TextViewClickMovement.class.getSimpleName();

    private final OnTextViewClickMovementListener mListener;
    private final GestureDetector                 mGestureDetector;
    private TextView                              mWidget;
    private Spannable                             mBuffer;

    public enum LinkType {

        /** Indicates that phone link was clicked */
        PHONE,

        /** Identifies that URL was clicked */
        WEB_URL,

        /** Identifies that Email Address was clicked */
        EMAIL_ADDRESS,

        /** Indicates that none of above mentioned were clicked */
        NONE
    }

    /**
     * Interface used to handle Long clicks on the {@link TextView} and taps
     * on the phone, web, mail links inside of {@link TextView}.
     */
    public interface OnTextViewClickMovementListener {

        /**
         * This method will be invoked when user press and hold
         * finger on the {@link TextView}
         *
         * @param linkText Text which contains link on which user presses.
         * @param linkType Type of the link can be one of {@link LinkType} enumeration
         */
        void onLinkClicked(final String linkText, final LinkType linkType);

        /**
         *
         * @param text Whole text of {@link TextView}
         */
        void onLongClick(final String text);
    }


    public TextViewClickMovement(final OnTextViewClickMovementListener listener, final Context context) {
        mListener        = listener;
        mGestureDetector = new GestureDetector(context, new SimpleOnGestureListener());
    }

    @Override
    public boolean onTouchEvent(final TextView widget, final Spannable buffer, final MotionEvent event) {

        mWidget = widget;
        mBuffer = buffer;
        mGestureDetector.onTouchEvent(event);

        return false;
    }

    /**
     * Detects various gestures and events.
     * Notify users when a particular motion event has occurred.
     */
    class SimpleOnGestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onDown(MotionEvent event) {
            // Notified when a tap occurs.
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            // Notified when a long press occurs.
            final String text = mBuffer.toString();

            if (mListener != null) {
                Log.d(TAG, "----> Long Click Occurs on TextView with ID: " + mWidget.getId() + "\n" +
                                  "Text: " + text + "\n<----");

                mListener.onLongClick(text);
            }
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent event) {
            // Notified when tap occurs.
            final String linkText = getLinkText(mWidget, mBuffer, event);

            LinkType linkType = LinkType.NONE;

            if (Patterns.PHONE.matcher(linkText).matches()) {
                linkType = LinkType.PHONE;
            }
            else if (Patterns.WEB_URL.matcher(linkText).matches()) {
                linkType = LinkType.WEB_URL;
            }
            else if (Patterns.EMAIL_ADDRESS.matcher(linkText).matches()) {
                linkType = LinkType.EMAIL_ADDRESS;
            }

            if (mListener != null) {
                Log.d(TAG, "----> Tap Occurs on TextView with ID: " + mWidget.getId() + "\n" +
                                  "Link Text: " + linkText + "\n" +
                                  "Link Type: " + linkType + "\n<----");

                mListener.onLinkClicked(linkText, linkType);
            }

            return false;
        }

        private String getLinkText(final TextView widget, final Spannable buffer, final MotionEvent event) {

            int x = (int) event.getX();
            int y = (int) event.getY();

            x -= widget.getTotalPaddingLeft();
            y -= widget.getTotalPaddingTop();

            x += widget.getScrollX();
            y += widget.getScrollY();

            Layout layout = widget.getLayout();
            int line = layout.getLineForVertical(y);
            int off = layout.getOffsetForHorizontal(line, x);

            ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);

            if (link.length != 0) {
                return buffer.subSequence(buffer.getSpanStart(link[0]),
                        buffer.getSpanEnd(link[0])).toString();
            }

            return "";
        }
    }
}

Usage

TextView tv = (TextView) v.findViewById(R.id.textview);
tv.setText(Html.fromHtml("<a href='test'>test</a>"));
textView.setMovementMethod(new TextViewClickMovement(this, context));

Links

Hope this helps! You can find code here.

Call a function with argument list in python

You can use *args and **kwargs syntax for variable length arguments.

What do *args and **kwargs mean?

And from the official python tutorial

http://docs.python.org/dev/tutorial/controlflow.html#more-on-defining-functions

How to create an HTML button that acts like a link?

@Nicolas,following worked for me as yours didn't have type="button" due to which it started behaving as submit type..since i already have one submit type.it didn't worked for me ....and now you can either add class to button or to <a> to get required layout:

<a href="http://www.google.com/">
    <button type="button">Click here</button>
</a>

Finding the max/min value in an array of primitives using Java

Using Commons Lang (to convert) + Collections (to min/max)

import java.util.Arrays;
import java.util.Collections;

import org.apache.commons.lang.ArrayUtils;

public class MinMaxValue {

    public static void main(String[] args) {
        char[] a = {'3', '5', '1', '4', '2'};

        List b = Arrays.asList(ArrayUtils.toObject(a));

        System.out.println(Collections.min(b));
        System.out.println(Collections.max(b));
   }
}

Note that Arrays.asList() wraps the underlying array, so it should not be too memory intensive and it should not perform a copy on the elements of the array.

How can I print out C++ map values?

Since C++17 you can use range-based for loops together with structured bindings for iterating over your map. This improves readability, as you reduce the amount of needed first and second members in your code:

std::map<std::string, std::pair<std::string, std::string>> myMap;
myMap["x"] = { "a", "b" };
myMap["y"] = { "c", "d" };

for (const auto &[k, v] : myMap)
    std::cout << "m[" << k << "] = (" << v.first << ", " << v.second << ") " << std::endl;

Output:

m[x] = (a, b)
m[y] = (c, d)

Code on Coliru

Does Enter key trigger a click event?

For angular 6 there is a new way of doing it. On your input tag add

(keyup.enter)="keyUpFunction($event)"

Where keyUpFunction($event) is your function.

What does the construct x = x || y mean?

Basically it checks if the value before the || evaluates to true, if yes, it takes this value, if not, it takes the value after the ||.

Values for which it will take the value after the || (as far as i remember):

  • undefined
  • false
  • 0
  • '' (Null or Null string)

Display curl output in readable JSON format in Unix shell script

I am guessing that you want to prettify the JSON output. That could be achieved using python:

curl http://localhost:8880/test.json | python -mjson.tool > out.json

unix - count of columns in file

Proper pure way

Under bash, you could simply:

IFS=\| read -ra headline <stores.dat
echo ${#headline[@]}
4

A lot quicker as without forks, and reusable as $headline hold the full head line. You could, for sample:

printf " - %s\n" "${headline[@]}"
 - sid
 - storeNo
 - latitude
 - longitude

Nota This syntax will drive correctly spaces and others characters in column names.

Alternative: strong binary checking for max columns on each rows

What if some row do contain some extra columns?

This command will search for bigger line, counting separators:

tr -dc $'\n|' <stores.dat |wc -L
3

There are max 3 separators, then 4 fields.

Action Bar's onClick listener for the Home button

you should to delete your the Override onOptionsItemSelected and replate your onCreateOptionsMenu with this code

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_action_bar_finish_order_stop, menu);
        menu.getItem(0).setOnMenuItemClickListener(new FinishOrderStopListener(this, getApplication(), selectedChild));
        return true;

    }

LINQ to Entities how to update a record

//for update

(from x in dataBase.Customers
         where x.Name == "Test"
         select x).ToList().ForEach(xx => xx.Name="New Name");

//for delete

dataBase.Customers.RemoveAll(x=>x.Name=="Name");

Why doesn't CSS ellipsis work in table cell?

Leave your tables as they are. Just wrap the content inside the TD's with a span that has the truncation CSS applied.

/* CSS */
.truncate {
    width: 50px; /*your fixed width */
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: block; /* this fixes your issue */
}

<!-- HTML -->
<table>
    <tbody>
        <tr>
            <td>
                <span class="truncate">
                    Table data to be truncated if it's too long.
                </span>
            </td>
        </tr>
    </tbody>
</table>

Use '=' or LIKE to compare strings in SQL?

There's a couple of other tricks that Postgres offers for string matching (if that happens to be your DB):

ILIKE, which is a case insensitive LIKE match:

select * from people where name ilike 'JOHN'

Matches:

  • John
  • john
  • JOHN

And if you want to get really mad you can use regular expressions:

select * from people where name ~ 'John.*'

Matches:

  • John
  • Johnathon
  • Johnny

Scraping data from website using vba

I modified some thing that were poping up error for me and end up with this which worked great to extract the data as I needed:

Sub get_data_web()

Dim appIE As Object
Set appIE = CreateObject("internetexplorer.application")

With appIE
    .navigate "https://finance.yahoo.com/quote/NQ%3DF/futures?p=NQ%3DF"
    .Visible = True
End With

Do While appIE.Busy
    DoEvents
Loop

Set allRowofData = appIE.document.getElementsByClassName("Ta(end) BdT Bdc($c-fuji-grey-c) H(36px)")

Dim i As Long
Dim myValue As String

Count = 1

    For Each itm In allRowofData

        For i = 0 To 4

        myValue = itm.Cells(i).innerText
        ActiveSheet.Cells(Count, i + 1).Value = myValue

        Next

        Count = Count + 1

    Next

appIE.Quit
Set appIE = Nothing


End Sub

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

Here is the purely cross platform and neat way:

1) Define a trigger action

namespace CustomTriggers {
   public class DeselectListViewItemAction:TriggerAction<ListView> {
       protected override void Invoke(ListView sender) {
                sender.SelectedItem = null;
       }
   }
}

2) Apply the above class instance as an EventTrigger action in XAML as below

 <ListView x:Name="YourListView" ItemsSource="{Binding ViewModelItems}">
    <ListView.Triggers>
        <EventTrigger Event="ItemSelected">
            <customTriggers:DeselectListViewItemAction></customTriggers:DeselectListViewItemAction>
        </EventTrigger>
    </ListView.Triggers>
</ListView>

Don't forget to add xmlns:customTriggers="clr-namespace:CustomTriggers;assembly=ProjectAssembly"

Note: Because none of your items are in selected mode, selection styling will not get applied on either of the platforms.

Convert seconds to hh:mm:ss in Python

Just be careful when dividing by 60: division between integers returns an integer -> 12/60 = 0 unless you import division from future. The following is copy and pasted from Python 2.6.2:

IDLE 2.6.2      
>>> 12/60
0
>>> from __future__ import division
>>> 12/60
0.20000000000000001

How to print a double with two decimals in Android?

yourTextView.setText(String.format("Value of a: %.2f", a));

Javascript add method to object

This all depends on how you're creating Foo, and how you intend to use .bar().

First, are you using a constructor-function for your object?

var myFoo = new Foo();

If so, then you can extend the Foo function's prototype property with .bar, like so:

function Foo () { /*...*/ }
Foo.prototype.bar = function () { /*...*/ };

var myFoo = new Foo();
myFoo.bar();

In this fashion, each instance of Foo now has access to the SAME instance of .bar.
To wit: .bar will have FULL access to this, but will have absolutely no access to variables within the constructor function:

function Foo () { var secret = 38; this.name = "Bob"; }
Foo.prototype.bar = function () { console.log(secret); };
Foo.prototype.otherFunc = function () { console.log(this.name); };

var myFoo = new Foo();
myFoo.otherFunc(); // "Bob";
myFoo.bar(); // error -- `secret` is undefined...
             // ...or a value of `secret` in a higher/global scope

In another way, you could define a function to return any object (not this), with .bar created as a property of that object:

function giveMeObj () {
    var private = 42,
        privateBar = function () { console.log(private); },
        public_interface = {
            bar : privateBar
        };

    return public_interface;
}

var myObj = giveMeObj();
myObj.bar(); // 42

In this fashion, you have a function which creates new objects.
Each of those objects has a .bar function created for them.
Each .bar function has access, through what is called closure, to the "private" variables within the function that returned their particular object.
Each .bar still has access to this as well, as this, when you call the function like myObj.bar(); will always refer to myObj (public_interface, in my example Foo).

The downside to this format is that if you are going to create millions of these objects, that's also millions of copies of .bar, which will eat into memory.

You could also do this inside of a constructor function, setting this.bar = function () {}; inside of the constructor -- again, upside would be closure-access to private variables in the constructor and downside would be increased memory requirements.

So the first question is:
Do you expect your methods to have access to read/modify "private" data, which can't be accessed through the object itself (through this or myObj.X)?

and the second question is: Are you making enough of these objects so that memory is going to be a big concern, if you give them each their own personal function, instead of giving them one to share?

For example, if you gave every triangle and every texture their own .draw function in a high-end 3D game, that might be overkill, and it would likely affect framerate in such a delicate system...

If, however, you're looking to create 5 scrollbars per page, and you want each one to be able to set its position and keep track of if it's being dragged, without letting every other application have access to read/set those same things, then there's really no reason to be scared that 5 extra functions are going to kill your app, assuming that it might already be 10,000 lines long (or more).

Duplicate AssemblyVersion Attribute

For me it was that AssembyInfo.cs and SolutionInfo.cs had different values. So check these files as well. I just removed the version from one of them.

error LNK2005, already defined?

And if you want these translation units to share this variable, define int k; in A.cpp and put extern int k; in B.cpp.

How do you change the formatting options in Visual Studio Code?

Same thing happened to me just now. I set prettier as the Default Formatter in Settings and it started working again. My Default Formatter was null.

To set VSCODE Default Formatter

File -> Preferences -> Settings (for Windows) Code -> Preferences -> Settings (for Mac)

Search for "Default Formatter". In the dropdown, prettier will show as esbenp.prettier-vscode.

VSCODE Editor Option

How to substring in jquery

No jQuery needed! Just use the substring method:

var gorge = name.substring(4);

Or if the text you want to remove isn't static:

var name = 'nameGorge';
var toRemove = 'name';
var gorge = name.replace(toRemove,'');

How to replace master branch in Git, entirely, from another branch?

You should be able to use the "ours" merge strategy to overwrite master with seotweaks like this:

git checkout seotweaks
git merge -s ours master
git checkout master
git merge seotweaks

The result should be your master is now essentially seotweaks.

(-s ours is short for --strategy=ours)

From the docs about the 'ours' strategy:

This resolves any number of heads, but the resulting tree of the merge is always that of the current branch head, effectively ignoring all changes from all other branches. It is meant to be used to supersede old development history of side branches. Note that this is different from the -Xours option to the recursive merge strategy.

Update from comments: If you get fatal: refusing to merge unrelated histories, then change the second line to this: git merge --allow-unrelated-histories -s ours master

What's the most concise way to read query parameters in AngularJS?

you could also use $location.$$search.yourparameter

Reading From A Text File - Batch

Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.

So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.

cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit

But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.

@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit

Or if you'd like them to select the file from which to write in the batch you could do the following.

@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit

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

There are any number of ways to do this. For example:

double d = 5.0;
bool isInt = d == (int)d;

You can also use modulo.

double d = 5.0;
bool isInt = d % 1 == 0;

Can I make dynamic styles in React Native?

If you are using a screen with filters for example, and you want to set the background of the filter regarding if it was selected or not, you can do:

<TouchableOpacity style={this.props.venueFilters.includes('Bar')?styles.filterBtnActive:styles.filterBtn} onPress={()=>this.setFilter('Bar')}>
<Text numberOfLines={1}>
Bar
</Text>
</TouchableOpacity>

On which set filter is:

setVenueFilter(filter){
  var filters = this.props.venueFilters;
  filters.push(filter);
  console.log(filters.includes('Bar'), "Inclui Bar");
  this.setState(previousState => {
    return { updateFilter: !previousState.updateFilter };
  });
  this.props.setVenueFilter(filters);
}

PS: the function this.props.setVenueFilter(filters) is a redux action, and this.props.venueFilters is a redux state.

How do I install chkconfig on Ubuntu?

Install this package in Ubuntu:

apt install sysv-rc-conf

its a substitute for chkconfig cmd.

After install run this cmd:

sysv-rc-conf --list

It'll show all services in all the runlevels. You can also run this:

sysv-rc-conf --level (runlevel number ex:1 2 3 4 5 6 )

Now you can choose which service should be active in boot time.

How can I clear an HTML file input with JavaScript?

Here are my two cents, the input files are stored as array so here is how to null it

document.getElementById('selector').value = []

this return an empty array and works on all browsers

How to delete and update a record in Hive

Once you have installed and configured Hive , create simple table :

hive>create table testTable(id int,name string)row format delimited fields terminated by ',';

Then, try to insert few rowsin test table.

hive>insert into table testTable values (1,'row1'),(2,'row2');

Now try to delete records , you just inserted in table.

hive>delete from testTable where id = 1;

Error! FAILED: SemanticException [Error 10294]: Attempt to do update or delete using transaction manager that does not support these operations.

By default transactions are configured to be off. It is been said that update is not supported with the delete operation used in the conversion manager. To support update/delete , you must change following configuration.

cd  $HIVE_HOME
vi conf/hive-site.xml

Add below properties to file

<property>
  <name>hive.support.concurrency</name>
  <value>true</value>
 </property>
 <property>
  <name>hive.enforce.bucketing</name>
  <value>true</value>
 </property>
 <property>
  <name>hive.exec.dynamic.partition.mode</name>
  <value>nonstrict</value>
 </property>
 <property>
  <name>hive.txn.manager</name>
  <value>org.apache.hadoop.hive.ql.lockmgr.DbTxnManager</value>
 </property>
 <property>
  <name>hive.compactor.initiator.on</name>
  <value>true</value>
 </property>
 <property>
  <name>hive.compactor.worker.threads</name>
  <value>2</value>
 </property>

Restart the service and then try delete command again :

Error!

FAILED: LockException [Error 10280]: Error communicating with the metastore.

There is problem with metastore. In order to use insert/update/delete operation, You need to change following configuration in conf/hive-site.xml as feature is currently in development.

<property>
  <name>hive.in.test</name>
  <value>true</value>
 </property>

Restart the service and then delete command again :

hive>delete from testTable where id = 1;

Error!

FAILED: SemanticException [Error 10297]: Attempt to do update or delete on table default.testTable that does not use an AcidOutputFormat or is not bucketed.

Only ORC file format is supported in this first release. The feature has been built such that transactions can be used by any storage format that can determine how updates or deletes apply to base records (basically, that has an explicit or implicit row id), but so far the integration work has only been done for ORC.

Tables must be bucketed to make use of these features. Tables in the same system not using transactions and ACID do not need to be bucketed.

See below built table example with ORCFileformat, bucket enabled and ('transactional'='true').

hive>create table testTableNew(id int ,name string ) clustered by (id) into 2 buckets stored as orc TBLPROPERTIES('transactional'='true');

Insert :

hive>insert into table testTableNew values (1,'row1'),(2,'row2'),(3,'row3');

Update :

hive>update testTableNew set name = 'updateRow2' where id = 2;

Delete :

hive>delete from testTableNew where id = 1;

Test :

hive>select * from testTableNew ;

How to find the Git commit that introduced a string in any branch?

Messing around with the same answers:

$ git config --global alias.find '!git log --color -p -S '
  • ! is needed because other way, git do not pass argument correctly to -S. See this response
  • --color and -p helps to show exactly "whatchanged"

Now you can do

$ git find <whatever>

or

$ git find <whatever> --all
$ git find <whatever> master develop

Is there a difference between x++ and ++x in java?

Yes, the value returned is the value after and before the incrementation, respectively.

class Foo {
    public static void main(String args[]) {
        int x = 1;
        int a = x++;
        System.out.println("a is now " + a);
        x = 1;
        a = ++x;
        System.out.println("a is now " + a);
    }
}

$ java Foo
a is now 1
a is now 2

What is a Y-combinator?

I wonder if there's any use in attempting to build this from the ground up. Let's see. Here's a basic, recursive factorial function:

function factorial(n) {
    return n == 0 ? 1 : n * factorial(n - 1);
}

Let's refactor and create a new function called fact that returns an anonymous factorial-computing function instead of performing the calculation itself:

function fact() {
    return function(n) {
        return n == 0 ? 1 : n * fact()(n - 1);
    };
}

var factorial = fact();

That's a little weird, but there's nothing wrong with it. We're just generating a new factorial function at each step.

The recursion at this stage is still fairly explicit. The fact function needs to be aware of its own name. Let's parameterize the recursive call:

function fact(recurse) {
    return function(n) {
        return n == 0 ? 1 : n * recurse(n - 1);
    };
}

function recurser(x) {
    return fact(recurser)(x);
}

var factorial = fact(recurser);

That's great, but recurser still needs to know its own name. Let's parameterize that, too:

function recurser(f) {
    return fact(function(x) {
        return f(f)(x);
    });
}

var factorial = recurser(recurser);

Now, instead of calling recurser(recurser) directly, let's create a wrapper function that returns its result:

function Y() {
    return (function(f) {
        return f(f);
    })(recurser);
}

var factorial = Y();

We can now get rid of the recurser name altogether; it's just an argument to Y's inner function, which can be replaced with the function itself:

function Y() {
    return (function(f) {
        return f(f);
    })(function(f) {
        return fact(function(x) {
            return f(f)(x);
        });
    });
}

var factorial = Y();

The only external name still referenced is fact, but it should be clear by now that that's easily parameterized, too, creating the complete, generic, solution:

function Y(le) {
    return (function(f) {
        return f(f);
    })(function(f) {
        return le(function(x) {
            return f(f)(x);
        });
    });
}

var factorial = Y(function(recurse) {
    return function(n) {
        return n == 0 ? 1 : n * recurse(n - 1);
    };
});

How to align matching values in two columns in Excel, and bring along associated values in other columns

Skip all of this. Download Microsoft FUZZY LOOKUP add in. Create tables using your columns. Create a new worksheet. INPUT tables into the tool. Click all corresponding columns check boxes. Use slider for exact matches. HIT go and wait for the magic.

Get a list of all functions and procedures in an Oracle database

SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE')

The column STATUS tells you whether the object is VALID or INVALID. If it is invalid, you have to try a recompile, ORACLE can't tell you if it will work before.

jQuery: how to trigger anchor link's click event

You cannot open in a new tab programmatically, it's a browser functionality. You can open a link in an external window . Have a look here

Redirecting to a page after submitting form in HTML

For anyone else having the same problem, I figured it out myself.

_x000D_
_x000D_
    <html>_x000D_
      <body>_x000D_
        <form target="_blank" action="https://website.com/action.php" method="POST">_x000D_
          <input type="hidden" name="fullname" value="Sam" />_x000D_
          <input type="hidden" name="city" value="Dubai&#32;" />_x000D_
          <input onclick="window.location.href = 'https://website.com/my-account';" type="submit" value="Submit request" />_x000D_
        </form>_x000D_
      </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

All I had to do was add the target="_blank" attribute to inline on form to open the response in a new page and redirect the other page using onclick on the submit button.

How to change working directory in Jupyter Notebook?

Running os.chdir(NEW_PATH) will change the working directory.

import os
os.getcwd()
Out[2]:
'/tmp'
In [3]:

os.chdir('/')
In [4]:


os.getcwd()
Out[4]:
'/'
In [ ]:

How to convert a time string to seconds?

without imports

time = "01:34:11"
sum(x * int(t) for x, t in zip([3600, 60, 1], time.split(":"))) 

CSS text-align not working

You have to make the UL inside the div behave like a block. Try adding

.navigation ul {
     display: inline-block;
}

How do I split a string in Rust?

Use split()

let mut split = "some string 123 ffd".split("123");

This gives an iterator, which you can loop over, or collect() into a vector.

for s in split {
    println!("{}", s)
}
let vec = split.collect::<Vec<&str>>();
// OR
let vec: Vec<&str> = split.collect();

Getting java.net.SocketTimeoutException: Connection timed out in android

I was facing this problem and the solution was to restart my modem (router). I could get connection for my app to internet after that.

I think the library I am using is not managing connections properly because it happeend just few times.

How To Inject AuthenticationManager using Java Configuration in a Custom Filter

In addition to what Angular University said above you may want to use @Import to aggregate @Configuration classes to the other class (AuthenticationController in my case) :

@Import(SecurityConfig.class)
@RestController
public class AuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
//some logic
}

Spring doc about Aggregating @Configuration classes with @Import: link

How to use subList()

You could use streams in Java 8. To always get 10 entries at the most, you could do:

dataList.stream().skip(5).limit(10).collect(Collectors.toList());
dataList.stream().skip(30).limit(10).collect(Collectors.toList());

Inline JavaScript onclick function

This isn't really recommended, but you can do it all inline like so:

<a href="#" onClick="function test(){ /* Do something */  } test(); return false;"></a>

But I can't think of any situations off hand where this would be better than writing the function somewhere else and invoking it onClick.

MySQL's now() +1 day

better use quoted `data` and `date`. AFAIR these may be reserved words my version is:

INSERT INTO `table` ( `data` , `date` ) VALUES('".$date."',NOW()+INTERVAL 1 DAY);

Adding timestamp to a filename with mv in BASH

The few lines you posted from your script look okay to me. It's probably something a bit deeper.

You need to find which line is giving you this error. Add set -xv to the top of your script. This will print out the line number and the command that's being executed to STDERR. This will help you identify where in your script you're getting this particular error.

BTW, do you have a shebang at the top of your script? When I see something like this, I normally expect its an issue with the Shebang. For example, if you had #! /bin/bash on top, but your bash interpreter is located in /usr/bin/bash, you'll see this error.

EDIT

New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file?

Two ways:

  1. Select the Edit->EOL Conversion->Unix Format menu item when you edit a file. Once it has the correct line endings, Notepad++ will keep them.
  2. To make sure all new files have the correct line endings, go to the Settings->Preferences menu item, and pull up the Preferences dialog box. Select the New Document/Default Directory tab. Under New Document and Format, select the Unix radio button. Click the Close button.

Convert timestamp in milliseconds to string formatted time in Java

long second = TimeUnit.MILLISECONDS.toSeconds(millis);
long minute = TimeUnit.MILLISECONDS.toMinutes(millis);
long hour = TimeUnit.MILLISECONDS.toHours(millis);
millis -= TimeUnit.SECONDS.toMillis(second);
return String.format("%02d:%02d:%02d:%d", hour, minute, second, millis);

What is the equivalent of 'describe table' in SQL Server?

The query below will provide similar output as the info() function in python, Pandas library.

USE [Database_Name]

IF OBJECT_ID('tempdo.dob.#primary_key', 'U') IS NOT NULL DROP TABLE #primary_key

SELECT 
CONS_T.TABLE_CATALOG,
CONS_T.TABLE_SCHEMA,
CONS_T.TABLE_NAME,
CONS_C.COLUMN_NAME,
CONS_T.CONSTRAINT_TYPE,
CONS_T.CONSTRAINT_NAME
INTO  #primary_key
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS CONS_T 
JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS CONS_C ON CONS_C.CONSTRAINT_NAME= CONS_T.CONSTRAINT_NAME


SELECT
SMA.name AS [Schema Name],
ST.name AS [Table Name],
SC.column_id AS [Column Order],
SC.name AS [Column Name],
PKT.CONSTRAINT_TYPE, 
PKT.CONSTRAINT_NAME, 
SC.system_type_id,
STP.name AS [Data Type],
SC.max_length,
SC.precision, 
SC.scale, 
SC.is_nullable, 
SC.is_masked
FROM sys.tables  AS ST
JOIN sys.schemas AS SMA ON SMA.schema_id = ST.schema_id
JOIN sys.columns AS SC ON SC.object_id = ST.object_id 
JOIN sys.types AS STP ON STP.system_type_id = SC.system_type_id
LEFT JOIN #primary_key AS PKT ON PKT.TABLE_SCHEMA = SMA.name
                                 AND PKT.TABLE_NAME = ST.name
                                 AND PKT.COLUMN_NAME = SC.name
ORDER BY ST.name ASC, SMA.name ASC

Best way to generate xml?

Use lxml.builder class, from: http://lxml.de/tutorial.html#the-e-factory

import lxml.builder as lb
from lxml import etree

nstext = "new story"
story = lb.E.Asset(
  lb.E.Attribute(nstext, name="Name", act="set"),
  lb.E.Relation(lb.E.Asset(idref="Scope:767"),
            name="Scope", act="set")
  )

print 'story:\n', etree.tostring(story, pretty_print=True)

Output:

story:
<Asset>
  <Attribute name="Name" act="set">new story</Attribute>
  <Relation name="Scope" act="set">
    <Asset idref="Scope:767"/>
  </Relation>
</Asset>

I'm trying to use python in powershell

$env:path="$env:Path;C:\Python27" will only set it for the current session. Next time you open Powershell, you will have to do the same thing again.

The [Environment]::SetEnvironmentVariable() is the right way, and it would have set your PATH environment variable permanently. You just have to start Powershell again to see the effect in this case.

How to update attributes without validation

All the validation from model are skipped when we use validate: false

user = User.new(....)
user.save(validate: false)

Cause of a process being a deadlock victim

Here is how this particular deadlock problem actually occurred and how it was actually resolved. This is a fairly active database with 130K transactions occurring daily. The indexes in the tables in this database were originally clustered. The client requested us to make the indexes nonclustered. As soon as we did, the deadlocking began. When we reestablished the indexes as clustered, the deadlocking stopped.

Trigger standard HTML5 validation (form) without using submit button?

i was using

objectName.addEventListener('click', function() {
event.preventDefault();
}

but its show error "event is undefined" so in this case use event parameter like

objectName.addEventListener('click', function(event) {
event.preventDefault();
}

now its works fine

Turning a string into a Uri in Android

Uri.parse(STRING);

See doc:

String: an RFC 2396-compliant, encoded URI

Url must be canonicalized before using, like this:

Uri.parse(Uri.decode(STRING));

npm ERR! Error: EPERM: operation not permitted, rename

I closed VS, deleted the node_modules folder.

Then ran:

npm i -D -E [email protected] css- 
[email protected] [email protected] mini-css- 
[email protected] [email protected] [email protected] 
[email protected] [email protected] 

Then had to change the property to not read only on node_modules folder once it got done running.

Then ran:

npm i @microsoft/signalr @types/node

Then opened back up the project in VS and the package.json looked right with the dependencies.

Along the same lines as others talking about read only on node_modules folder and closing down VS to run npm install over.

List<T> OrderBy Alphabetical Order

Do you need the list to be sorted in place, or just an ordered sequence of the contents of the list? The latter is easier:

var peopleInOrder = people.OrderBy(person => person.LastName);

To sort in place, you'd need an IComparer<Person> or a Comparison<Person>. For that, you may wish to consider ProjectionComparer in MiscUtil.

(I know I keep bringing MiscUtil up - it just keeps being relevant...)

In LINQ, select all values of property X where X != null

get one column in the distinct select and ignore null values:

 var items = db.table.Where(p => p.id!=null).GroupBy(p => p.id)
                                .Select(grp => grp.First().id)
                                .ToList();

Android/Java - Date Difference in days

I found a very easy way to do this and it's what I'm using in my app.

Let's say you have the dates in Time objects (or whatever, we just need the milliseconds):

Time date1 = initializeDate1(); //get the date from somewhere
Time date2 = initializeDate2(); //get the date from somewhere

long millis1 = date1.toMillis(true);
long millis2 = date2.toMillis(true);

long difference = millis2 - millis1 ;

//now get the days from the difference and that's it
long days = TimeUnit.MILLISECONDS.toDays(difference);

//now you can do something like
if(days == 7)
{
    //do whatever when there's a week of difference
}

if(days >= 30)
{
    //do whatever when it's been a month or more
}

What's the difference between returning value or Promise.resolve from then()

Both of your examples should behave pretty much the same.

A value returned inside a then() handler becomes the resolution value of the promise returned from that then(). If the value returned inside the .then is a promise, the promise returned by then() will "adopt the state" of that promise and resolve/reject just as the returned promise does.

In your first example, you return "bbb" in the first then() handler, so "bbb" is passed into the next then() handler.

In your second example, you return a promise that is immediately resolved with the value "bbb", so "bbb" is passed into the next then() handler. (The Promise.resolve() here is extraneous).

The outcome is the same.

If you can show us an example that actually exhibits different behavior, we can tell you why that is happening.

Creating an object: with or without `new`

The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.

The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete to do so.

Squash my last X commits together using Git

If you don't care about the commit messages of the in-between commits, you can use

git reset --mixed <commit-hash-into-which-you-want-to-squash>
git commit -a --amend

$(window).height() vs $(document).height

AFAIK $(window).height(); returns the height of your window and $(document).height(); returns the height of your document

Java word count program

you should make your code more generic by considering other word separators as well.. such as "," ";" etc.

public class WordCounter{
    public int count(String input){
        int count =0;
        boolean incrementCounter = false;
        for (int i=0; i<input.length(); i++){
            if (isValidWordCharacter(input.charAt(i))){
                incrementCounter = true;
            }else if (incrementCounter){
                count++;
                incrementCounter = false;
            }
        }
        if (incrementCounter) count ++;//if string ends with a valid word
        return count;
    }
    private boolean isValidWordCharacter(char c){
        //any logic that will help you identify a valid character in a word
        // you could also have a method which identifies word separators instead of this
        return (c >= 'A' && c<='Z') || (c >= 'a' && c<='z'); 
    }
}

Difference between JSON.stringify and JSON.parse

They are opposing each other. JSON.Stringify() converts JSON to string and JSON.Parse() parses a string into JSON.

Passing arguments to angularjs filters

From what I understand you can't pass an arguments to a filter function (when using the 'filter' filter). What you would have to do is to write a custom filter, sth like this:

.filter('weDontLike', function(){

return function(items, name){

    var arrayToReturn = [];        
    for (var i=0; i<items.length; i++){
        if (items[i].name != name) {
            arrayToReturn.push(items[i]);
        }
    }

    return arrayToReturn;
};

Here is the working jsFiddle: http://jsfiddle.net/pkozlowski_opensource/myr4a/1/

The other simple alternative, without writing custom filters is to store a name to filter out in a scope and then write:

$scope.weDontLike = function(item) {
  return item.name != $scope.name;
};

Break string into list of characters in Python

So to add the string hello to a list as individual characters, try this:

newlist = []
newlist[:0] = 'hello'
print (newlist)

  ['h','e','l','l','o']

However, it is easier to do this:

splitlist = list(newlist)
print (splitlist)

How to stop process from .BAT file?

As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:

TSKILL processName

or

TSKILL PID

Have on mind that processName should not have the .exe suffix and is limited to 18 characters.

Another option is WMIC :

wmic Path win32_process Where "Caption Like 'MyProcess.exe'" Call Terminate

wmic offer even more flexibility than taskkill .With wmic Path win32_process get you can see the available fileds you can filter.

SSL Error When installing rubygems, Unable to pull data from 'https://rubygems.org/

On Windows you'll have to use HTTP source to update gem then change back to using HTTPS.

gem sources -r https://rubygems.org/
gem sources -a http://rubygems.org/
gem update --system
gem sources -r http://rubygems.org/
gem sources -a https://rubygems.org/

Edit: Warning I'm not sure if this is safe. Does anyone know if ruby packages are signed? The accepted answer looks like a better solution.

WPF Databinding: How do I access the "parent" data context?

This will also work:

<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl},
                             Path=DataContext.AllowItemCommand}" />

ListView will inherit its DataContext from Window, so it's available at this point, too.
And since ListView, just like similar controls (e. g. Gridview, ListBox, etc.), is a subclass of ItemsControl, the Binding for such controls will work perfectly.

Google Play error "Error while retrieving information from server [DF-DFERH-01]"

In my case, this error message was displayed when I tried downloading an app from Google Play Store using a VPN. The download only worked when I disabled the VPN. Using a VPN, downloads were only working for the apps I downloaded previously.

This looks like a censorship from Google, which is really bad for the user experience and I hope they will stop this.

Fortunately I don't use Android on my smartphone, it was on my Linux laptop using Anbox or Android x86 in VirtualBox.

Play multiple CSS animations at the same time

you can try something like this

set the parent to rotate and the image to scale so that the rotate and scale time can be different

_x000D_
_x000D_
div {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  width: 120px;_x000D_
  height: 120px;_x000D_
  margin: -60px 0 0 -60px;_x000D_
  -webkit-animation: spin 2s linear infinite;_x000D_
}_x000D_
.image {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  width: 120px;_x000D_
  height: 120px;_x000D_
  margin: -60px 0 0 -60px;_x000D_
  -webkit-animation: scale 4s linear infinite;_x000D_
}_x000D_
@-webkit-keyframes spin {_x000D_
  100% {_x000D_
    transform: rotate(180deg);_x000D_
  }_x000D_
}_x000D_
@-webkit-keyframes scale {_x000D_
  100% {_x000D_
    transform: scale(2);_x000D_
  }_x000D_
}
_x000D_
<div>_x000D_
  <img class="image" src="http://makeameme.org/media/templates/120/grumpy_cat.jpg" alt="" width="120" height="120" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Unix tail equivalent command in Windows Powershell

try Windows Server 2003 Resource Kit Tools

it contains a tail.exe which can be run on Windows system.

https://www.microsoft.com/en-us/download/details.aspx?id=17657

TypeError: Router.use() requires middleware function but got a Object

check your routes.js file

example my routes.js

_x000D_
_x000D_
    const express = require('express')_x000D_
    const router = express.Router()_x000D_
    _x000D_
    const usersController = require('../app/controllers/usersController')_x000D_
    const autheticateuser = require('../app/middlewares/authentication')_x000D_
    _x000D_
    router.post('/users/login', autheticateuser, usersController.login)_x000D_
    router.post('/users/register', autheticateuser, usersController.register)_x000D_
      
_x000D_
_x000D_
_x000D_

check end of routes.js

module.exports = router

if not there add and module.exports = router run again


If your Error is : "TypeError: Route.post() or Route.get() requires middleware function but got a Object"

goto controller.js (i.e., usersController) and check all the function names you might misspelled , or you given in function routes file but missed in contollers

_x000D_
_x000D_
const User = require('../models/user')_x000D_
const express = require('express')_x000D_
const router = express.Router()_x000D_
_x000D_
_x000D_
_x000D_
module.exports.register = (req, res) => {_x000D_
    const data = req.body_x000D_
    const user = new User(data)_x000D_
    user.save()_x000D_
        .then((user) => {_x000D_
            res.send(user)_x000D_
        })_x000D_
        .catch((err) => {_x000D_
            res.json(err)_x000D_
        })_x000D_
}
_x000D_
_x000D_
_x000D_

in routes.js i given two routes but in controllers i missed to define route for

router.post('/users/login')

this will make error **

"TypeError: route.post() requires middleware function but got a Object"

**

Checking if my Windows application is running

you need a way to say that "i am running" from the app,

1) open a WCF ping service 2) write to registry/file on startup and delete on shutdown 3) create a Mutex

... i prefer the WCF part because you may not clean up file/registry correctly and Mutex seems to have its own issues

What are the benefits of learning Vim?

I've been using vi and vim also for some 20 years, and I'm still learning new things.

David Rayner's Best of Vim Tips site is an excellent list, though it's probably more useful once you have some familiarity with vim.

I also want to mention the ViEmu site which has some great info on vi/vim tips and especially the article Why, oh WHY, do those nutheads use vi? (archived version)

How to implement a ConfigurationSection with a ConfigurationElementCollection

If you are looking for a custom configuration section like following

<CustomApplicationConfig>
        <Credentials Username="itsme" Password="mypassword"/>
        <PrimaryAgent Address="10.5.64.26" Port="3560"/>
        <SecondaryAgent Address="10.5.64.7" Port="3570"/>
        <Site Id="123" />
        <Lanes>
          <Lane Id="1" PointId="north" Direction="Entry"/>
          <Lane Id="2" PointId="south" Direction="Exit"/>
        </Lanes> 
</CustomApplicationConfig>

then you can use my implementation of configuration section so to get started add System.Configuration assembly reference to your project

Look at the each nested elements I used, First one is Credentials with two attributes so lets add it first

Credentials Element

public class CredentialsConfigElement : System.Configuration.ConfigurationElement
    {
        [ConfigurationProperty("Username")]
        public string Username
        {
            get 
            {
                return base["Username"] as string;
            }
        }

        [ConfigurationProperty("Password")]
        public string Password
        {
            get
            {
                return base["Password"] as string;
            }
        }
    }

PrimaryAgent and SecondaryAgent

Both has the same attributes and seem like a Address to a set of servers for a primary and a failover, so you just need to create one element class for both of those like following

public class ServerInfoConfigElement : ConfigurationElement
    {
        [ConfigurationProperty("Address")]
        public string Address
        {
            get
            {
                return base["Address"] as string;
            }
        }

        [ConfigurationProperty("Port")]
        public int? Port
        {
            get
            {
                return base["Port"] as int?;
            }
        }
    }

I'll explain how to use two different element with one class later in this post, let us skip the SiteId as there is no difference in it. You just have to create one class same as above with one property only. let us see how to implement Lanes collection

it is splitted in two parts first you have to create an element implementation class then you have to create collection element class

LaneConfigElement

public class LaneConfigElement : ConfigurationElement
    {
        [ConfigurationProperty("Id")]
        public string Id
        {
            get
            {
                return base["Id"] as string;
            }
        }

        [ConfigurationProperty("PointId")]
        public string PointId
        {
            get
            {
                return base["PointId"] as string;
            }
        }

        [ConfigurationProperty("Direction")]
        public Direction? Direction
        {
            get
            {
                return base["Direction"] as Direction?;
            }
        }
    }

    public enum Direction
    { 
        Entry,
        Exit
    }

you can notice that one attribute of LanElement is an Enumeration and if you try to use any other value in configuration which is not defined in Enumeration application will throw an System.Configuration.ConfigurationErrorsException on startup. Ok lets move on to Collection Definition

[ConfigurationCollection(typeof(LaneConfigElement), AddItemName = "Lane", CollectionType = ConfigurationElementCollectionType.BasicMap)]
    public class LaneConfigCollection : ConfigurationElementCollection
    {
        public LaneConfigElement this[int index]
        {
            get { return (LaneConfigElement)BaseGet(index); }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                BaseAdd(index, value);
            }
        }

        public void Add(LaneConfigElement serviceConfig)
        {
            BaseAdd(serviceConfig);
        }

        public void Clear()
        {
            BaseClear();
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new LaneConfigElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((LaneConfigElement)element).Id;
        }

        public void Remove(LaneConfigElement serviceConfig)
        {
            BaseRemove(serviceConfig.Id);
        }

        public void RemoveAt(int index)
        {
            BaseRemoveAt(index);
        }

        public void Remove(String name)
        {
            BaseRemove(name);
        }

    }

you can notice that I have set the AddItemName = "Lane" you can choose whatever you like for your collection entry item, i prefer to use "add" the default one but i changed it just for the sake of this post.

Now all of our nested Elements have been implemented now we should aggregate all of those in a class which has to implement System.Configuration.ConfigurationSection

CustomApplicationConfigSection

public class CustomApplicationConfigSection : System.Configuration.ConfigurationSection
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(CustomApplicationConfigSection));
        public const string SECTION_NAME = "CustomApplicationConfig";

        [ConfigurationProperty("Credentials")]
        public CredentialsConfigElement Credentials
        {
            get
            {
                return base["Credentials"] as CredentialsConfigElement;
            }
        }

        [ConfigurationProperty("PrimaryAgent")]
        public ServerInfoConfigElement PrimaryAgent
        {
            get
            {
                return base["PrimaryAgent"] as ServerInfoConfigElement;
            }
        }

        [ConfigurationProperty("SecondaryAgent")]
        public ServerInfoConfigElement SecondaryAgent
        {
            get
            {
                return base["SecondaryAgent"] as ServerInfoConfigElement;
            }
        }

        [ConfigurationProperty("Site")]
        public SiteConfigElement Site
        {
            get
            {
                return base["Site"] as SiteConfigElement;
            }
        }

        [ConfigurationProperty("Lanes")]
        public LaneConfigCollection Lanes
        {
            get { return base["Lanes"] as LaneConfigCollection; }
        }
    }

Now you can see that we have two properties with name PrimaryAgent and SecondaryAgent both have the same type now you can easily understand why we had only one implementation class against these two element.

Before you can use this newly invented configuration section in your app.config (or web.config) you just need to tell you application that you have invented your own configuration section and give it some respect, to do so you have to add following lines in app.config (may be right after start of root tag).

<configSections>
    <section name="CustomApplicationConfig" type="MyNameSpace.CustomApplicationConfigSection, MyAssemblyName" />
  </configSections>

NOTE: MyAssemblyName should be without .dll e.g. if you assembly file name is myDll.dll then use myDll instead of myDll.dll

to retrieve this configuration use following line of code any where in your application

CustomApplicationConfigSection config = System.Configuration.ConfigurationManager.GetSection(CustomApplicationConfigSection.SECTION_NAME) as CustomApplicationConfigSection;

I hope above post would help you to get started with a bit complicated kind of custom config sections.

Happy Coding :)

****Edit**** To Enable LINQ on LaneConfigCollection you have to implement IEnumerable<LaneConfigElement>

And Add following implementation of GetEnumerator

public new IEnumerator<LaneConfigElement> GetEnumerator()
        {
            int count = base.Count;
            for (int i = 0; i < count; i++)
            {
                yield return base.BaseGet(i) as LaneConfigElement;
            }
        }

for the people who are still confused about how yield really works read this nice article

Two key points taken from above article are

it doesn’t really end the method’s execution. yield return pauses the method execution and the next time you call it (for the next enumeration value), the method will continue to execute from the last yield return call. It sounds a bit confusing I think… (Shay Friedman)

Yield is not a feature of the .Net runtime. It is just a C# language feature which gets compiled into simple IL code by the C# compiler. (Lars Corneliussen)

HTML: Image won't display?

I confess to not having read the whole thread. However when I faced a similar issue I found that checking carefully the case of the file name and correcting that in the HTML reference fixed a similar issue. So local preview on Windows worked but when I published to my server (hosted Linux) I had to make sure "mugshot.jpg" was changed to "mugshot.JPG". Part of the problem is the defaults in Windows hiding full file names behind file type indications.

Wait until all promises complete even if some rejected

This should be consistent with how Q does it:

if(!Promise.allSettled) {
    Promise.allSettled = function (promises) {
        return Promise.all(promises.map(p => Promise.resolve(p).then(v => ({
            state: 'fulfilled',
            value: v,
        }), r => ({
            state: 'rejected',
            reason: r,
        }))));
    };
}

Check if an element is present in a Bash array

You could do:

if [[ " ${arr[*]} " == *" d "* ]]; then
    echo "arr contains d"
fi

This will give false positives for example if you look for "a b" -- that substring is in the joined string but not as an array element. This dilemma will occur for whatever delimiter you choose.

The safest way is to loop over the array until you find the element:

array_contains () {
    local seeking=$1; shift
    local in=1
    for element; do
        if [[ $element == "$seeking" ]]; then
            in=0
            break
        fi
    done
    return $in
}

arr=(a b c "d e" f g)
array_contains "a b" "${arr[@]}" && echo yes || echo no    # no
array_contains "d e" "${arr[@]}" && echo yes || echo no    # yes

Here's a "cleaner" version where you just pass the array name, not all its elements

array_contains2 () { 
    local array="$1[@]"
    local seeking=$2
    local in=1
    for element in "${!array}"; do
        if [[ $element == "$seeking" ]]; then
            in=0
            break
        fi
    done
    return $in
}

array_contains2 arr "a b"  && echo yes || echo no    # no
array_contains2 arr "d e"  && echo yes || echo no    # yes

For associative arrays, there's a very tidy way to test if the array contains a given key: The -v operator

$ declare -A arr=( [foo]=bar [baz]=qux )
$ [[ -v arr[foo] ]] && echo yes || echo no
yes
$ [[ -v arr[bar] ]] && echo yes || echo no
no

See 6.4 Bash Conditional Expressions in the manual.

Java 8: merge lists with stream API

In Java 8 we can use stream List1.stream().collect(Collectors.toList()).addAll(List2); Another option List1.addAll(List2)

Checking if any elements in one list are in another

There are different ways. If you just want to check if one list contains any element from the other list, you can do this..

not set(list1).isdisjoint(list2)

I believe using isdisjoint is better than intersection for Python 2.6 and above.

Drawing a line/path on Google Maps

It is really easy with Google Maps Android API v2

Just copy the example from Developer documentation

(of course you have to init your map first)

GoogleMap map;
 // ... get a map.
 // Add a thin red line from London to New York.
 Polyline line = map.addPolyline(new PolylineOptions()
     .add(new LatLng(51.5, -0.1), new LatLng(40.7, -74.0))
     .width(5)
     .color(Color.RED));

How do I get the command-line for an Eclipse run configuration?

I found a solution on Stack Overflow for Java program run configurations which also works for JUnit run configurations.

You can get the full command executed by your configuration on the Debug tab, or more specifically the Debug view.

  1. Run your application
  2. Go to your Debug perspective
  3. There should be an entry in there (in the Debug View) for the app you've just executed
  4. Right-click the node which references java.exe or javaw.exe and select Properties In the dialog that pops up you'll see the Command Line which includes all jars, parameters, etc

Change key pair for ec2 instance

What you can do...

  1. Create a new Instance Profile / Role that has the AmazonEC2RoleForSSM policy attached.

  2. Attach this Instance Profile to the instance.

  3. Use SSM Session Manager to login to the instance.
  4. Use keygen on your local machine to create a key pair.
  5. Push the public part of that key onto the instance using your SSM session.
  6. Profit.

ascending/descending in LINQ - can one change the order via parameter?

You can easily create your own extension method on IEnumerable or IQueryable:

public static IOrderedEnumerable<TSource> OrderByWithDirection<TSource,TKey>
    (this IEnumerable<TSource> source,
     Func<TSource, TKey> keySelector,
     bool descending)
{
    return descending ? source.OrderByDescending(keySelector)
                      : source.OrderBy(keySelector);
}

public static IOrderedQueryable<TSource> OrderByWithDirection<TSource,TKey>
    (this IQueryable<TSource> source,
     Expression<Func<TSource, TKey>> keySelector,
     bool descending)
{
    return descending ? source.OrderByDescending(keySelector)
                      : source.OrderBy(keySelector);
}

Yes, you lose the ability to use a query expression here - but frankly I don't think you're actually benefiting from a query expression anyway in this case. Query expressions are great for complex things, but if you're only doing a single operation it's simpler to just put that one operation:

var query = dataList.OrderByWithDirection(x => x.Property, direction);

How to display a PDF via Android web browser without "downloading" first

You can open PDF in Google Docs Viewer by appending URL to:

http://docs.google.com/gview?embedded=true&url=<url of a supported doc>

This would open PDF in default browser or a WebView.

A list of supported formats is given here.

Create a CSS rule / class with jQuery at runtime

you can apply css an an object. So you can define your object in your javascript like this:

var my_css_class = { backgroundColor : 'blue', color : '#fff' };

And then simply apply it to all the elements you want

$("#myelement").css(my_css_class);

So it is reusable. What purpose would you do this for though?

How do you use a variable in a regular expression?

This:

var txt=new RegExp(pattern,attributes);

is equivalent to this:

var txt=/pattern/attributes;

See http://www.w3schools.com/jsref/jsref_obj_regexp.asp.

How to format x-axis time scale values in Chart.js v2

as per the Chart js documentation page tick configuration section. you can format the value of each tick using the callback function. for example I wanted to change locale of displayed dates to be always German. in the ticks parts of the axis options

ticks: {
    callback: function(value) { 
        return new Date(value).toLocaleDateString('de-DE', {month:'short', year:'numeric'}); 
    },
},

What are valid values for the id attribute in HTML?

From the HTML 4 specification:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

A common mistake is to use an ID that starts with a digit.

How to get child element by class name?

Use YAHOO.util.Dom.getElementsByClassName() from here.

Why do I get AttributeError: 'NoneType' object has no attribute 'something'?

g.d.d.c. is right, but adding a very frequent example:

You might call this function in a recursive form. In that case, you might end up at null pointer or NoneType. In that case, you can get this error. So before accessing an attribute of that parameter check if it's not NoneType.

Swift: Sort array of objects alphabetically

Sorted array Swift 4.2

arrayOfRaces = arrayOfItems.sorted(by: { ($0["raceName"] as! String) < ($1["raceName"] as! String) })

How do you compare structs for equality in C?

It depends on whether the question you are asking is:

  1. Are these two structs the same object?
  2. Do they have the same value?

To find out if they are the same object, compare pointers to the two structs for equality. If you want to find out in general if they have the same value you have to do a deep comparison. This involves comparing all the members. If the members are pointers to other structs you need to recurse into those structs too.

In the special case where the structs do not contain pointers you can do a memcmp to perform a bitwise comparison of the data contained in each without having to know what the data means.

Make sure you know what 'equals' means for each member - it is obvious for ints but more subtle when it comes to floating-point values or user-defined types.

How to determine the Schemas inside an Oracle Data Pump Export file

You need to search for OWNER_NAME.

cat -v dumpfile.dmp | grep -o '<OWNER_NAME>.*</OWNER_NAME>' | uniq -u

cat -v turn the dumpfile into visible text.

grep -o shows only the match so we don't see really long lines

uniq -u removes duplicate lines so you see less output.

This works pretty well, even on large dump files, and could be tweaked for usage in a script.