Programs & Examples On #Onscroll

javascript scroll event for iPhone/iPad?

For iOS you need to use the touchmove event as well as the scroll event like this:

document.addEventListener("touchmove", ScrollStart, false);
document.addEventListener("scroll", Scroll, false);

function ScrollStart() {
    //start of scroll event for iOS
}

function Scroll() {
    //end of scroll event for iOS
    //and
    //start/end of scroll event for other browsers
}

Detecting scroll direction

You can try doing this.

_x000D_
_x000D_
function scrollDetect(){_x000D_
  var lastScroll = 0;_x000D_
_x000D_
  window.onscroll = function() {_x000D_
      let currentScroll = document.documentElement.scrollTop || document.body.scrollTop; // Get Current Scroll Value_x000D_
_x000D_
      if (currentScroll > 0 && lastScroll <= currentScroll){_x000D_
        lastScroll = currentScroll;_x000D_
        document.getElementById("scrollLoc").innerHTML = "Scrolling DOWN";_x000D_
      }else{_x000D_
        lastScroll = currentScroll;_x000D_
        document.getElementById("scrollLoc").innerHTML = "Scrolling UP";_x000D_
      }_x000D_
  };_x000D_
}_x000D_
_x000D_
_x000D_
scrollDetect();
_x000D_
html,body{_x000D_
  height:100%;_x000D_
  width:100%;_x000D_
  margin:0;_x000D_
  padding:0;_x000D_
}_x000D_
_x000D_
.cont{_x000D_
  height:100%;_x000D_
  width:100%;_x000D_
}_x000D_
_x000D_
.item{_x000D_
  margin:0;_x000D_
  padding:0;_x000D_
  height:100%;_x000D_
  width:100%;_x000D_
  background: #ffad33;_x000D_
}_x000D_
_x000D_
.red{_x000D_
  background: red;_x000D_
}_x000D_
_x000D_
p{_x000D_
  position:fixed;_x000D_
  font-size:25px;_x000D_
  top:5%;_x000D_
  left:5%;_x000D_
}
_x000D_
<div class="cont">_x000D_
  <div class="item"></div>_x000D_
  <div class="item red"></div>_x000D_
  <p id="scrollLoc">0</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

oracle SQL how to remove time from date

If your column with DATE datatype has value like below : -

value in column : 10-NOV-2005 06:31:00

Then, You can Use TRUNC function in select query to convert your date-time value to only date like - DD/MM/YYYY or DD-MON-YYYY

select TRUNC(column_1) from table1;

result : 10-NOV-2005

You will see above result - Provided that NLS_DATE_FORMAT is set as like below :-

Alter session NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';

Insert data into hive table

Try to use this with single quotes in data:

insert into table test_hive values ('1','puneet');

How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

This variant is better because you could not know whether file exists or not. You should send correct header when you know for certain that you can read contents of your file. Also, if you have branches of code that does not finish with '.end()', browser will wait until it get them. In other words, your browser will wait a long time.

var fs = require("fs");
var filename = "./index.html";

function start(resp) {

    fs.readFile(filename, "utf8", function(err, data) {
        if (err) {
            // may be filename does not exists?
            resp.writeHead(404, {
                'Content-Type' : 'text/html'
            });
            // log this error into browser
            resp.write(err.toString());
            resp.end();
        } else {

            resp.writeHead(200, {
                "Content-Type": "text/html"
            });      
            resp.write(data.toString());
            resp.end();
        }
    });
}

Could not extract response: no suitable HttpMessageConverter found for response type

public class Application {

    private static List<HttpMessageConverter<?>> getMessageConverters() {
        List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
        converters.add(new MappingJacksonHttpMessageConverter());
        return converters;
    }   

    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();

        restTemplate.setMessageConverters(getMessageConverters());
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        //Page page = restTemplate.getForObject("http://graph.facebook.com/pivotalsoftware", Page.class);

        ResponseEntity<Page> response = 
                  restTemplate.exchange("http://graph.facebook.com/skbh86", HttpMethod.GET, entity, Page.class, "1");
        Page page = response.getBody();
        System.out.println("Name:    " + page.getId());
        System.out.println("About:   " + page.getFirst_name());
        System.out.println("Phone:   " + page.getLast_name());
        System.out.println("Website: " + page.getMiddle_name());
        System.out.println("Website: " + page.getName());
    }
}

Calculate a MD5 hash from a string

This solution requires c# 8 and takes advantage of Span<T>. Note, you would still need to call .Replace("-", string.Empty).ToLowerInvariant() to format the result if necessary.

public static string CreateMD5(ReadOnlySpan<char> input)
{
    var encoding = System.Text.Encoding.UTF8;
    var inputByteCount = encoding.GetByteCount(input);
    using var md5 = System.Security.Cryptography.MD5.Create();

    Span<byte> bytes = inputByteCount < 1024
        ? stackalloc byte[inputByteCount]
        : new byte[inputByteCount];
    Span<byte> destination = stackalloc byte[md5.HashSize / 8];

    encoding.GetBytes(input, bytes);

    // checking the result is not required because this only returns false if "(destination.Length < HashSizeValue/8)", which is never true in this case
    md5.TryComputeHash(bytes, destination, out int _bytesWritten);

    return BitConverter.ToString(destination.ToArray());
}

how to count the spaces in a java string?

public static void main(String[] args) {
    String str = "Honey   dfd    tEch Solution";
    String[] arr = str.split(" ");
    System.out.println(arr.length);
    int count = 0;
    for (int i = 0; i < arr.length; i++) {
        if (!arr[i].trim().isEmpty()) {
            System.out.println(arr[i]);
            count++;
        }
    }
    System.out.println(count);
}

Query to get the names of all tables in SQL Server 2008 Database

In a single database - yes:

USE your_database
SELECT name FROM sys.tables

Getting all tables across all databases - only with a hack.... see this SO question for several approaches how to do that: How do I list all tables in all databases in SQL Server in a single result set?

How to edit HTML input value colour?

You can add color in the style rule of your input: color:#ccc;

Replacing accented characters php

Vietnamese characters for those who need them

'Š'=>'S', 'š'=>'s', 'Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
                            'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U',
                            'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss', 'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c',
                            'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o',
                            'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y' );
$str = strtr( $str, $unwanted_array );

What is the best way to remove a table row with jQuery?

if you have HTML like this

<tr>
 <td><span class="spanUser" userid="123"></span></td>
 <td><span class="spanUser" userid="123"></span></td>
</tr>

where userid="123" is a custom attribute that you can populate dynamically when you build the table,

you can use something like

  $(".spanUser").live("click", function () {

        var span = $(this);   
        var userid = $(this).attr('userid');

        var currentURL = window.location.protocol + '//' + window.location.host;
        var url = currentURL + "/Account/DeleteUser/" + userid;

        $.post(url, function (data) {
          if (data) {
                   var tdTAG = span.parent(); // GET PARENT OF SPAN TAG
                   var trTAG = tdTAG.parent(); // GET PARENT OF TD TAG
                   trTAG.remove(); // DELETE TR TAG == DELETE AN ENTIRE TABLE ROW 
             } else {
                alert('Sorry, there is some error.');
            }
        }); 

     });

So in that case you don't know the class or id of the TR tag but anyway you are able to delete it.

How do I set default value of select box in angularjs

You can just append

track by version.id

to your ng-options.

How can I have same rule for two locations in NGINX config?

Try

location ~ ^/(first/location|second/location)/ {
  ...
}

The ~ means to use a regular expression for the url. The ^ means to check from the first character. This will look for a / followed by either of the locations and then another /.

Solution to INSTALL_FAILED_INSUFFICIENT_STORAGE error on Android

Answering to the very first post of this topic...

Symptom : Some app don't install, saying there is no space and in reallity there is plenty of space free on both internal and external storage !!! Solution: disable external installation by default.

Setting external install by defaut with this:

adb shell pm set-install-location 2

Makes install impossible on many apps that can't install externally (such as adblock + or so)

Then the solution is

adb shell pm set-install-location 0

Or

adb shell pm set-install-location 1

0: auto (if one is full - or irrelevant !!! - it select the other)
1: internal
2: external

How Exactly Does @param Work - Java

You might miss @author and inside of @param you need to explain what's that parameter for, how to use it, etc.

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#

MVP:

Advantages:

Presenter will be present in between Model and view.Presenter will fetch data from Model and will do manipulations for data as view wants and give it to view and view is responsible only for rendering.

Disadvantages:

1)We can't use presenter for multiple modules because data is being modified in presenter as desired by one view class.

3)Breaking Clean architecture because data flow should be only outwards but here data is coming back from presenter to View.

MVC:

Advanatages:

Here we have Controller in between view and model.Here data request will be done from controller to view but data will be sent back to view in form of interface but not with controller.So,here controller won't get bloated up because of many transactions.

Disadvantagaes:

Data Manipulation should be done by View as it wants and this will be extra work on UI thread which may effect UI rendering if data processing is more.

MVVM:

After announcing Architectural components,we got access to ViewModel which provided us biggest advantage i.e it's lifecycle aware.So,it won't notify data if view is not available.It is a clean architecture because flow is only in forward mode and data will be notified automatically by LiveData. So,it is Android's recommended architecture.

Even MVVM has a disadvantage. Since it is a lifecycle aware some concepts like alarm or reminder should come outside app.So,in this scenario we can't use MVVM.

Capitalize words in string

I would use regex for this purpose:

myString = '  this Is my sTring.  ';
myString.trim().toLowerCase().replace(/\w\S*/g, (w) => (w.replace(/^\w/, (c) => c.toUpperCase())));

How to use boolean 'and' in Python

You can also test them as a couple.

if (i,ii)==(5,10):
    print "i is 5 and ii is 10"

Preview an image before it is uploaded

What about this solution?

Just add the data attribute "data-type=editable" to an image tag like this:

<img data-type="editable" id="companyLogo" src="http://www.coventrywebgraphicdesign.co.uk/wp-content/uploads/logo-here.jpg" height="300px" width="300px" />

And the script to your project off course...

function init() {
    $("img[data-type=editable]").each(function (i, e) {
        var _inputFile = $('<input/>')
            .attr('type', 'file')
            .attr('hidden', 'hidden')
            .attr('onchange', 'readImage()')
            .attr('data-image-placeholder', e.id);

        $(e.parentElement).append(_inputFile);

        $(e).on("click", _inputFile, triggerClick);
    });
}

function triggerClick(e) {
    e.data.click();
}

Element.prototype.readImage = function () {
    var _inputFile = this;
    if (_inputFile && _inputFile.files && _inputFile.files[0]) {
        var _fileReader = new FileReader();
        _fileReader.onload = function (e) {
            var _imagePlaceholder = _inputFile.attributes.getNamedItem("data-image-placeholder").value;
            var _img = $("#" + _imagePlaceholder);
            _img.attr("src", e.target.result);
        };
        _fileReader.readAsDataURL(_inputFile.files[0]);
    }
};

// 
// IIFE - Immediately Invoked Function Expression
// https://stackoverflow.com/questions/18307078/jquery-best-practises-in-case-of-document-ready
(

function (yourcode) {
    "use strict";
    // The global jQuery object is passed as a parameter
    yourcode(window.jQuery, window, document);
}(

function ($, window, document) {
    "use strict";
    // The $ is now locally scoped 
    $(function () {
        // The DOM is ready!
        init();
    });

    // The rest of your code goes here!
}));

See demo at JSFiddle

The name 'InitializeComponent' does not exist in the current context

Because of some reason after copying .xaml and it's .cs between projects the build action is sometimes changing. Please make sure build action of your .xaml is Page.

Access to the path denied error in C#

You do not have permissions to access the file. Please be sure whether you can access the file in that drive.

string route= @"E:\Sample.text";
FileStream fs = new FileStream(route, FileMode.Create);

You have to provide the file name to create. Please try this, now you can create.

How to generate xsd from wsdl

(WHEN .wsdl is referring to .xsd/schemas using import) If you're using the WMB Tooklit (v8.0.0.4 WMB) then you can find .xsd using following steps :

Create library (optional) > Right Click , New Message Model File > Select SOAP XML > Choose Option 'I already have WSDL for my data' > 'Select file outside workspace' > 'Select the WSDL bindings to Import' (if there are multiple) > Finish.

This will give you the .xsd and .wsdl files in your Workspace (Application Perspective).

How do I set up curl to permanently use a proxy?

Curl will look for a .curlrc file in your home folder when it starts. You can create (or edit) this file and add this line:

proxy = yourproxy.com:8080

How to read a configuration file in Java

It depends.

Start with Basic I/O, take a look at Properties, take a look at Preferences API and maybe even Java API for XML Processing and Java Architecture for XML Binding

And if none of those meet your particular needs, you could even look at using some kind of Database

How do I find the version of Apache running without access to the command line?

Telnet to the host at port 80.

Type:

get / http1.1
::enter::
::enter::

It is kind of an HTTP request, but it's not valid so the 500 error it gives you will probably give you the information you want. The blank lines at the end are important otherwise it will just seem to hang.

Should URL be case sensitive?

According to W3's "HTML and URLs" they should:

There may be URLs, or parts of URLs, where case doesn't matter, but identifying these may not be easy. Users should always consider that URLs are case-sensitive.

Easiest way to ignore blank lines when reading a file in Python

I guess there is a simple solution which I recently used after going through so many answers here.

with open(file_name) as f_in:   
    for line in f_in:
        if len(line.split()) == 0:
            continue

This just does the same work, ignoring all empty line.

Parse HTML table to Python list?

If the HTML is not XML you can't do it with etree. But even then, you don't have to use an external library for parsing a HTML table. In python 3 you can reach your goal with HTMLParser from html.parser. I've the code of the simple derived HTMLParser class here in a github repo.

You can use that class (here named HTMLTableParser) the following way:

import urllib.request
from html_table_parser import HTMLTableParser

target = 'http://www.twitter.com'

# get website content
req = urllib.request.Request(url=target)
f = urllib.request.urlopen(req)
xhtml = f.read().decode('utf-8')

# instantiate the parser and feed it
p = HTMLTableParser()
p.feed(xhtml)
print(p.tables)

The output of this is a list of 2D-lists representing tables. It looks maybe like this:

[[['   ', ' Anmelden ']],
 [['Land', 'Code', 'Für Kunden von'],
  ['Vereinigte Staaten', '40404', '(beliebig)'],
  ['Kanada', '21212', '(beliebig)'],
  ...
  ['3424486444', 'Vodafone'],
  ['  Zeige SMS-Kurzwahlen für andere Länder ']]]

Push method in React Hooks (useState)?

if you want to push after specific index you can do as below:

   const handleAddAfterIndex = index => {
       setTheArray(oldItems => {
            const copyItems = [...oldItems];
            const finalItems = [];
            for (let i = 0; i < copyItems.length; i += 1) {
                if (i === index) {
                    finalItems.push(copyItems[i]);
                    finalItems.push(newItem);
                } else {
                    finalItems.push(copyItems[i]);
                }
            }
            return finalItems;
        });
    };

Is there a kind of Firebug or JavaScript console debug for Android?

You can type about:debug in some of the mobile browsers to pull up a JavaScript console.

Create a .csv file with values from a Python list

Jupyter notebook

Let's say that your list name is A

Then you can code the following and you will have it as a csv file (columns only!)

R="\n".join(A)
f = open('Columns.csv','w')
f.write(R)
f.close()

How can I make Java print quotes, like "Hello"?

There are two easy methods:

  1. Use backslash \ before double quotes.
  2. Use two single quotes instead of double quotes like '' instead of "

For example:

System.out.println("\"Hello\"");                       
System.out.println("''Hello''"); 

Generating a random password in php

Being a little smarter:

function strand($length){
  if($length > 0)
    return chr(rand(33, 126)) . strand($length - 1);
}

check it here.

Why does JSHint throw a warning if I am using const?

Create .jshintrc file in the root dir and add there the latest js version: "esversion": 9 and asi version: "asi": true (it will help you to avoid using semicolons)

{
    "esversion": 9,
    "asi": true
}

Calling a parent window function from an iframe

<a onclick="parent.abc();" href="#" >Call Me </a>

See window.parent

Returns a reference to the parent of the current window or subframe.

If a window does not have a parent, its parent property is a reference to itself.

When a window is loaded in an <iframe>, <object>, or <frame>, its parent is the window with the element embedding the window.

How to make an Android device vibrate? with different frequency?

Above answers are perfect. However I wanted to vibrate my app exactly twice on button click and this small information is missing here, hence posting for future readers like me. :)

We have to follow as mentioned above and the only change will be in the vibrate pattern as below,

long[] pattern = {0, 100, 1000, 300};
v.vibrate(pattern, -1); //-1 is important

This will exactly vibrate twice. As we already know

  1. 0 is for delay
  2. 100 says vibrate for 100ms for the first time
  3. next comes delay of 1000ms
  4. and post that vibrate again for 300ms

One can go on and on mentioning delay and vibration alternatively (e.g. 0, 100, 1000, 300, 1000, 300 for 3 vibrations and so on..) but remember @Dave's word use it responsibly. :)

Also note here that the repeat parameter is set to -1 which means the vibration will happen exactly as mentioned in the pattern. :)

Enter triggers button click

You can use javascript to block form submission until the appropriate time. A very crude example:

<form onsubmit='return false;' id='frmNoEnterSubmit' action="index.html">

    <input type='text' name='txtTest' />

    <input type='button' value='Submit' 
        onclick='document.forms["frmNoEnterSubmit"].onsubmit=""; document.forms["frmNoEnterSubmit"].submit();' />

</form>

Pressing enter will still trigger the form to submit, but the javascript will keep it from actually submitting, until you actually press the button.

PHP error: "The zip extension and unzip command are both missing, skipping."

For older Ubuntu distros i.e 16.04, 14.04, 12.04 etc

sudo apt-get install zip unzip php7.0-zip

Split an integer into digits to compute an ISBN checksum

On Older versions of Python...

map(int,str(123))

On New Version 3k

list(map(int,str(123)))

Search a string in a file and delete it from this file by Shell Script

Try the vim-way:

ex -s +"g/foo/d" -cwq file.txt

What's the difference between REST & RESTful

As Jason said in the comments, RESTful is just used as an adjective describing something that respects the REST constraints.

How to convert View Model into JSON object in ASP.NET MVC?

<htmltag id=’elementId’ data-ZZZZ’=’@Html.Raw(Json.Encode(Model))’ />

Refer https://highspeedlowdrag.wordpress.com/2014/08/23/mvc-data-to-jquery-data/

I did below and it works like charm.

<input id="hdnElement" class="hdnElement" type="hidden" value='@Html.Raw(Json.Encode(Model))'>

Check if cookie exists else set cookie to Expire in 10 days

You need to read and write document.cookie

if (document.cookie.indexOf("visited=") >= 0) {
  // They've been here before.
  alert("hello again");
}
else {
  // set a new cookie
  expiry = new Date();
  expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes

  // Date()'s toGMTSting() method will format the date correctly for a cookie
  document.cookie = "visited=yes; expires=" + expiry.toGMTString();
  alert("this is your first time");
}

Disabled form inputs do not appear in the request

Semantically this feels like the correct behaviour

I'd be asking myself "Why do I need to submit this value?"

If you have a disabled input on a form, then presumably you do not want the user changing the value directly

Any value that is displayed in a disabled input should either be

  1. output from a value on the server that produced the form, or
  2. if the form is dynamic, be calculable from the other inputs on the form

Assuming that the server processing the form is the same as the server serving it, all the information to reproduce the values of the disabled inputs should be available at processing

In fact, to preserve data integrity - even if the value of the disabled input was sent to the processing server, you should really be validating it. This validation would require the same level of information as you would need to reproduce the values anyway!

I'd almost argue that read-only inputs shouldn't be sent in the request either

Happy to be corrected, but all the use cases I can think of where read-only/disabled inputs need to be submitted are really just styling issues in disguise

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

This happened to me when using java sdk. The problem was for me was i wasnt using the session token from assumed role.

Working code example ( in kotlin )

        val identityUserPoolProviderClient = AWSCognitoIdentityProviderClientBuilder
            .standard()
            .withCredentials(AWSStaticCredentialsProvider(BasicSessionCredentials("accessKeyId", ""secretAccessKey, "sessionToken")))
            .build()

How to hide columns in HTML table?

you can also use:

<td style="visibility:hidden;">
or
<td style="visibility:collapse;">

The difference between them that "hidden" hides the cell but it holds the space but with "collapse" the space is not held like display:none. This is significant when hidding a whole column or row.

std::vector versus std::array in C++

A vector is a container class while an array is an allocated memory.

Which command do I use to generate the build of a Vue app?

For NPM => npm run Build For Yarn => yarn run build

You also can check scripts in package.json file

Set Text property of asp:label in Javascript PROPER way

This one Works for me with asp label control.

 function changeEmaillbl() {


         if (document.getElementById('<%=rbAgency.ClientID%>').checked = true) {
             document.getElementById('<%=lblUsername.ClientID%>').innerHTML = 'Accredited No.:';
         } 
     }

TLS 1.2 not working in cURL

I has similar problem in context of Stripe:

Error: Stripe no longer supports API requests made with TLS 1.0. Please initiate HTTPS connections with TLS 1.2 or later. You can learn more about this at https://stripe.com/blog/upgrading-tls.

Forcing TLS 1.2 using CURL parameter is temporary solution or even it can't be applied because of lack of room to place an update. By default TLS test function https://gist.github.com/olivierbellone/9f93efe9bd68de33e9b3a3afbd3835cf showed following configuration:

SSL version: NSS/3.21 Basic ECC
SSL version number: 0
OPENSSL_VERSION_NUMBER: 1000105f
TLS test (default): TLS 1.0
TLS test (TLS_v1): TLS 1.2
TLS test (TLS_v1_2): TLS 1.2

I updated libraries using following command:

yum update nss curl openssl

and then saw this:

SSL version: NSS/3.21 Basic ECC
SSL version number: 0
OPENSSL_VERSION_NUMBER: 1000105f
TLS test (default): TLS 1.2
TLS test (TLS_v1): TLS 1.2
TLS test (TLS_v1_2): TLS 1.2

Please notice that default TLS version changed to 1.2! That globally solved problem. This will help PayPal users too: https://www.paypal.com/au/webapps/mpp/tls-http-upgrade (update before end of June 2017)

Linux shell script for database backup

After hours and hours work, I created a solution like the below. I copy paste for other people that can benefit.

First create a script file and give this file executable permission.

# cd /etc/cron.daily/
# touch /etc/cron.daily/dbbackup-daily.sh
# chmod 755 /etc/cron.daily/dbbackup-daily.sh
# vi /etc/cron.daily/dbbackup-daily.sh

Then copy following lines into file with Shift+Ins

#!/bin/sh
now="$(date +'%d_%m_%Y_%H_%M_%S')"
filename="db_backup_$now".gz
backupfolder="/var/www/vhosts/example.com/httpdocs/backups"
fullpathbackupfile="$backupfolder/$filename"
logfile="$backupfolder/"backup_log_"$(date +'%Y_%m')".txt
echo "mysqldump started at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
mysqldump --user=mydbuser --password=mypass --default-character-set=utf8 mydatabase | gzip > "$fullpathbackupfile"
echo "mysqldump finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
chown myuser "$fullpathbackupfile"
chown myuser "$logfile"
echo "file permission changed" >> "$logfile"
find "$backupfolder" -name db_backup_* -mtime +8 -exec rm {} \;
echo "old files deleted" >> "$logfile"
echo "operation finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
echo "*****************" >> "$logfile"
exit 0

Edit:
If you use InnoDB and backup takes too much time, you can add "single-transaction" argument to prevent locking. So mysqldump line will be like this:

mysqldump --user=mydbuser --password=mypass --default-character-set=utf8
          --single-transaction mydatabase | gzip > "$fullpathbackupfile"

This app won't run unless you update Google Play Services (via Bazaar)

I've created a (German) description how to get it working. You basically need an emulator with at least API level 9 and no Google APIs. Then you'll have to get the APKs from a rooted device:

adb -d pull /data/app/com.android.vending-2.apk
adb -d pull /data/app/com.google.android.gms-2.apk

and install them in the emulator:

adb -e install com.android.vending-2.apk
adb -e install com.google.android.gms-2.apk

You can even run the native Google Maps App, if you have an emulator with at least API level 14 and additionally install com.google.android.apps.maps-1.apk

Have fun.

How can I determine if a date is between two dates in Java?

Another option

min.getTime() <= d.getTime() && d.getTime() <= max.getTime()

Store multiple values in single key in json

Use arrays:

{
    "number": ["1", "2", "3"],
    "alphabet": ["a", "b", "c"]
}

You can the access the different values from their position in the array. Counting starts at left of array at 0. myJsonObject["number"][0] == 1 or myJsonObject["alphabet"][2] == 'c'

RandomForestClassfier.fit(): ValueError: could not convert string to float

You can't pass str to your model fit() method. as it mentioned here

The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.

Try transforming your data to float and give a try to LabelEncoder.

Web scraping with Python

I would strongly suggest checking out pyquery. It uses jquery-like (aka css-like) syntax which makes things really easy for those coming from that background.

For your case, it would be something like:

from pyquery import *

html = PyQuery(url='http://www.example.com/')
trs = html('table.spad tbody tr')

for tr in trs:
  tds = tr.getchildren()
  print tds[1].text, tds[2].text

Output:

5:16 AM 9:28 PM
5:15 AM 9:30 PM
5:13 AM 9:31 PM
5:12 AM 9:33 PM
5:11 AM 9:34 PM
5:10 AM 9:35 PM
5:09 AM 9:37 PM

What is monkey patching?

A MonkeyPatch is a piece of Python code which extends or modifies other code at runtime (typically at startup).

A simple example looks like this:

from SomeOtherProduct.SomeModule import SomeClass

def speak(self):
    return "ook ook eee eee eee!"

SomeClass.speak = speak

Source: MonkeyPatch page on Zope wiki.

Click through div to underlying elements

An easier way would be to inline the transparent background image using Data URIs as follows:

.click-through {
    pointer-events: none;
    background: url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7);
}

Can enums be subclassed to add new elements?

Under the covers your ENUM is just a regular class generated by the compiler. That generated class extends java.lang.Enum. The technical reason you can't extend the generated class is that the generated class is final. The conceptual reasons for it being final are discussed in this topic. But I'll add the mechanics to the discussion.

Here is a test enum:

public enum TEST {  
    ONE, TWO, THREE;
}

The resulting code from javap:

public final class TEST extends java.lang.Enum<TEST> {
  public static final TEST ONE;
  public static final TEST TWO;
  public static final TEST THREE;
  static {};
  public static TEST[] values();
  public static TEST valueOf(java.lang.String);
}

Conceivably you could type this class on your own and drop the "final". But the compiler prevents you from extending "java.lang.Enum" directly. You could decide NOT to extend java.lang.Enum, but then your class and its derived classes would not be an instanceof java.lang.Enum ... which might not really matter to you any way!

Getting Hour and Minute in PHP

Another way to address the timezone issue if you want to set the default timezone for the entire script to a certian timezone is to use date_default_timezone_set() then use one of the supported timezones.

How can I get a list of all open named pipes in Windows?

At CMD prompt:

>ver

Microsoft Windows [Version 10.0.18362.476]

>dir \\.\pipe\\

Shell Script Syntax Error: Unexpected End of File

I have encountered the same error while trying to execute a script file created in windows OS using textpad. so that one can select proper file format like unix/mac etc.. or recreate the script in linux iteself.

Tools: replace not replacing in Android manifest

You can replace those in your Manifest application tag:

<application
    tools:replace="android:icon, android:label, android:theme, android:name,android:allowBackup"
android:allowBackup="false"...>

and will work for you.

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

Map with Key as String and Value as List in Groovy

Groovy accepts nearly all Java syntax, so there is a spectrum of choices, as illustrated below:

// Java syntax 

Map<String,List> map1  = new HashMap<>();
List list1 = new ArrayList();
list1.add("hello");
map1.put("abc", list1); 
assert map1.get("abc") == list1;

// slightly less Java-esque

def map2  = new HashMap<String,List>()
def list2 = new ArrayList()
list2.add("hello")
map2.put("abc", list2)
assert map2.get("abc") == list2

// typical Groovy

def map3  = [:]
def list3 = []
list3 << "hello"
map3.'abc'= list3
assert map3.'abc' == list3

What is the correct way to write HTML using Javascript?

document.write() doesn't work with XHTML. It's executed after the page has finished loading and does nothing more than write out a string of HTML.

Since the actual in-memory representation of HTML is the DOM, the best way to update a given page is to manipulate the DOM directly.

The way you'd go about doing this would be to programmatically create your nodes and then attach them to an existing place in the DOM. For [purposes of a contrived] example, assuming that I've got a div element maintaining an ID attribute of "header," then I could introduce some dynamic text by doing this:

// create my text
var sHeader = document.createTextNode('Hello world!');

// create an element for the text and append it
var spanHeader = document.createElement('span');
spanHeader.appendChild(sHeader);

// grab a reference to the div header
var divHeader = document.getElementById('header');

// append the new element to the header
divHeader.appendChild(spanHeader);

Entity Framework .Remove() vs. .DeleteObject()

If you really want to use Deleted, you'd have to make your foreign keys nullable, but then you'd end up with orphaned records (which is one of the main reasons you shouldn't be doing that in the first place). So just use Remove()

ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:

A thing worth noting is that setting .State = EntityState.Deleted does not trigger automatically detected change. (archive)

MySQL - How to parse a string value to DATETIME format inside an INSERT statement?

Use MySQL's STR_TO_DATE() function to parse the string that you're attempting to insert:

INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES
  (STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))

Refresh Part of Page (div)

Let's assume that you have 2 divs inside of your html file.

<div id="div1">some text</div>
<div id="div2">some other text</div>

The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.

You can, however, communicate between the server (the back-end) and the client.

What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.

Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.

setInterval(function()
{
    alert("hi");
}, 30000);

You could also do it like this:

setTimeout(foo, 30000);

Whereea foo is a function.

Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.

A classic AJAX looks like this:

var fetch = true;
var url = 'someurl.java';
$.ajax(
{
    // Post the variable fetch to url.
    type : 'post',
    url : url,
    dataType : 'json', // expected returned data format.
    data : 
    {
        'fetch' : fetch // You might want to indicate what you're requesting.
    },
    success : function(data)
    {
        // This happens AFTER the backend has returned an JSON array (or other object type)
        var res1, res2;

        for(var i = 0; i < data.length; i++)
        {
            // Parse through the JSON array which was returned.
            // A proper error handling should be added here (check if
            // everything went successful or not)

            res1 = data[i].res1;
            res2 = data[i].res2;

            // Do something with the returned data
            $('#div1').html(res1);
        }
    },
    complete : function(data)
    {
        // do something, not critical.
    }
});

Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.

I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.

Add an index (numeric ID) column to large data frame

Well, if I understand you correctly. You can do something like the following.

To show it, I first create a data.frame with your example

df <- 
scan(what = character(), sep = ",", text =
"001, 34, 3, aa.com
002, 4, 4, aa.com
034, 3, 3, aa.com
001, 12, 4, bb.com
002, 1, 3, bb.com
034, 2, 2, cc.com")

df <- as.data.frame(matrix(df, 6, 4, byrow = TRUE))
colnames(df) <- c("user_id", "number_of_logins", "number_of_images", "web")  

You can then run one of the following lines to add a column (at the end of the data.frame) with the row number as the generated user id. The second lines simply adds leading zeros.

df$generated_uid  <- 1:nrow(df)
df$generated_uid2 <- sprintf("%03d", 1:nrow(df))

If you absolutely want the generated user id to be the first column, you can add the column like so:

df <- cbind("generated_uid3" = sprintf("%03d", 1:nrow(df)), df)

or simply rearrage the columns.

Looping through the content of a file in Bash

#!/bin/bash
#
# Change the file name from "test" to desired input file 
# (The comments in bash are prefixed with #'s)
for x in $(cat test.txt)
do
    echo $x
done

BigDecimal to string

For better support different locales use this way:

DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(0);
df.setGroupingUsed(false);

df.format(bigDecimal);

also you can customize it:

DecimalFormat df = new DecimalFormat("###,###,###");
df.format(bigDecimal);

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

I used the following two steps which I found in the comments/posts linked in the other answers:

Step one: Convert the x.509 cert and key to a pkcs12 file

openssl pkcs12 -export -in server.crt -inkey server.key \
               -out server.p12 -name [some-alias] \
               -CAfile ca.crt -caname root

Note: Make sure you put a password on the pkcs12 file - otherwise you'll get a null pointer exception when you try to import it. (In case anyone else had this headache). (Thanks jocull!)

Note 2: You might want to add the -chain option to preserve the full certificate chain. (Thanks Mafuba)

Step two: Convert the pkcs12 file to a Java keystore

keytool -importkeystore \
        -deststorepass [changeit] -destkeypass [changeit] -destkeystore server.keystore \
        -srckeystore server.p12 -srcstoretype PKCS12 -srcstorepass some-password \
        -alias [some-alias]

Finished

OPTIONAL Step zero: Create self-signed certificate

openssl genrsa -out server.key 2048
openssl req -new -out server.csr -key server.key
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Cheers!

How to receive serial data using android bluetooth

Take a look at incredible Bluetooth Serial class that has onResume() ability that helped me so much. I hope this helps ;)

@angular/material/index.d.ts' is not a module

Just update @angular/material from 7 to 9,

npm uninstall @angular/material --save

npm install @angular/material@^7.1.0 --save

ng update @angular/material

Just wait and see Angular doing the Migration alone,

Hope it helps someone :)

Find index of last occurrence of a substring in a string

You can use rfind() or rindex()
Python2 links: rfind() rindex()

>>> s = 'Hello StackOverflow Hi everybody'

>>> print( s.rfind('H') )
20

>>> print( s.rindex('H') )
20

>>> print( s.rfind('other') )
-1

>>> print( s.rindex('other') )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

The difference is when the substring is not found, rfind() returns -1 while rindex() raises an exception ValueError (Python2 link: ValueError).

If you do not want to check the rfind() return code -1, you may prefer rindex() that will provide an understandable error message. Else you may search for minutes where the unexpected value -1 is coming from within your code...


Example: Search of last newline character

>>> txt = '''first line
... second line
... third line'''

>>> txt.rfind('\n')
22

>>> txt.rindex('\n')
22

Maximum size of an Array in Javascript

No need to trim the array, simply address it as a circular buffer (index % maxlen). This will ensure it never goes over the limit (implementing a circular buffer means that once you get to the end you wrap around to the beginning again - not possible to overrun the end of the array).

For example:

var container = new Array ();
var maxlen = 100;
var index = 0;

// 'store' 1538 items (only the last 'maxlen' items are kept)
for (var i=0; i<1538; i++) {
   container [index++ % maxlen] = "storing" + i;
}

// get element at index 11 (you want the 11th item in the array)
eleventh = container [(index + 11) % maxlen];

// get element at index 11 (you want the 11th item in the array)
thirtyfifth = container [(index + 35) % maxlen];

// print out all 100 elements that we have left in the array, note
// that it doesn't matter if we address past 100 - circular buffer
// so we'll simply get back to the beginning if we do that.
for (i=0; i<200; i++) {
   document.write (container[(index + i) % maxlen] + "<br>\n");
}

Abstract Class:-Real Time Example

You should be able to cite at least one from the JDK itself. Look in the java.util.collections package. There are several abstract classes. You should fully understand interface, abstract, and concrete for Map and why Joshua Bloch wrote it that way.

How to get the number of columns in a matrix?

While size(A,2) is correct, I find it's much more readable to first define

rows = @(x) size(x,1); 
cols = @(x) size(x,2);

and then use, for example, like this:

howManyColumns_in_A = cols(A)
howManyRows_in_A    = rows(A)

It might appear as a small saving, but size(.., 1) and size(.., 2) must be some of the most commonly used functions, and they are not optimally readable as-is.

In git how is fetch different than pull and how is merge different than rebase?

Merge - HEAD branch will generate a new commit, preserving the ancestry of each commit history. History can become polluted if merge commits are made by multiple people who work on the same branch in parallel.

Rebase - Re-writes the changes of one branch onto another without creating a new commit. The code history is simplified, linear and readable but it doesn't work with pull requests, because you can't see what minor changes someone made.

I would use git merge when dealing with feature-based workflow or if I am not familiar with rebase. But, if I want a more a clean, linear history then git rebase is more appropriate. For more details be sure to check out this merge or rebase article.

How to center a WPF app on screen?

You don't need to reference the System.Windows.Forms assembly from your application. Instead, you can use System.Windows.SystemParameters.WorkArea. This is equivalent to the System.Windows.Forms.Screen.PrimaryScreen.WorkingArea!

How might I force a floating DIV to match the height of another floating DIV?

You should wrap them in a div with no float.

<div style="float:none;background:#FDD017;" class="clearfix">
    <div id="response" style="float:left; width:65%;">Response with two lines</div>
    <div id="note" style="float:left; width:35%;">single line note</div>
</div>

I also use the clearfix patch on here http://www.webtoolkit.info/css-clearfix.html

how to split the ng-repeat data with three columns using bootstrap

I fix without .row

<div class="col col-33 left" ng-repeat="photo in photos">
   Content here...
</div>

and css

.left {
  float: left;
}

How to subtract n days from current date in java?

for future use find day of the week ,deduct day and display the deducted day using date.

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

String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday",
        "Thursday", "Friday", "Saturday" };
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
Date dt1 = format1.parse("20/10/2013");

Calendar c = Calendar.getInstance();
c.setTime(dt1);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
long diff = Calendar.getInstance().getTime().getTime() ;
System.out.println(dayOfWeek);

switch (dayOfWeek) {

case 6:
    System.out.println(days[dayOfWeek - 1]);
    break;
case 5:

    System.out.println(days[dayOfWeek - 1]);
    break;      
case 4:
    System.out.println(days[dayOfWeek - 1]);
    break;
case 3:

    System.out.println(days[dayOfWeek - 1]);
    break;
case 2:
    System.out.println(days[dayOfWeek - 1]);
    break;
case 1:

    System.out.println(days[dayOfWeek - 1]);

     diff = diff -(dt1.getTime()- 3 );
     long valuebefore = dt1.getTime();
     long valueafetr = dt1.getTime()-2;
     System.out.println("DATE IS befor subtraction :"+valuebefore);
     System.out.println("DATE IS after subtraction :"+valueafetr);

     long x= dt1.getTime()-(2 * 24 * 3600 * 1000);
     System.out.println("Deducted date to find firday is - 2 days form Sunday :"+new Date((dt1.getTime()-(2*24*3600*1000))));
     System.out.println("DIffrence from now on is :"+diff);
        if(diff > 0) {

            diff = diff / (1000 * 60 * 60 * 24);
            System.out.println("Diff"+diff);
            System.out.println("Date is Expired!"+(dt1.getTime() -(long)2));
        }

    break;
}
}

Save bitmap to file function

  1. You need an appropriate permission in manifest.xml:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
  2. out.flush() check the out is not null..

  3. String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
                                "/PhysicsSketchpad";
    File dir = new File(file_path);
    if(!dir.exists())
        dir.mkdirs();
    File file = new File(dir, "sketchpad" + pad.t_id + ".png");
    FileOutputStream fOut = new FileOutputStream(file);
    
    bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
    fOut.flush();
    fOut.close();
    

Is it possible to save HTML page as PDF using JavaScript or jquery?

Ya its very easy to do with javascript. Hope this code is useful to you.

You'll need the JSpdf library.

<div id="content">
     <h3>Hello, this is a H3 tag</h3>

    <p>a pararaph</p>
</div>
<div id="editor"></div>
<button id="cmd">Generate PDF</button>

<script>
    var doc = new jsPDF();
    var specialElementHandlers = {
        '#editor': function (element, renderer) {
            return true;
        }
    };

    $('#cmd').click(function () {
        doc.fromHTML($('#content').html(), 15, 15, {
            'width': 170,
                'elementHandlers': specialElementHandlers
        });
        doc.save('sample-file.pdf');
    });

    // This code is collected but useful, click below to jsfiddle link.
</script>

jsfiddle link here

print variable and a string in python

Assuming you use Python 2.7 (not 3):

print "I have", card.price (as mentioned above).

print "I have %s" % card.price (using string formatting)

print " ".join(map(str, ["I have", card.price])) (by joining lists)

There are a lot of ways to do the same, actually. I would prefer the second one.

GitHub relative link in Markdown file

Just wanted to add this because none of the above solutions worked if target link is directory with spaces in it's name. If target link is a directory and it has space then even escaping space with \ doesn't render the link on Github. Only solution worked for me is using %20 for each space.

e.g.: if directory structure is this

Top_dir
|-----README.md
|-----Cur_dir1
      |----Dir A
           |----README.md
      |----Dir B
           |----README.md

To make link to Dir A in README.md present in Top_dir you can do this:

[Dir 1](Cur_dir1/Dir%20A)

SQL Server reports 'Invalid column name', but the column is present and the query works through management studio

Also happens when you forget to change the ConnectionString and ask a table that has no idea about the changes you're making locally.

Android SDK Manager Not Installing Components

To go along with what v01d said:

Using Android Studio for Mac OS X, the SDK folder could also be at /Users/{user}/Library/Android/sdk, where {user} is your username.

To find out where the partial SDK installation is, go to Configure > SDK Manager in Android Studio, then click edit at the top. This should pop up a window and show the location.

Copy this path and paste it front of the cd command in a terminal. Finally execute sudo ./android sdk to launch the standalone SDK manager.


EDIT (July 14, 2016):

The "android" binary file could also be at /Users/{user}/Library/Android/sdk/tools.

Center button under form in bootstrap

With Bootstrap 3, you can use the 'text-center' styling attribute.

<div class="col-md-3 text-center"> 
  <button id="button" name="button" class="btn btn-primary">Press Me!</button> 
</div>

Convert hex to binary

For solving the left-side trailing zero problem:


my_hexdata = "1a"

scale = 16 ## equals to hexadecimal

num_of_bits = 8

bin(int(my_hexdata, scale))[2:].zfill(num_of_bits)

It will give 00011010 instead of the trimmed version.

How to print struct variables in console?

fmt.Printf("%+v\n", project)

This is the basic way of printing the details

Postgresql -bash: psql: command not found

It can be due to psql not being in PATH

$ locate psql
/usr/lib/postgresql/9.6/bin/psql

Then create a link in /usr/bin

ln -s /usr/lib/postgresql/9.6/bin/psql /usr/bin/psql

Then try to execute psql it should work.

Functional style of Java 8's Optional.ifPresent and if-not-Present?

The described behavior can be achieved by using Vavr (formerly known as Javaslang), an object-functional library for Java 8+, that implements most of Scala constructs (being Scala a more expressive language with a way richer type system built on JVM). It is a very good library to add to your Java projects to write pure functional code.

Vavr provides the Option monad that provides functions to work with the Option type such as:

  • fold: to map the value of the option on both cases (defined/empty)
  • onEmpty: allows to execute a Runnable when option is empty
  • peek: allows to consume the value of the option (when defined).
  • and it is also Serializable on the contrary of Optional which means you can safely use it as method argument and instance member.

Option follows the monad laws at difference to the Java's Optional "pseudo-monad" and provides a richer API. And of course you can make it from a Java's Optional (and the other way around): Option.ofOptional(javaOptional) –Vavr is focused on interoperability.

Going to the example:

// AWESOME Vavr functional collections (immutable for the gread good :)
// fully convertible to Java's counterparts.
final Map<String, String> map = Map("key1", "value1", "key2", "value2");

final Option<String> opt = map.get("nonExistentKey"); // you're safe of null refs!
        
final String result = opt.fold(
        () -> "Not found!!!",                // Option is None
        val -> "Found the value: " + val     // Option is Some(val)
);

Moreover, all Vavr types are convertible to its Java counterparts, for the sake of the example: Optional javaOptional = opt.toJava(), very easy :) Of course the conversion also exists in the other way: Option option = Option.ofOptional(javaOptional).

N.B. Vavr offers a io.vavr.API class with a lot of convenient static methods =)

Further reading

Null reference, the billion dollar mistake

N.B. This is only a very little example of what Vavr offers (pattern matching, streams a.k.a. lazy evaluated lists, monadic types, immutable collections,...).

Android, How to limit width of TextView (and add three dots at the end of text)?

I am using Horizonal Recyclerview.
1) Here in CardView, TextView gets distorted vertically when using

android:ellipsize="end"
android:maxLines="1"

Check the bold TextViews Wyman Group, Jaskolski... enter image description here

2) But when I used singleLine along with ellipsize -

android:ellipsize="end"
android:singleLine="true"

Check the bold TextViews Wyman Group, Jaskolski... enter image description here

2nd solution worked for me properly (using singleLine). Also I have tested in OS version: 4.1 and above (till 8.0), it's working fine without any crashes.

How to use enums in C++

I think your root issue is the use of . instead of ::, which will use the namespace.

Try:

enum Days {Saturday, Sunday, Tuesday, Wednesday, Thursday, Friday};
Days day = Days::Saturday;
if(Days::Saturday == day)  // I like literals before variables :)
{
    std::cout<<"Ok its Saturday";
}

Creating a select box with a search option

Selectize Js has all options we require .Please Try It

_x000D_
_x000D_
  $(document).ready(function () {_x000D_
      $('select').selectize({_x000D_
          sortField: 'text'_x000D_
      });_x000D_
  });
_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.min.js" integrity="sha256-+C0A5Ilqmu4QcSPxrlGpaZxJ04VjsRjKu+G82kl5UJk=" crossorigin="anonymous"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.bootstrap3.min.css" integrity="sha256-ze/OEYGcFbPRmvCnrSeKbRTtjG4vGLHXgOqsyLFTRjg=" crossorigin="anonymous" />_x000D_
</head>_x000D_
<body>_x000D_
  <select id="select-state" placeholder="Pick a state...">_x000D_
    <option value="">Select a state...</option>_x000D_
    <option value="AL">Alabama</option>_x000D_
    <option value="AK">Alaska</option>_x000D_
    <option value="AZ">Arizona</option>_x000D_
    <option value="AR">Arkansas</option>_x000D_
    <option value="CA">California</option>_x000D_
    <option value="CO">Colorado</option>_x000D_
    <option value="CT">Connecticut</option>_x000D_
    <option value="DE">Delaware</option>_x000D_
    <option value="DC">District of Columbia</option>_x000D_
    <option value="FL">Florida</option>_x000D_
    <option value="GA">Georgia</option>_x000D_
    <option value="HI">Hawaii</option>_x000D_
    <option value="ID">Idaho</option>_x000D_
    <option value="IL">Illinois</option>_x000D_
    <option value="IN">Indiana</option>_x000D_
  </select>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Upload DOC or PDF using PHP

One of your conditions is failing. Check the value of mime-type for your files.
Try using application/pdf, not text/pdf. Refer to Proper MIME media type for PDF files

How can I select all rows with sqlalchemy?

I use the following snippet to view all the rows in a table. Use a query to find all the rows. The returned objects are the class instances. They can be used to view/edit the values as required:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Sequence
from sqlalchemy import String, Integer, Float, Boolean, Column
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'MyTable'
    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    some_col = Column(String(500))

    def __init__(self, some_col):
        self.some_col = some_col

engine = create_engine('sqlite:///sqllight.db', echo=True)
Session = sessionmaker(bind=engine)
session = Session()

for class_instance in session.query(MyTable).all():
    print(vars(class_instance))

session.close()

How to check if a file contains a specific string using Bash

grep -q "something" file
[[ !? -eq 0 ]] && echo "yes" || echo "no"

The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM'

THE ANSWER: The problem was all of the posts for such an issue were related to older kerberos and IIS issues where proxy credentials or AllowNTLM properties were helping. My case was different. What I have discovered after hours of picking worms from the ground was that somewhat IIS installation did not include Negotiate provider under IIS Windows authentication providers list. So I had to add it and move up. My WCF service started to authenticate as expected. Here is the screenshot how it should look if you are using Windows authentication with Anonymous auth OFF.

You need to right click on Windows authentication and choose providers menu item.

enter image description here

Hope this helps to save some time.

Powershell folder size of folders without listing Subdirectories

Interesting how powerful yet how helpless PS can be in the same time, coming from a Nix learning PS. after install crgwin/gitbash, you can do any combination in one commands:

size of current folder: du -sk .

size of all files and folders under current directory du -sk *

size of all subfolders (including current folders) find ./ -type d -exec du -sk {} \;

Detect if user is scrolling

If you want detect when user scroll over certain div, you can do something like this:

window.onscroll = function() {
    var distanceScrolled = document.documentElement.scrollTop;
    console.log('Scrolled: ' + distanceScrolled);
}

For example, if your div appear after scroll until the position 112:

window.onscroll = function() {
    var distanceScrolled = document.documentElement.scrollTop;
    if (distanceScrolled > 112) {
      do something...
    }
}

But as you can see you don't need a div, just the offset distance you want something to happen.

Check if instance is of a type

Try the following

if (c is TForm) { 
 ...
}

How to negate a method reference predicate

Building on other's answers and personal experience:

Predicate<String> blank = String::isEmpty;
content.stream()
       .filter(blank.negate())

How to find all duplicate from a List<string>?

I'm assuming each string in your list contains several words, let me know if that's incorrect.

List<string> list = File.RealAllLines("foobar.txt").ToList();

var words = from line in list
            from word in line.Split(new[] { ' ', ';', ',', '.', ':', '(', ')' }, StringSplitOptions.RemoveEmptyEntries)
            select word;

var duplicateWords = from w in words
                     group w by w.ToLower() into g
                     where g.Count() > 1
                     select new
                     {
                         Word = g.Key,
                         Count = g.Count()
                     }

What is an attribute in Java?

Attributes is same term used alternativly for properties or fields or data members or class members.

Bootstrap 4 Change Hamburger Toggler Color

One simplest way to encounter this is to use font awesome for example

 <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
       <span><i class="fas fa-bars"></i></span>
</button>

Then u can change the i element like you change any other ielement.

Invalid length for a Base-64 char array

The encrypted string had two special characters, + and =.

'+' sign was giving the error, so below solution worked well:

//replace + sign

encryted_string = encryted_string.Replace("+", "%2b");

//`%2b` is HTTP encoded string for **+** sign

OR

//encode special charactes 

encryted_string = HttpUtility.UrlEncode(encryted_string);

//then pass it to the decryption process
...

JQuery: if div is visible

You can use .is(':visible')

Selects all elements that are visible.

For example:

if($('#selectDiv').is(':visible')){

Also, you can get the div which is visible by:

$('div:visible').callYourFunction();

Live example:

_x000D_
_x000D_
console.log($('#selectDiv').is(':visible'));_x000D_
console.log($('#visibleDiv').is(':visible'));
_x000D_
#selectDiv {_x000D_
  display: none;  _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>
_x000D_
_x000D_
_x000D_

Simple way to read single record from MySQL

$results = $mysqli->query("SELECT product_code, product_name, product_desc, product_img_name, price FROM products WHERE id = 1");

How to INNER JOIN 3 tables using CodeIgniter

function fetch_comments($ticket_id){
    $this->db->select('tbl_tickets_replies.comments, 
           tbl_users.username,tbl_roles.role_name');
    $this->db->where('tbl_tickets_replies.ticket_id',$ticket_id);
    $this->db->join('tbl_users','tbl_users.id = tbl_tickets_replies.user_id');
    $this->db->join('tbl_roles','tbl_roles.role_id=tbl_tickets_replies.role_id');
    return $this->db->get('tbl_tickets_replies');
}

Print the stack trace of an exception

Throwable.printStackTrace(..) can take a PrintWriter or PrintStream argument:

} catch (Exception ex) {
    ex.printStackTrace(new java.io.PrintStream(yourOutputStream));
}

That said, consider using a logger interface like SLF4J with an logging implementation like LOGBack or log4j.

Count occurrences of a char in a string using Bash

awk works well if you your server has it

var="text,text,text,text" 
num=$(echo "${var}" | awk -F, '{print NF-1}')
echo "${num}"

Colorplot of 2D array matplotlib

Here is the simplest example that has the key lines of code:

import numpy as np 
import matplotlib.pyplot as plt

H = np.array([[1, 2, 3, 4],
          [5, 6, 7, 8],
          [9, 10, 11, 12],
          [13, 14, 15, 16]])

plt.imshow(H, interpolation='none')
plt.show()

enter image description here

Vertically align text next to an image?

Using flex property in css.

To align text vertically center by using in flex using align-items:center; if you want to align text horizontally center by using in flex using justify-content:center;.

_x000D_
_x000D_
div{
  display: flex;
  align-items: center;
}
_x000D_
<div>
  <img src="http://lorempixel.com/30/30/" alt="small img" />
  <span>It works.</span>
</div>
_x000D_
_x000D_
_x000D_

Using table-cell in css.

_x000D_
_x000D_
div{
  display: table;
}
div *{
  display: table-cell;
  vertical-align: middle;
}
_x000D_
<div>
  <img src="http://lorempixel.com/30/30/" alt="small img" />
  <span>It works.</span>
</div>
_x000D_
_x000D_
_x000D_

Unable to run 'adb root' on a rooted Android phone

I finally found out how to do this! Basically you need to run adb shell first and then while you're in the shell run su, which will switch the shell to run as root!

$: adb shell
$: su

The one problem I still have is that sqlite3 is not installed so the command is not recognized.

Wordpress plugin install: Could not create directory

CentOS7 or Ubuntu 16


1.

WordPress uses ftp to install themes and plugins.
So the ftpd should have been configured to create-directory

vim /etc/pure-ftpd.confg

and if it is no then should be yes

# Are anonymous users allowed to create new directories?
AnonymousCanCreateDirs       yes

lastly

sudo systemctl restart pure-ftpd

2.

Maybe there is an ownership issue with the parent directories. Find the Web Server user name and group name if it is Apache Web Server

apachectl -S

it will print

...
...
User: name="apache" id=997
Group: name="apache" id=1000

on Ubuntu it is

User: name="www-data" id=33 not_used
Group: name="www-data" id=33 not_used

then

sudo chown -R apache:apache directory-name

3.

Sometimes it is because of directories permissions. So try

sudo chmod -R 755 directory-name

in some cases 755 does not work. (It should & I do not no why) so try

sudo chmod -R 777 directory-name

4.

Maybe it is because of php safe mode. So turn it off in the root of your domain

vim php.ini

then add

safe_mode = Off

NOTE:
For not entering FTP username and password each time installing a theme we can configure WordPress to use it directly by adding

define('FS_METHOD','direct');

to the wp-config.php file.

How to escape regular expression special characters using javascript?

Use the \ character to escape a character that has special meaning inside a regular expression.

To automate it, you could use this:

function escapeRegExp(text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}

Update: There is now a proposal to standardize this method, possibly in ES2016: https://github.com/benjamingr/RegExp.escape

Update: The abovementioned proposal was rejected, so keep implementing this yourself if you need it.

How to connect Android app to MySQL database?

Yes you can connect your android app to your PHP to grab results from your database. Use a webservice to connect to your backend script via ASYNC task and http post requests. Check this link for more information Connecting to MySQL

DB2 Query to retrieve all table names for a given schema

SELECT
  name
FROM
  SYSIBM.SYSTABLES
WHERE
    type = 'T'
  AND
    creator = 'MySchema'
  AND
    name LIKE 'book_%';

How to properly use unit-testing's assertRaises() with NoneType objects?

Complete snippet would look like the following. It expands @mouad's answer to asserting on error's message (or generally str representation of its args), which may be useful.

from unittest import TestCase


class TestNoneTypeError(TestCase):

  def setUp(self): 
    self.testListNone = None

  def testListSlicing(self):
    with self.assertRaises(TypeError) as ctx:
        self.testListNone[:1]
    self.assertEqual("'NoneType' object is not subscriptable", str(ctx.exception))

How to determine the current language of a wordpress page when using polylang?

<?php
                    $currentpage = $_SERVER['REQUEST_URI'];
                    $eep=explode('/',$currentpage);
                    $ln=$eep[1];
                    if (in_array("en", $eep))
                    {
                        $lan='en';
                    }
                    if (in_array("es", $eep))
                    {
                        $lan='es';
                    }
                ?>

When to use reinterpret_cast?

Here is a variant of Avi Ginsburg's program which clearly illustrates the property of reinterpret_cast mentioned by Chris Luengo, flodin, and cmdLP: that the compiler treats the pointed-to memory location as if it were an object of the new type:

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

class A
{
public:
    int i;
};

class B : public A
{
public:
    virtual void f() {}
};

int main()
{
    string s;
    B b;
    b.i = 0;
    A* as = static_cast<A*>(&b);
    A* ar = reinterpret_cast<A*>(&b);
    B* c = reinterpret_cast<B*>(ar);
    
    cout << "as->i = " << hex << setfill('0')  << as->i << "\n";
    cout << "ar->i = " << ar->i << "\n";
    cout << "b.i   = " << b.i << "\n";
    cout << "c->i  = " << c->i << "\n";
    cout << "\n";
    cout << "&(as->i) = " << &(as->i) << "\n";
    cout << "&(ar->i) = " << &(ar->i) << "\n";
    cout << "&(b.i) = " << &(b.i) << "\n";
    cout << "&(c->i) = " << &(c->i) << "\n";
    cout << "\n";
    cout << "&b = " << &b << "\n";
    cout << "as = " << as << "\n";
    cout << "ar = " << ar << "\n";
    cout << "c  = " << c  << "\n";
    
    cout << "Press ENTER to exit.\n";
    getline(cin,s);
}

Which results in output like this:

as->i = 0
ar->i = 50ee64
b.i   = 0
c->i  = 0

&(as->i) = 00EFF978
&(ar->i) = 00EFF974
&(b.i)   = 00EFF978
&(c->i)  = 00EFF978

&b = 00EFF974
as = 00EFF978
ar = 00EFF974
c  = 00EFF974
Press ENTER to exit.

It can be seen that the B object is built in memory as B-specific data first, followed by the embedded A object. The static_cast correctly returns the address of the embedded A object, and the pointer created by static_cast correctly gives the value of the data field. The pointer generated by reinterpret_cast treats b's memory location as if it were a plain A object, and so when the pointer tries to get the data field it returns some B-specific data as if it were the contents of this field.

One use of reinterpret_cast is to convert a pointer to an unsigned integer (when pointers and unsigned integers are the same size):

int i; unsigned int u = reinterpret_cast<unsigned int>(&i);

Convert String into a Class Object

As stated by others, your question is ambiguous at best. The problem is, you want to represent the object as a string, and then be able to construct the object again from that string.

However, note that while many object types in Java have string representations, this does not guarantee that an object can be constructed from its string representation.

To quote this source,

Object serialization is the process of saving an object's state to a sequence of bytes, as well as the process of rebuilding those bytes into a live object at some future time.

So, you see, what you want might not be possible. But it is possible to save your object's state to a byte sequence, and then reconstruct it from that byte sequence.

Make cross-domain ajax JSONP request with jQuery

Concept explained

Are you trying do a cross-domain AJAX call? Meaning, your service is not hosted in your same web application path? Your web-service must support method injection in order to do JSONP.

Your code seems fine and it should work if your web services and your web application hosted in the same domain.

When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.

For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do then jQuery will add ?callback={some_random_dynamically_generated_method}.

This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:

window.some_random_dynamically_generated_method = function(actualJsonpData) {
    //here actually has reference to the success function mentioned with $.ajax
    //so it just calls the success method like this: 
    successCallback(actualJsonData);
}

Summary

Your client code seems just fine. However, you have to modify your server-code to wrap your JSON data with a function name that passed with query string. i.e.

If you have reqested with query string

?callback=my_callback_method

then, your server must response data wrapped like this:

my_callback_method({your json serialized data});

What are the complexity guarantees of the standard containers?

I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).

Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.

Also the STL library reference at http://www.cplusplus.com/reference/stl/ provides the complexity requirements where appropriate.

How to normalize an array in NumPy to a unit vector?

You mentioned sci-kit learn, so I want to share another solution.

sci-kit learn MinMaxScaler

In sci-kit learn, there is a API called MinMaxScaler which can customize the the value range as you like.

It also deal with NaN issues for us.

NaNs are treated as missing values: disregarded in fit, and maintained in transform. ... see reference [1]

Code sample

The code is simple, just type

# Let's say X_train is your input dataframe
from sklearn.preprocessing import MinMaxScaler
# call MinMaxScaler object
min_max_scaler = MinMaxScaler()
# feed in a numpy array
X_train_norm = min_max_scaler.fit_transform(X_train.values)
# wrap it up if you need a dataframe
df = pd.DataFrame(X_train_norm)
Reference

how to exit a python script in an if statement

This works fine for me:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")
      exit()

edit: use input in python 3.2 instead of raw_input

How to get the date from the DatePicker widget in Android?

I manged to set the MinDate & the MaxDate programmatically like this :

    final Calendar c = Calendar.getInstance();

    int maxYear = c.get(Calendar.YEAR) - 20; // this year ( 2011 ) - 20 = 1991
    int maxMonth = c.get(Calendar.MONTH);
    int maxDay = c.get(Calendar.DAY_OF_MONTH);

    int minYear = 1960;
    int minMonth = 0; // january
    int minDay = 25;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_account);
        BirthDateDP = (DatePicker) findViewById(R.id.create_account_BirthDate_DatePicker);
        BirthDateDP.init(maxYear - 10, maxMonth, maxDay, new OnDateChangedListener()
        {

        @Override
        public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
        {
            if (year < minYear)
                view.updateDate(minYear, minMonth, minDay);

                if (monthOfYear < minMonth && year == minYear)
                view.updateDate(minYear, minMonth, minDay);

                if (dayOfMonth < minDay && year == minYear && monthOfYear == minMonth)
                view.updateDate(minYear, minMonth, minDay);


                if (year > maxYear)
                view.updateDate(maxYear, maxMonth, maxDay);

                if (monthOfYear > maxMonth && year == maxYear)
                view.updateDate(maxYear, maxMonth, maxDay);

                if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
                view.updateDate(maxYear, maxMonth, maxDay);
        }}); // BirthDateDP.init()
    } // activity

it works fine for me, enjoy :)

Java JDBC - How to connect to Oracle using Service Name instead of SID

You can also specify the TNS name in the JDBC URL as below

jdbc:oracle:thin:@(DESCRIPTION =(ADDRESS_LIST =(ADDRESS =(PROTOCOL=TCP)(HOST=blah.example.com)(PORT=1521)))(CONNECT_DATA=(SID=BLAHSID)(GLOBAL_NAME=BLAHSID.WORLD)(SERVER=DEDICATED)))

How do I set the background color of my main screen in Flutter?

and it's another approach to change the color of background:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: Scaffold(backgroundColor: Colors.pink,),);
  }
}

How do I determine the size of my array in C?

For multidimensional arrays it is a tad more complicated. Oftenly people define explicit macro constants, i.e.

#define g_rgDialogRows   2
#define g_rgDialogCols   7

static char const* g_rgDialog[g_rgDialogRows][g_rgDialogCols] =
{
    { " ",  " ",    " ",    " 494", " 210", " Generic Sample Dialog", " " },
    { " 1", " 330", " 174", " 88",  " ",    " OK",        " " },
};

But these constants can be evaluated at compile-time too with sizeof:

#define rows_of_array(name)       \
    (sizeof(name   ) / sizeof(name[0][0]) / columns_of_array(name))
#define columns_of_array(name)    \
    (sizeof(name[0]) / sizeof(name[0][0]))

static char* g_rgDialog[][7] = { /* ... */ };

assert(   rows_of_array(g_rgDialog) == 2);
assert(columns_of_array(g_rgDialog) == 7);

Note that this code works in C and C++. For arrays with more than two dimensions use

sizeof(name[0][0][0])
sizeof(name[0][0][0][0])

etc., ad infinitum.

How to add conditional attribute in Angular 2?

null removes it:

[attr.checked]="value ? '' : null"

or

[attr.checked]="value ? 'checked' : null"

Hint:

Attribute vs property

When the HTML element where you add this binding does not have a property with the name used in the binding (checked in this case) and also no Angular component or directive is applied to the same element that has an @Input() checked;, then [xxx]="..." can not be used.

See also What is the difference between properties and attributes in HTML?

What to bind to when there is no such property

Alternatives are [style.xxx]="...", [attr.xxx]="...", [class.xxx]="..." depending on what you try to accomplish.

Because <input> only has a checked attribute, but no checked property [attr.checked]="..." is the right way for this specific case.

Attributes can only handle string values

A common pitfall is also that for [attr.xxx]="..." bindings the value (...) is always stringified. Only properties and @Input()s can receive other value types like boolean, number, object, ...

Most properties and attributes of elements are connected and have the same name.

Property-attribute connection

When bound to the attribute the property also only receives the stringified value from the attribute.
When bound to the property the property receives the value bound to it (boolean, number, object, ...) and the attribute again the stringified value.

Two cases where attribute and property names do not match.

Angular was changed since then and knows about these special cases and handles them so that you can bind to <label [for]=" even though no such property exists (same for colspan)

How to use jQuery Plugin with Angular 4?

You can update your jquery typings version like so

npm install --save @types/jquery@latest

I had this same error and I've been at if for 5 days surfing the net for a solution.it worked for me and it should work for you

redirect COPY of stdout to log file from within bash script itself

Neither of these is a perfect solution, but here are a couple things you could try:

exec >foo.log
tail -f foo.log &
# rest of your script

or

PIPE=tmp.fifo
mkfifo $PIPE
exec >$PIPE
tee foo.log <$PIPE &
# rest of your script
rm $PIPE

The second one would leave a pipe file sitting around if something goes wrong with your script, which may or may not be a problem (i.e. maybe you could rm it in the parent shell afterwards).

Peak memory usage of a linux/unix process

If the process runs for at least a couple seconds, then you can use the following bash script, which will run the given command line then print to stderr the peak RSS (substitute for rss any other attribute you're interested in). It's somewhat lightweight, and it works for me with the ps included in Ubuntu 9.04 (which I can't say for time).

#!/usr/bin/env bash
"$@" & # Run the given command line in the background.
pid=$! peak=0
while true; do
  sleep 1
  sample="$(ps -o rss= $pid 2> /dev/null)" || break
  let peak='sample > peak ? sample : peak'
done
echo "Peak: $peak" 1>&2

how to use "tab space" while writing in text file

use \t instead of space.

bw.write("\t"); 

Can't import database through phpmyadmin file size too large

If you do not want to change the settings or play with command line. There is option to compress the file and upload in phpMyAdmin. It should bring down the size considerably.

getting the screen density programmatically in android?

The following answer is a small improvement based upon qwertzguy's answer.

double density = getResources().getDisplayMetrics().density;
if (density >= 4.0) {
   //"xxxhdpi";
}
else if (density >= 3.0 && density < 4.0) {
   //xxhdpi
}
else if (density >= 2.0) {
   //xhdpi
}
else if (density >= 1.5 && density < 2.0) {
   //hdpi
}
else if (density >= 1.0 && density < 1.5) {
   //mdpi
}

How can I center a div within another div?

If you set width: auto to a block element, then the width would be 100%. So it really doesn't make much sense to have the auto value here. It is really the same for height, because by default any element is set to an automatic height.

So finally your div#container is actually centered, but it just occupies the whole width of its parent element. You do the centering right, and you need just to change the width (if needed) to see that it is really centered. If you want to center your #main_content then just apply margin: 0 auto; on it.

Python NameError: name is not defined

You must define the class before creating an instance of the class. Move the invocation of Something to the end of the script.

You can try to put the cart before the horse and invoke procedures before they are defined, but it will be an ugly hack and you will have to roll your own as defined here:

Make function definition in a python file order independent

Python how to plot graph sine wave

import matplotlib.pyplot as plt # For ploting
import numpy as np # to work with numerical data efficiently

fs = 100 # sample rate 
f = 2 # the frequency of the signal

x = np.arange(fs) # the points on the x axis for plotting
# compute the value (amplitude) of the sin wave at the for each sample
y = np.sin(2*np.pi*f * (x/fs)) 

#this instruction can only be used with IPython Notbook. 
% matplotlib inline
# showing the exact location of the smaples
plt.stem(x,y, 'r', )
plt.plot(x,y)

enter image description here

MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

Alternatively, you can use Inner Queries to do so.

SQL> INSERT INTO <NEW_TABLE> SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM <OLD_TABLE>);

Hope this helps!

Get the Query Executed in Laravel 3/4

Last query print

$queries = \DB::getQueryLog();
$last_query = end($queries);

// Add binding to query
foreach ($last_query['bindings'] as $val) {
        $last_query['query'] = preg_replace('/\?/', "'{$val}'", $last_query['query'], 1);
}
dd($last_query);

Best way to split string into lines

You could use Regex.Split:

string[] tokens = Regex.Split(input, @"\r?\n|\r");

Edit: added |\r to account for (older) Mac line terminators.

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

You can solve your problem with help of Attribute routing

Controller

[Route("api/category/{categoryId}")]
public IEnumerable<Order> GetCategoryId(int categoryId) { ... }

URI in jquery

api/category/1

Route Configuration

using System.Web.Http;

namespace WebApplication
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

            // Other Web API configuration not shown.
        }
    }
}

and your default routing is working as default convention-based routing

Controller

public string Get(int id)
    {
        return "object of id id";
    }   

URI in Jquery

/api/records/1 

Route Configuration

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

        // Convention-based routing.
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Review article for more information Attribute routing and onvention-based routing here & this

How to detect my browser version and operating system using JavaScript?

Try this one..

// Browser with version  Detection
navigator.sayswho= (function(){
    var N= navigator.appName, ua= navigator.userAgent, tem;
    var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
    if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
    M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
    return M;
})();

var browser_version          = navigator.sayswho;
alert("Welcome to " + browser_version);

check out the working fiddle ( here )

"CAUTION: provisional headers are shown" in Chrome debugger

Another possible scenario I've seen - the exact same request is being sent again just after few milliseconds (most likely due to a bug in the client side).
In that case you'll also see that the status of the first request is "canceled" and that the latency is only several milliseconds.

How do I set the selenium webdriver get timeout?

Try this:

 driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

How do I change the hover over color for a hover over table in Bootstrap?

Instead of changing the default table-hover class, make a new class ( anotherhover ) and apply it to the table that you need this effect for.

Code as below;

.anotherhover tbody tr:hover td { background: CornflowerBlue; }

IE 8: background-size fix

Also i have found another useful link. It is a background hack used like this

.selector { background-size: cover; -ms-behavior: url(/backgroundsize.min.htc); }

https://github.com/louisremi/background-size-polyfill

Matlab: Running an m-file from command-line

Since R2019b, there is a new command line option, -batch. It replaces -r, which is no longer recommended. It also unifies the syntax across platforms. See for example the documentation for Windows, for the other platforms the description is identical.

matlab -batch "statement to run"

This starts MATLAB without the desktop or splash screen, logs all output to stdout and stderr, exits automatically when the statement completes, and provides an exit code reporting success or error.

It is thus no longer necessary to use try/catch around the code to run, and it is no longer necessary to add an exit statement.

How to solve the memory error in Python

Assuming your example text is representative of all the text, one line would consume about 75 bytes on my machine:

In [3]: sys.getsizeof('usedfor zipper fasten_coat')
Out[3]: 75

Doing some rough math:

75 bytes * 8,000,000 lines / 1024 / 1024 = ~572 MB

So roughly 572 meg to store the strings alone for one of these files. Once you start adding in additional, similarly structured and sized files, you'll quickly approach your virtual address space limits, as mentioned in @ShadowRanger's answer.

If upgrading your python isn't feasible for you, or if it only kicks the can down the road (you have finite physical memory after all), you really have two options: write your results to temporary files in-between loading in and reading the input files, or write your results to a database. Since you need to further post-process the strings after aggregating them, writing to a database would be the superior approach.

JBoss vs Tomcat again

I have also read that for some servers one for example needs only annotate persistence contexts, but in some servers, the injection should be done manually.

Android, How to read QR code in my application?

Use a QR library like ZXing... I had very good experience with it, QrDroid is much buggier. If you must rely on an external reader, rely on a standard one like Google Goggles!

Error when trying to access XAMPP from a network

This solution worked well for me: http://www.apachefriends.org/f/viewtopic.php?f=17&t=50902&p=196185#p196185

Edit /opt/lampp/etc/extra/httpd-xampp.conf and adding Require all granted line at bottom of block <Directory "/opt/lampp/phpmyadmin"> to have the following code:

<Directory "/opt/lampp/phpmyadmin">
  AllowOverride AuthConfig Limit
  Order allow,deny
  Allow from all
  Require all granted
</Directory>

Simple dictionary in C++

A table out of char array:

char map[256] = { 0 };
map['T'] = 'A'; 
map['A'] = 'T';
map['C'] = 'G';
map['G'] = 'C';
/* .... */

How to check SQL Server version

Following are possible ways to see the version:

Method 1: Connect to the instance of SQL Server, and then run the following query:

Select @@version

An example of the output of this query is as follows:

Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64)   Mar 29 2009 
10:11:52   Copyright (c) 1988-2008 Microsoft Corporation  Express 
Edition (64-bit) on Windows NT 6.1 <X64> (Build 7600: )

Method 2: Connect to the server by using Object Explorer in SQL Server Management Studio. After Object Explorer is connected, it will show the version information in parentheses, together with the user name that is used to connect to the specific instance of SQL Server.

Method 3: Look at the first few lines of the Errorlog file for that instance. By default, the error log is located at Program Files\Microsoft SQL Server\MSSQL.n\MSSQL\LOG\ERRORLOG and ERRORLOG.n files. The entries may resemble the following:

2011-03-27 22:31:33.50 Server      Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64)                 Mar 29 2009 10:11:52                 Copyright (c) 1988-2008 Microsoft Corporation                Express Edition (64-bit) on Windows NT 6.1 <X64> (Build 7600: )

As you can see, this entry gives all the necessary information about the product, such as version, product level, 64-bit versus 32-bit, the edition of SQL Server, and the OS version on which SQL Server is running.

Method 4: Connect to the instance of SQL Server, and then run the following query:

SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')

Note This query works with any instance of SQL Server 2000 or of a later version

Oracle PL/SQL : remove "space characters" from a string

select regexp_replace('This is a test   ' || chr(9) || ' foo ', '[[:space:]]', '') from dual;

REGEXP_REPLACE
--------------
Thisisatestfoo

SQL UPDATE with sub-query that references the same table in MySQL

UPDATE user_account student

SET (student.student_education_facility_id) = (

   SELECT teacher.education_facility_id

   FROM user_account teacher

   WHERE teacher.user_account_id = student.teacher_id AND teacher.user_type = 'ROLE_TEACHER'

)

WHERE student.user_type = 'ROLE_STUDENT';

How to start new line with space for next line in Html.fromHtml for text view in android

Enclose your text in
--Here-- with the space you want in new line. save it in a String variable then pass it in Html.fromHtml().

Bash loop ping successful

Here's my one-liner solution:

screen -S internet-check -d -m -- bash -c 'while ! ping -c 1 google.com; do echo -; done; echo Google responding to ping | mail -s internet-back [email protected]'

This runs an infinite ping in a new screen session until there is a response, at which point it sends an e-mail to [email protected]. Useful in the age of e-mail sent to phones.

(You might want to check that mail is configured correctly by just running echo test | mail -s test [email protected] first. Of course you can do whatever you want from done; onwards, sound a bell, start a web browser, use your imagination.)

What is the incentive for curl to release the library for free?

I'm Daniel Stenberg.

I made curl

I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.

I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.

Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.

Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.

Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.

At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.

Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.

Why do I still work on curl?

Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?

  1. I can't speak for my fellow project team members. We all participate in this for our own reasons.
  2. I think it's still the right thing to do. I'm proud of what we've accomplished and I truly want to make the world a better place and I think curl does its little part in this.
  3. There are still bugs to fix and features to add!
  4. curl is free but my time is not. I still have a job and someone still has to pay someone for me to get paid every month so that I can put food on the table for my family. I charge customers and companies to help them with curl. You too can get my help for a fee, which then indirectly helps making sure that curl continues to evolve, remain free and the kick-ass product it is.
  5. curl was my spare time project for twenty years before I started working with it full time. I've had great jobs and worked on awesome projects. I've been in a position of luxury where I could continue to work on curl on my spare time and keep shipping a quality product for free. My work on curl has given me friends, boosted my career and taken me to places I would not have been at otherwise.
  6. I would not do it differently if I could back and do it again.

Am I proud of what we've done?

Yes. So insanely much.

But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.

We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.

Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.

For real?

Yeah. For real.

Do I ever get tired? Is it ever done?

Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.

But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.

curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.

How to POST a FORM from HTML to ASPX page

The Request.Form.Keys collection will be empty if none of your html inputs have NAMEs. It's easy to forget to put them there after you've been doing .NET for a while. Just name them and you'll be good to go.

Most Useful Attributes

It's not well-named, not well-supported in the framework, and shouldn't require a parameter, but this attribute is a useful marker for immutable classes:

[ImmutableObject(true)]

TypeError: 'float' object not iterable

for i in count: means for i in 7:, which won't work. The bit after the in should be of an iterable type, not a number. Try this:

for i in range(count):

How do I record audio on iPhone with AVAudioRecorder?

In the following link you can find useful info about recording with AVAudioRecording. In this link in the first part "USing Audio" there is an anchor named “Recording with the AVAudioRecorder Class.” that leads you to the example.

AudioVideo Conceptual MultimediaPG

How to get first and last element in an array in java?

This is the given array.

    int myIntegerNumbers[] = {1,2,3,4,5,6,7,8,9,10};

// If you want print the last element in the array.

    int lastNumerOfArray= myIntegerNumbers[9];
    Log.i("MyTag", lastNumerOfArray + "");

// If you want to print the number of element in the array.

    Log.i("MyTag", "The number of elements inside" +
            "the array " +myIntegerNumbers.length);

// Second method to print the last element inside the array.

    Log.i("MyTag", "The last elements inside " +
            "the array " + myIntegerNumbers[myIntegerNumbers.length-1]);

Dark color scheme for Eclipse

I've created several color themes, and a script to extract a new one from someone's color preferences. I'm currently using one I still have yet to post on the site, but I should eventually get to it.

http://eclipsecolorthemes.jottit.com

Type definition in object literal in TypeScript

In TypeScript if we are declaring object then we'd use the following syntax:

[access modifier] variable name : { /* structure of object */ }

For example:

private Object:{ Key1: string, Key2: number }

Good tool for testing socket connections?

Try Wireshark or WebScarab second is better for interpolating data into the exchange (not sure Wireshark even can). Anyway, one of them should be able to help you out.

How to remove an appended element with Jquery and why bind or live is causing elements to repeat

I would do something like:

$(documento).on('click', '#answer', function() {
  feedback('hey there');
});

Android: Difference between Parcelable and Serializable?

Parcelable is sort of a standard in Android development. But not because of speed

Parcelable is recommended approach for data transfers. But if you use serializable correctly as shown in this repo, you will see that serializable is sometimes even faster then parcelable. Or at least timings are comparable.

Is Parcelable faster then Serializable?

No, if serialization is done right.

Usual Java serialization on an average Android device (if done right *) is about 3.6 times faster than Parcelable for writes and about 1.6 times faster for reads. Also it proves that Java Serialization (if done right) is fast storage mechanism that gives acceptable results even with relatively large object graphs of 11000 objects with 10 fields each.

* The sidenote is that usually everybody who blindly states that "Parcelable is mush faster" compares it to default automatic serialization, which uses much reflection inside. This is unfair comparison, because Parcelable uses manual (and very complicated) procedure of writing data to the stream. What is usually not mentioned is that standard Java Serializable according to the docs can also be done in a manual way, using writeObject() and readObject() methods. For more info see JavaDocs. This is how it should be done for the best performance.

So, if serializable is faster and easier to implement, why android has parcelable at all?

The reason is native code. Parcelable is created not just for interprocess communication. It also can be used for intercode communication. You can send and recieve objects from C++ native layer. That's it.

What should you choose? Both will work good. But I think that Parcelable is better choice since it is recommended by google and as you can see from this thread is much more appreciated.

How do you append rows to a table using jQuery?

Maybe this is the answer you are looking for. It finds the last instance of <tr /> and appends the new row after it:

<script type="text/javascript">
    $('a').click(function() {
        $('#myTable tr:last').after('<tr class="child"><td>blahblah<\/td></tr>');
    });
</script>

Format Date time in AngularJS

you can get the 'date' filter like this:

var today = $filter('date')(new Date(),'yyyy-MM-dd HH:mm:ss Z');

This will give you today's date in format you want.

What are the differences between Visual Studio Code and Visual Studio?

One huge difference (for me) is that Visual Studio Code is one monitor only. With Visual Studio you can use multi-screen setups.

Best Practice: Initialize JUnit class fields in setUp() or at declaration?

If you're wondering specifically about the examples in the JUnit FAQ, such as the basic test template, I think the best practice being shown off there is that the class under test should be instantiated in your setUp method (or in a test method).

When the JUnit examples create an ArrayList in the setUp method, they all go on to test the behavior of that ArrayList, with cases like testIndexOutOfBoundException, testEmptyCollection, and the like. The perspective there is of someone writing a class and making sure it works right.

You should probably do the same when testing your own classes: create your object in setUp or in a test method, so that you'll be able to get reasonable output if you break it later.

On the other hand, if you use a Java collection class (or other library class, for that matter) in your test code, it's probably not because you want to test it--it's just part of the test fixture. In this case, you can safely assume it works as intended, so initializing it in the declaration won't be a problem.

For what it's worth, I work on a reasonably large, several-year-old, TDD-developed code base. We habitually initialize things in their declarations in test code, and in the year and a half that I've been on this project, it has never caused a problem. So there's at least some anecdotal evidence that it's a reasonable thing to do.

How to set .net Framework 4.5 version in IIS 7 application pool

Go to "Run" and execute this:

%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir

NOTE: run as administrator.

Calling stored procedure with return value

This is a very short sample of returning a single value from a procedure:

SQL:

CREATE PROCEDURE [dbo].[MakeDouble] @InpVal int AS BEGIN 
SELECT @InpVal * 2; RETURN 0; 
END

C#-code:

int inpVal = 11;
string retVal = "?";
using (var sqlCon = new SqlConnection(
    "Data Source = . ; Initial Catalog = SampleDb; Integrated Security = True;"))
{
    sqlCon.Open();
    retVal = new SqlCommand("Exec dbo.MakeDouble " + inpVal + ";", 
        sqlCon).ExecuteScalar().ToString();
    sqlCon.Close();
}
Debug.Print(inpVal + " * 2 = " + retVal); 
//> 11 * 2 = 22

How to upgrade docker container after its image changed

Taking from http://blog.stefanxo.com/2014/08/update-all-docker-images-at-once/

You can update all your existing images using the following command pipeline:

docker images | awk '/^REPOSITORY|\<none\>/ {next} {print $1}' | xargs -n 1 docker pull

UITableView load more when scrolling to bottom like Facebook application

for loading from an API, It works for me, Xcode10 , swift 4.2 :

1- create New Swift file and do like this:

//
//  apiTVCController.swift
//  ApiTestingTableView
//
//  Created by Hooma7n on 4/7/19.
//  Copyright © 2019 Hooma7n. All rights reserved.
//

import Foundation
import Alamofire

class apiget {

    var tableData : [Datum] = []
    var loadin : [Datum] = []
    var testfortotal : Int?


    func getfromapi(completionHandler : ((_ isSucess : Bool) -> Void)?) {
        let url = "https://reqres.in/api/users?page=1"
        Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil)
            .responseJSON(completionHandler : { response in
                switch response.result {
                case .success(let data):
                    guard let jsonData = try? JSONSerialization.data(withJSONObject: data, options: JSONSerialization.WritingOptions.prettyPrinted) else {return}
                    let decoder = JSONDecoder()
                    guard let result = try? decoder.decode(Welcome.self, from: jsonData) else {return}
                    self.tableData = result.data ?? []
                    self.testfortotal = result.total ?? 0
                    completionHandler?(true)

                //                    print(result)
                case .failure(let error):
                    print(error)
                }
            })
    }

    var pagecounter : Int = 2


    func loadmore(completionHandler : ((_ isSucess : Bool) -> Void)?){

        let url = "https://reqres.in/api/users?page=\(pagecounter)"
        Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil)
            .responseJSON(completionHandler : { response in
                switch response.result {
                case .success(let data):
                    guard let jsonData = try? JSONSerialization.data(withJSONObject: data, options: JSONSerialization.WritingOptions.prettyPrinted) else {return}
                    let decoder = JSONDecoder()
                    guard let myresult = try? decoder.decode(Welcome.self, from: jsonData) else {return}
                    self.loadin = myresult.data ?? []
                    self.tableData.append(contentsOf: myresult.data ?? [])
                    completionHandler?(true)
                    print(self.pagecounter)
                    self.pagecounter += 1

                //                    print(myresult)
                case .failure(let error):
                    print(error)
                }
            })

    }

}

extension apiget {

    struct Welcome: Codable {
        let page, perPage, total, totalPages: Int?
        var data: [Datum]?

        enum CodingKeys: String, CodingKey {
            case page
            case perPage = "per_page"
            case total
            case totalPages = "total_pages"
            case data
        }
    }

    struct Datum: Codable {
        let id: Int?
        let firstName, lastName: String?
        let avatar: String?

        enum CodingKeys: String, CodingKey {
            case id
            case firstName = "first_name"
            case lastName = "last_name"
            case avatar
        }
    }


}

2- in Your ViewController file (tableView Controller) :

//
//  apiTVC.swift
//  ApiTestingTableView
//
//  Created by Hooma7n on 4/7/19.
//  Copyright © 2019 Hooma7n. All rights reserved.
//

import UIKit
import Alamofire

class apiTVC: UITableViewController {

    var datamodel = apiget()

    override func viewDidLoad() {
        super.viewDidLoad()

        datamodel.getfromapi(completionHandler: {finish in
            if finish {self.tableView.reloadData()
            }

        })

    }


    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datamodel.tableData.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! apiTableViewCell
        cell.firstNameLabel.text = datamodel.tableData[indexPath.row].firstName
        cell.lastNameLabel.text = datamodel.tableData[indexPath.row].lastName
        cell.dateLabel.text = "\(datamodel.tableData[indexPath.row].id ?? 0)"
        cell.profileImageView.loadImage(fromURL: datamodel.tableData[indexPath.row].avatar ?? "")

        return cell

    }

    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let lastElement = datamodel.tableData.count - 1
        let total = datamodel.testfortotal ?? 12
        if indexPath.row == lastElement && datamodel.tableData.count < total{

            datamodel.loadmore(completionHandler: {finish in
                if finish {

                    self.tableView.reloadData()

                }})
        }
    }
}

if using tableView in Your viewController set delegate,datasource self in viewDidLoad.

Use css gradient over background image

The accepted answer works well. Just for completeness (and since I like it's shortness), I wanted to share how to to it with compass (SCSS/SASS):

body{
  $colorStart: rgba(0,0,0,0);
  $colorEnd: rgba(0,0,0,0.8);
  @include background-image(linear-gradient(to bottom, $colorStart, $colorEnd), url("bg.jpg"));
}

JSON: why are forward slashes escaped?

Ugly PHP!

The JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES must be default, not an (strange) option... How to say it to php-developers?

The default MUST be the most frequent use, and the (current) most widely used standards as UTF8. How many PHP-code fragments in the Github or other place need this exoctic "embedded in HTML" feature?

How to use sed to replace only the first occurrence in a file?

#!/bin/sed -f
1,/^#include/ {
    /^#include/i\
#include "newfile.h"
}

How this script works: For lines between 1 and the first #include (after line 1), if the line starts with #include, then prepend the specified line.

However, if the first #include is in line 1, then both line 1 and the next subsequent #include will have the line prepended. If you are using GNU sed, it has an extension where 0,/^#include/ (instead of 1,) will do the right thing.

How to change plot background color?

Use the set_facecolor(color) method of the axes object, which you've created one of the following ways:

  • You created a figure and axis/es together

    fig, ax = plt.subplots(nrows=1, ncols=1)
    
  • You created a figure, then axis/es later

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1) # nrows, ncols, index
    
  • You used the stateful API (if you're doing anything more than a few lines, and especially if you have multiple plots, the object-oriented methods above make life easier because you can refer to specific figures, plot on certain axes, and customize either)

    plt.plot(...)
    ax = plt.gca()
    

Then you can use set_facecolor:

ax.set_facecolor('xkcd:salmon')
ax.set_facecolor((1.0, 0.47, 0.42))

example plot with pink background on the axes

As a refresher for what colors can be:

matplotlib.colors

Matplotlib recognizes the following formats to specify a color:

  • an RGB or RGBA tuple of float values in [0, 1] (e.g., (0.1, 0.2, 0.5) or (0.1, 0.2, 0.5, 0.3));
  • a hex RGB or RGBA string (e.g., '#0F0F0F' or '#0F0F0F0F');
  • a string representation of a float value in [0, 1] inclusive for gray level (e.g., '0.5');
  • one of {'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'};
  • a X11/CSS4 color name;
  • a name from the xkcd color survey; prefixed with 'xkcd:' (e.g., 'xkcd:sky blue');
  • one of {'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'} which are the Tableau Colors from the ‘T10’ categorical palette (which is the default color cycle);
  • a “CN” color spec, i.e. 'C' followed by a single digit, which is an index into the default property cycle (matplotlib.rcParams['axes.prop_cycle']); the indexing occurs at artist creation time and defaults to black if the cycle does not include color.

All string specifications of color, other than “CN”, are case-insensitive.

How to duplicate a whole line in Vim?

yy

will yank the current line without deleting it

dd

will delete the current line

p

will put a line grabbed by either of the previous methods

How to change the ROOT application?

Adding a <Context> tag in the <Host> tag in server.xml for Tomcat 6 will resolve the problem.

If you use path="" empty you can use a URL like http://localhost/first.do.

In the context tag set attributes docBase="E:\struts-ITRCbook\myStrutsbook" and reloadable="true", then end the context tag.

It should look something like this:

<Host name="localhost"  appBase="webapps" 
        unpackWARs="true" autoDeploy="true"
        xmlValidation="false" xmlNamespaceAware="false">
    <Context path="" docBase="E:\struts-ITRCbook\myStrutsbook" reloadable="true">
    </Context>
</Host>

CSS rotate property in IE

Just a hint... think twice before using "transform: rotate()", or even "-ms-transform :rotate()" (IE9) with mobiles!

I've been knocking hard to the wall for days. I have a 'kinetic' system going on, that slides images and, on top of it, a command area. I did "transform" on an arrow button so it simulates pointing up and down... I've reviewd the 1.000 plus code lines for ages!!! ;-)

All ok, once I removed transform:rotate from the CSS. It's a bit (not to use bad words) tricky the way IE handles it, comparing to other borwsers.

Great answer @Spudley! Thanks for writing it!

Why does an image captured using camera intent gets rotated on some devices on Android?

If you are using Fresco, you can use this -

final ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(uri)
.setRotationOptions(RotationOptions.autoRotate())
.build();

mSimpleDraweeView.setController(
Fresco.newDraweeControllerBuilder()
    .setImageRequest(imageRequest)
    .build());

This automatically rotates the images based on Exif data.

Source: https://frescolib.org/docs/rotation.html

Loop through columns and add string lengths as new columns

For the sake of completeness, there is also a data.table solution:

library(data.table)
result <- setDT(df)[, paste0(names(df), "_length") := lapply(.SD, stringr::str_length)]
result
#      col1     col2 col1_length col2_length
#1:     abc adf qqwe           3           8
#2:    abcd        d           4           1
#3:       a        e           1           1
#4: abcdefg        f           7           1

How to drop a unique constraint from table column?

Use this SQL command to drop a unique constraint:

ALTER TABLE tbl_name
DROP INDEX column_name

How to retrieve the first word of the output of a command in bash?

read is your friend:

  • If string is in a variable:

    string="word1 word2"
    read -r first _ <<< "$string"
    printf '%s\n' "$first"
    
  • If you're working in a pipe: first case: you only want the first word of the first line:

    printf '%s\n' "word1 word2" "line2" | { read -r first _; printf '%s\n' "$first"; }
    

    second case: you want the first word of each line:

    printf '%s\n' "word1 word2" "worda wordb" | while read -r first _; do printf '%s\n' "$first"; done
    

These work if there are leading spaces:

printf '%s\n' "   word1 word2" | { read -r first _; printf '%s\n' "$first"; }

View stored procedure/function definition in MySQL

Perfect, try it:

SELECT ROUTINE_DEFINITION FROM INFORMATION_SCHEMA.ROUTINES
    WHERE ROUTINE_SCHEMA = 'yourdb' AND ROUTINE_TYPE = 'PROCEDURE' AND ROUTINE_NAME = "procedurename";

X-Frame-Options: ALLOW-FROM in firefox and chrome

I posted this question and never saw the feedback (which came in several months after, it seems :).

As Kinlan mentioned, ALLOW-FROM is not supported in all browsers as an X-Frame-Options value.

The solution was to branch based on browser type. For IE, ship X-Frame-Options. For everyone else, ship X-Content-Security-Policy.

Hope this helps, and sorry for taking so long to close the loop!

How to sort by column in descending order in Spark SQL?

In the case of Java:

If we use DataFrames, while applying joins (here Inner join), we can sort (in ASC) after selecting distinct elements in each DF as:

Dataset<Row> d1 = e_data.distinct().join(s_data.distinct(), "e_id").orderBy("salary");

where e_id is the column on which join is applied while sorted by salary in ASC.

Also, we can use Spark SQL as:

SQLContext sqlCtx = spark.sqlContext();
sqlCtx.sql("select * from global_temp.salary order by salary desc").show();

where

  • spark  -> SparkSession
  • salary -> GlobalTemp View.

Using Excel as front end to Access database (with VBA)

If the end user has Access, it might be easier to develop the whole thing in Access. Access has some WYSIWYG form design tools built-in.