Programs & Examples On #Background service

Android Starting Service at Boot Time , How to restart service class after device Reboot?

It's possible to register your own application service for starting automatically when the device has been booted. You need this, for example, when you want to receive push events from a http server and want to inform the user as soon a new event occurs. The user doesn't have to start the activity manually before the service get started...

It's quite simple. First give your app the permission RECEIVE_BOOT_COMPLETED. Next you need to register a BroadcastReveiver. We call it BootCompletedIntentReceiver.

Your Manifest.xml should now look like this:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.jjoe64">
 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
 <application>
  <receiver android:name=".BootCompletedIntentReceiver">
   <intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
   </intent-filter>
  </receiver>
  <service android:name=".BackgroundService"/>
 </application>
</manifest>

As the last step you have to implement the Receiver. This receiver just starts your background service.

package com.jjoe64;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.jjoe64.BackgroundService;

public class BootCompletedIntentReceiver extends BroadcastReceiver {
 @Override
 public void onReceive(Context context, Intent intent) {
  if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
   Intent pushIntent = new Intent(context, BackgroundService.class);
   context.startService(pushIntent);
  }
 }
}

From http://www.jjoe64.com/2011/06/autostart-service-on-device-boot.html

startForeground fail after upgrade to Android 8.1

In my case, it's because we tried to post a notification without specifying the NotificationChannel:

public static final String NOTIFICATION_CHANNEL_ID_SERVICE = "com.mypackage.service";
public static final String NOTIFICATION_CHANNEL_ID_TASK = "com.mypackage.download_info";

public void initChannel(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_SERVICE, "App Service", NotificationManager.IMPORTANCE_DEFAULT));
        nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_INFO, "Download Info", NotificationManager.IMPORTANCE_DEFAULT));
    }
}

The best place to put above code is in onCreate() method in the Application class, so that we just need to declare it once for all:

public class App extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        initChannel();
    }
}

After we set this up, we can use notification with the channelId we just specified:

Intent i = new Intent(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID_INFO);
            .setContentIntent(pi)
            .setWhen(System.currentTimeMillis())
            .setContentTitle("VirtualBox.exe")
            .setContentText("Download completed")
            .setSmallIcon(R.mipmap.ic_launcher);

Then, we can use it to post a notification:

int notifId = 45;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(notifId, builder.build());

If you want to use it as foreground service's notification:

startForeground(notifId, builder.build());

Upload files from Java client to a HTTP server

You'd normally use java.net.URLConnection to fire HTTP requests. You'd also normally use multipart/form-data encoding for mixed POST content (binary and character data). Click the link, it contains information and an example how to compose a multipart/form-data request body. The specification is in more detail described in RFC2388.

Here's a kickoff example:

String url = "http://example.com/upload";
String charset = "UTF-8";
String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.

URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

try (
    OutputStream output = connection.getOutputStream();
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) {
    // Send normal param.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
    writer.append(CRLF).append(param).append(CRLF).flush();

    // Send text file.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF);
    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
    writer.append(CRLF).flush();
    Files.copy(textFile.toPath(), output);
    output.flush(); // Important before continuing with writer!
    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

    // Send binary file.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
    writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
    writer.append("Content-Transfer-Encoding: binary").append(CRLF);
    writer.append(CRLF).flush();
    Files.copy(binaryFile.toPath(), output);
    output.flush(); // Important before continuing with writer!
    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

    // End of multipart/form-data.
    writer.append("--" + boundary + "--").append(CRLF).flush();
}

// Request is lazily fired whenever you need to obtain information about response.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode); // Should be 200

This code is less verbose when you use a 3rd party library like Apache Commons HttpComponents Client.

The Apache Commons FileUpload as some incorrectly suggest here is only of interest in the server side. You can't use and don't need it at the client side.

See also

how to get the cookies from a php curl into a variable

libcurl also provides CURLOPT_COOKIELIST which extracts all known cookies. All you need is to make sure the PHP/CURL binding can use it.

Print list without brackets in a single row

There are two answers , First is use 'sep' setting

>>> print(*names, sep = ', ')

The other is below

>>> print(', '.join(names))

Is it possible to install both 32bit and 64bit Java on Windows 7?

You can install multiple Java runtimes under Windows (including Windows 7) as long as each is in their own directory.

For example, if you are running Win 7 64-bit, or Win Server 2008 R2, you may install 32-bit JRE in "C:\Program Files (x86)\Java\jre6" and 64-bit JRE in "C:\Program Files\Java\jre6", and perhaps IBM Java 6 in "C:\Program Files (x86)\IBM\Java60\jre".

The Java Control Panel app theoretically has the ability to manage multiple runtimes: Java tab >> View... button

There are tabs for User and System settings. You can add additional runtimes with Add or Find, but once you have finished adding runtimes and hit OK, you have to hit Apply in the main Java tab frame, which is not as obvious as it could be - otherwise your changes will be lost.

If you have multiple versions installed, only the main version will auto-update. I have not found a solution to this apart from the weak workaround of manually updating whenever I see an auto-update, so I'd love to know if anyone has a fix for that.

Most Java IDEs allow you to select any Java runtime on your machine to build against, but if not using an IDE, you can easily manage this using environment variables in a cmd window. Your PATH and the JAVA_HOME variable determine which runtime is used by tools run from the shell. Set the JAVA_HOME to the jre directory you want and put the bin directory into your path (and remove references to other runtimes) - with IBM you may need to add multiple bin directories. This is pretty much all the set up that the default system Java does. You can also set CLASSPATH, ANT_HOME, MAVEN_HOME, etc. to unique values to match your runtime.

MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in Internet Explorer

I still had an issue with it passing the format yyyy-MM-dd, but I got around it by changing the Date.cshtml:

@model DateTime?

@{
    string date = string.Empty;
    if (Model != null)
    {
        date = string.Format("{0}-{1}-{2}", Model.Value.Year, Model.Value.Month, Model.Value.Day);
    }

    @Html.TextBox(string.Empty, date, new { @class = "datefield", type = "date"  })
}

Set the maximum character length of a UITextField

Swift 4

import UIKit

private var kAssociationKeyMaxLength: Int = 0

extension UITextField {
    
    @IBInspectable var maxLength: Int {
        get {
            if let length = objc_getAssociatedObject(self, &kAssociationKeyMaxLength) as? Int {
                return length
            } else {
                return Int.max
            }
        }
        set {
            objc_setAssociatedObject(self, &kAssociationKeyMaxLength, newValue, .OBJC_ASSOCIATION_RETAIN)
            addTarget(self, action: #selector(checkMaxLength), for: .editingChanged)
        }
    }
    
    @objc func checkMaxLength(textField: UITextField) {
        guard let prospectiveText = self.text,
            prospectiveText.count > maxLength
            else {
                return
        }
        
        let selection = selectedTextRange
        
        let indexEndOfText = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
        let substring = prospectiveText[..<indexEndOfText]
        text = String(substring)
        
        selectedTextRange = selection
    }
}

Edit: memory leak issue fixed.

enter image description here

Convert pandas DataFrame into list of lists

EDIT: as_matrix is deprecated since version 0.23.0

You can use the built in values or to_numpy (recommended option) method on the dataframe:

In [8]:
df.to_numpy()

Out[8]:
array([[  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.8,   6.1,   5.4, ...,  15.9,  14.4,   8.6],
   ..., 
   [  0.2,   1.3,   2.3, ...,  16.1,  16.1,  10.8],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4]])

If you explicitly want lists and not a numpy array add .tolist():

df.to_numpy().tolist()

Setting custom UITableViewCells height

Thanks to all the posts on this topic, there are some really helpful ways to adjust the rowHeight of a UITableViewCell.

Here is a compilation of some of the concepts from everyone else that really helps when building for the iPhone and iPad. You can also access different sections and adjust them according to the varying sizes of views.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
    int cellHeight = 0;

    if ([indexPath section] == 0) 
    {
        cellHeight = 16;
        settingsTable.rowHeight = cellHeight;
    }
    else if ([indexPath section] == 1)
    {
        cellHeight = 20;
        settingsTable.rowHeight = cellHeight;
    }

    return cellHeight;
}
else
{
    int cellHeight = 0;

    if ([indexPath section] == 0) 
    {
        cellHeight = 24;
        settingsTable.rowHeight = cellHeight;
    }
    else if ([indexPath section] == 1)
    {
        cellHeight = 40;
        settingsTable.rowHeight = cellHeight;
    }

    return cellHeight;
}
return 0;
} 

Transposing a 2D-array in JavaScript

here is my implementation in modern browser (without dependency):

transpose = m => m[0].map((x,i) => m.map(x => x[i]))

how can I check if a file exists?

an existing folder will FAIL with FileExists

Function FileExists(strFileName)
' Check if a file exists - returns True or False

use instead or in addition:

Function FolderExists(strFolderPath)
' Check if a path exists

How do I make a column unique and index it in a Ruby on Rails migration?

The short answer for old versions of Rails (see other answers for Rails 4+):

add_index :table_name, :column_name, unique: true

To index multiple columns together, you pass an array of column names instead of a single column name,

add_index :table_name, [:column_name_a, :column_name_b], unique: true

If you get "index name... is too long", you can add name: "whatever" to the add_index method to make the name shorter.

For fine-grained control, there's a "execute" method that executes straight SQL.

That's it!

If you are doing this as a replacement for regular old model validations, check to see how it works. The error reporting to the user will likely not be as nice without model-level validations. You can always do both.

Take nth column in a text file

If you are using structured data, this has the added benefit of not invoking an extra shell process to run tr and/or cut or something. ...

(Of course, you will want to guard against bad inputs with conditionals and sane alternatives.)

...
while read line ; 
do 
    lineCols=( $line ) ;
    echo "${lineCols[0]}"
    echo "${lineCols[1]}"
done < $myFQFileToRead ; 
...

docker error: /var/run/docker.sock: no such file or directory

You don't need to run any docker commands as sudo when you're using boot2docker as every command passed into the boot2docker VM runs as root by default.

You're seeing the error when you're running as sudo because sudo doesn't have the DOCKER_HOST env set, only your user does.

You can confirm this by doing a:

$ env

Then a

$ sudo env

And looking for DOCKER_HOST in each output.

As for having a docker file that runs your script, something like this might work for you:

Dockerfile

FROM busybox

# Copy your script into the docker image
ADD /path/to/your/script.sh /usr/local/bin/script.sh

# Run your script
CMD /usr/local/bin/script.sh

Then you can run:

docker build -t your-image-name:your-tag .

This will build your docker image, which you can see by doing a:

docker images

Then, to run your container, you can do a:

docker run your-image-name:your-tag

This run command will start a container from the image you created with your Dockerfile and your build command and then it will finish once your script.sh has finished executing.

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

Why are you all going the hard way?

with open("myfile") as myfile:
    nonempty = filter(str.rstrip, myfile)

Convert nonempty into a list if you have the urge to do so, although I highly suggest keeping nonempty a generator as it is in Python 3.x

In Python 2.x you may use itertools.ifilter to do your bidding instead.

Remove a string from the beginning of a string

Nice speed, but this is hard-coded to depend on the needle ending with _. Is there a general version? – toddmo Jun 29 at 23:26

A general version:

$parts = explode($start, $full, 2);
if ($parts[0] === '') {
    $end = $parts[1];
} else {
    $fail = true;
}

Some benchmarks:

<?php

$iters = 100000;
$start = "/aaaaaaa/bbbbbbbbbb";
$full = "/aaaaaaa/bbbbbbbbbb/cccccccccc/dddddddddd/eeeeeeeeee";
$end = '';

$fail = false;

$t0 = microtime(true);
for ($i = 0; $i < $iters; $i++) {
    if (strpos($full, $start) === 0) {
        $end = substr($full, strlen($start));
    } else {
        $fail = true;
    }
}
$t = microtime(true) - $t0;
printf("%16s : %f s\n", "strpos+strlen", $t);

$t0 = microtime(true);
for ($i = 0; $i < $iters; $i++) {
    $parts = explode($start, $full, 2);
    if ($parts[0] === '') {
        $end = $parts[1];
    } else {
        $fail = true;
    }
}
$t = microtime(true) - $t0;
printf("%16s : %f s\n", "explode", $t);

On my quite old home PC:

$ php bench.php

Outputs:

   strpos+strlen : 0.158388 s
         explode : 0.126772 s

How to check if a variable is set in Bash?

While most of the techniques stated here are correct, bash 4.2 supports an actual test for the presence of a variable (man bash), rather than testing the value of the variable.

[[ -v foo ]]; echo $?
# 1

foo=bar
[[ -v foo ]]; echo $?
# 0

foo=""
[[ -v foo ]]; echo $?
# 0

Notably, this approach will not cause an error when used to check for an unset variable in set -u / set -o nounset mode, unlike many other approaches, such as using [ -z.

How to disable JavaScript in Chrome Developer Tools?

Full and fast instructions for Chrome browsers (Opera incl.)

The first way

  1. If Developer Tools aren't open then press F12 key on keyboard to show the Developer Tools. In Opera browser you have to use key combination Ctrl + Shift + i on keyboard to open it.
  2. To show the settings just press F1 key on keyboard. The Developer Tools window must be focused when you are doing it. Or if you want to open the settings with the mouse then you have to click on ? button in the top right corner of the Developer Tools, then click Settings in the menu.

Then you have to scroll down the settings window to bottom and then you will see the checkbox for disabling JavaScript like follows:

disable JavaScript in chrome developer tools

Just click on this checkbox and push esc key on keyboard for hide the settings. If you want to enable it then you have to do the same way again.

The second way

  1. If Developer Tools aren't open then open it like in the first way is described.
  2. Press the key combination Ctrl + Shift + P (for Windows or Linux) or Cmd (?) + Shift + P (for Mac) to open the Command Menu. Be sure that the focus is on the DevTools window.
  3. Type there "Disable JavaScript" and then press Enter or click it with the mouse. If you want to turn back the enanled JS then open the Command Menu again and type there "Enable JavaScript" and then press Enter or click it with the mouse. You could also write just only "JavaScript" or "Java" there and then choose it with the mouse.

disable JavaScript in chrome developer tools

If all this does not work

For some reason it is possible that it does not work. I this case open a new empty site in "Incognito Mode" and do all this there.

The quickest way

In Chrome Web Store or on Opera Addon site you can find and install extensions which do it per one click. Just search "Javascript Switcher":

How to search by key=>value in a multidimensional array in PHP

If you want to search for array of keys this is good

function searchKeysInMultiDimensionalArray($array, $keys)
{
    $results = array();

    if (is_array($array)) {
        $resultArray = array_intersect_key($array, array_flip($keys));
        if (!empty($resultArray)) {
            $results[] = $resultArray;
        }

        foreach ($array as $subarray) {
            $results = array_merge($results, searchKeysInMultiDimensionalArray($subarray, $keys));
        }
    }

    return $results;
}

Keys will not overwrite because each set of key => values will be in separate array in resulting array.
If you don't want duplicate keys then use this one

function searchKeysInMultiDimensionalArray($array, $keys)
{
    $results = array();

    if (is_array($array)) {
        $resultArray = array_intersect_key($array, array_flip($keys));
        if (!empty($resultArray)) {
            foreach($resultArray as $key => $single) {

                $results[$key] = $single;
            }
        }

        foreach ($array as $subarray) {
            $results = array_merge($results, searchKeysInMultiDimensionalArray($subarray, $keys));
        }
    }

    return $results;
}

DateTime's representation in milliseconds?

There are ToUnixTime() and ToUnixTimeMs() methods in DateTimeExtensions class

DateTime.UtcNow.ToUnixTimeMs()

Is there a way to get a list of column names in sqlite?

I use this:

import sqlite3

    db = sqlite3.connect('~/foo.sqlite')
    dbc = db.cursor()
    dbc.execute("PRAGMA table_info('bar')"
    ciao = dbc.fetchall()

    HeaderList=[]
    for i in ciao:
        counter=0
        for a in i:
            counter+=1
            if( counter==2):
                HeaderList.append(a)

print(HeaderList)

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

For whatever reason $('.panel-collapse').collapse({'toggle': true, 'parent': '#accordion'}); only seems to work the first time and it only works to expand the collapsible. (I tried to start with a expanded collapsible and it wouldn't collapse.)

It could just be something that runs once the first time you initialize collapse with those parameters.

You will have more luck using the show and hide methods.

Here is an example:

$(function() {

  var $active = true;

  $('.panel-title > a').click(function(e) {
    e.preventDefault();
  });

  $('.collapse-init').on('click', function() {
    if(!$active) {
      $active = true;
      $('.panel-title > a').attr('data-toggle', 'collapse');
      $('.panel-collapse').collapse('hide');
      $(this).html('Click to disable accordion behavior');
    } else {
      $active = false;
      $('.panel-collapse').collapse('show');
      $('.panel-title > a').attr('data-toggle','');
      $(this).html('Click to enable accordion behavior');
    }
  });

});

http://bootply.com/98201

Update

Granted KyleMit seems to have a way better handle on this then me. I'm impressed with his answer and understanding.

I don't understand what's going on or why the show seemed to be toggling in some places.

But After messing around for a while.. Finally came with the following solution:

$(function() {
  var transition = false;
  var $active = true;

  $('.panel-title > a').click(function(e) {
    e.preventDefault();
  });

  $('#accordion').on('show.bs.collapse',function(){
    if($active){
        $('#accordion .in').collapse('hide');
    }
  });

  $('#accordion').on('hidden.bs.collapse',function(){
    if(transition){
        transition = false;
        $('.panel-collapse').collapse('show');
    }
  });

  $('.collapse-init').on('click', function() {
    $('.collapse-init').prop('disabled','true');
    if(!$active) {
      $active = true;
      $('.panel-title > a').attr('data-toggle', 'collapse');
      $('.panel-collapse').collapse('hide');
      $(this).html('Click to disable accordion behavior');
    } else {
      $active = false;
      if($('.panel-collapse.in').length){
        transition = true;
        $('.panel-collapse.in').collapse('hide');       
      }
      else{
        $('.panel-collapse').collapse('show');
      }
      $('.panel-title > a').attr('data-toggle','');
      $(this).html('Click to enable accordion behavior');
    }
    setTimeout(function(){
        $('.collapse-init').prop('disabled','');
    },800);
  });
});

http://bootply.com/98239

HTML text-overflow ellipsis detection

I think the better way to detect it is use getClientRects(), it seems each rect has the same height, so we can caculate lines number with the number of different top value.

getClientRects work like this

function getRowRects(element) {
    var rects = [],
        clientRects = element.getClientRects(),
        len = clientRects.length,
        clientRect, top, rectsLen, rect, i;

    for(i=0; i<len; i++) {
        has = false;
        rectsLen = rects.length;
        clientRect = clientRects[i];
        top = clientRect.top;
        while(rectsLen--) {
            rect = rects[rectsLen];
            if (rect.top == top) {
                has = true;
                break;
            }
        }
        if(has) {
            rect.right = rect.right > clientRect.right ? rect.right : clientRect.right;
            rect.width = rect.right - rect.left;
        }
        else {
            rects.push({
                top: clientRect.top,
                right: clientRect.right,
                bottom: clientRect.bottom,
                left: clientRect.left,
                width: clientRect.width,
                height: clientRect.height
            });
        }
    }
    return rects;
}

getRowRects work like this

you can detect like this

How to create JSON string in C#

I've found that you don't need the serializer at all. If you return the object as a List. Let me use an example.

In our asmx we get the data using the variable we passed along

// return data
[WebMethod(CacheDuration = 180)]
public List<latlon> GetData(int id) 
{
    var data = from p in db.property 
               where p.id == id 
               select new latlon
               {
                   lat = p.lat,
                   lon = p.lon

               };
    return data.ToList();
}

public class latlon
{
    public string lat { get; set; }
    public string lon { get; set; }
}

Then using jquery we access the service, passing along that variable.

// get latlon
function getlatlon(propertyid) {
var mydata;

$.ajax({
    url: "getData.asmx/GetLatLon",
    type: "POST",
    data: "{'id': '" + propertyid + "'}",
    async: false,
    contentType: "application/json;",
    dataType: "json",
    success: function (data, textStatus, jqXHR) { //
        mydata = data;
    },
    error: function (xmlHttpRequest, textStatus, errorThrown) {
        console.log(xmlHttpRequest.responseText);
        console.log(textStatus);
        console.log(errorThrown);
    }
});
return mydata;
}

// call the function with your data
latlondata = getlatlon(id);

And we get our response.

{"d":[{"__type":"MapData+latlon","lat":"40.7031420","lon":"-80.6047970}]}

How to filter in NaN (pandas)?

Simplest of all solutions:

filtered_df = df[df['var2'].isnull()]

This filters and gives you rows which has only NaN values in 'var2' column.

How to change the font and font size of an HTML input tag?

<input type ="text" id="txtComputer">

css

input[type="text"]
{
    font-size:24px;
}

How to watch and compile all TypeScript sources?

The tsc compiler will only watch those files that you pass on the command line. It will not watch files that are included using a /// <sourcefile> reference. If your working with the bash, you could use find to recursively find all *.ts files and compile them:

find . -name "*.ts" | xargs tsc -w

How can I make my website's background transparent without making the content (images & text) transparent too?

I would agree with @evillinux, It would be best to make your background image semi transparent so it supports < ie8

The other suggestions of using another div are also a great option, and it's the way to go if you want to do this in css. For example if the site had such features as selecting your own background color. I would suggest using a filter for older IE. eg:

filter:Alpha(opacity=50)

SQL "IF", "BEGIN", "END", "END IF"?

The only time the second insert into @clases should fail to fire is if an error occurred in the first insert statement.

If that's the case, then you need to decide if the second statement should run prior to the first OR if you need a transaction in order to perform a rollback.

CSS disable text selection

Don't apply these properties to the whole body. Move them to a class and apply that class to the elements you want to disable select:

.disable-select {
  -webkit-user-select: none;  
  -moz-user-select: none;    
  -ms-user-select: none;      
  user-select: none;
}

XMLHttpRequest module not defined/found

With the xhr2 library you can globally overwrite XMLHttpRequest from your JS code. This allows you to use external libraries in node, that were intended to be run from browsers / assume they are run in a browser.

global.XMLHttpRequest = require('xhr2');

Regex to check whether a string contains only numbers

var reg = /^\d+$/;

should do it. The original matches anything that consists of exactly one digit.

How to install mcrypt extension in xampp

First, you should download the suitable version for your system from here: https://pecl.php.net/package/mcrypt/1.0.3/windows

Then, you should copy php_mcrypt.dll to ../xampp/php/ext/ and enable the extension by adding extension=mcrypt to your xampp/php/php.ini file.

Regex for parsing directory and filename

Most languages have path parsing functions that will give you this already. If you have the ability, I'd recommend using what comes to you for free out-of-the-box.

Assuming / is the path delimiter...

^(.*/)([^/]*)$

The first group will be whatever the directory/path info is, the second will be the filename. For example:

  • /foo/bar/baz.log: "/foo/bar/" is the path, "baz.log" is the file
  • foo/bar.log: "foo/" is the path, "bar.log" is the file
  • /foo/bar: "/foo/" is the path, "bar" is the file
  • /foo/bar/: "/foo/bar/" is the path and there is no file.

How to use onResume()?

Restarting the app will call OnCreate().

Continuing the app when it is paused will call OnResume(). From the official docs at https://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle here's a diagram of the activity lifecycle.

the Android activity lifecycle, from https://developer.android.com/images/activity_lifecycle.png on https://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

Cannot resolve symbol 'AppCompatActivity'

If the soft methods via gradle file / "Invalidate caches" and the other IDE tools do not work, use the hard way:

  1. Exit Android Studio
  2. Navigate in your project to the .idea folder
  3. Just Rename the libraries folder
  4. Restart Android Studio. It should now recreate the libraries folder and work again.

This worked for me on

Android Studio 3.1.2
Build #AI-173.4720617, built on April 13, 2018
JRE: 1.8.0_152-release-1024-b01 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Linux 4.13.0-38-generic

Shahbaz Ali confirmed, it works also on

Android Studio 3.1.3
Build #AI-173.4819257, built on June 4, 2018
JRE: 1.8.0_152-release-1024-b01 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Linux 4.13.0-38-generic

moujib confirmed, it works on Android Studio 3.2.1

Is there any simple way to convert .xls file to .csv file? (Excel)

This is a modification of nate_weldon's answer with a few improvements:

  • More robust releasing of Excel objects
  • Set application.DisplayAlerts = false; before attempting to save to hide prompts

Also note that the application.Workbooks.Open and ws.SaveAs methods expect sourceFilePath and targetFilePath to be full paths (ie. directory path + filename)

private static void SaveAs(string sourceFilePath, string targetFilePath)
{
    Application application = null;
    Workbook wb = null;
    Worksheet ws = null;

    try
    {
        application = new Application();
        application.DisplayAlerts = false;
        wb = application.Workbooks.Open(sourceFilePath);
        ws = (Worksheet)wb.Sheets[1];
        ws.SaveAs(targetFilePath, XlFileFormat.xlCSV);
    }
    catch (Exception e)
    {
        // Handle exception
    }
    finally
    {
        if (application != null) application.Quit();
        if (ws != null) Marshal.ReleaseComObject(ws);
        if (wb != null) Marshal.ReleaseComObject(wb);
        if (application != null) Marshal.ReleaseComObject(application);
    }
}

How to concatenate text from multiple rows into a single text string in SQL server?

Here is the complete solution to achieve this:

-- Table Creation
CREATE TABLE Tbl
( CustomerCode    VARCHAR(50)
, CustomerName    VARCHAR(50)
, Type VARCHAR(50)
,Items    VARCHAR(50)
)

insert into Tbl
SELECT 'C0001','Thomas','BREAKFAST','Milk'
union SELECT 'C0001','Thomas','BREAKFAST','Bread'
union SELECT 'C0001','Thomas','BREAKFAST','Egg'
union SELECT 'C0001','Thomas','LUNCH','Rice'
union SELECT 'C0001','Thomas','LUNCH','Fish Curry'
union SELECT 'C0001','Thomas','LUNCH','Lessy'
union SELECT 'C0002','JOSEPH','BREAKFAST','Bread'
union SELECT 'C0002','JOSEPH','BREAKFAST','Jam'
union SELECT 'C0002','JOSEPH','BREAKFAST','Tea'
union SELECT 'C0002','JOSEPH','Supper','Tea'
union SELECT 'C0002','JOSEPH','Brunch','Roti'

-- function creation
GO
CREATE  FUNCTION [dbo].[fn_GetItemsByType]
(   
    @CustomerCode VARCHAR(50)
    ,@Type VARCHAR(50)
)
RETURNS @ItemType TABLE  ( Items VARCHAR(5000) )
AS
BEGIN

        INSERT INTO @ItemType(Items)
    SELECT  STUFF((SELECT distinct ',' + [Items]
         FROM Tbl 
         WHERE CustomerCode = @CustomerCode
            AND Type=@Type
            FOR XML PATH(''))
        ,1,1,'') as  Items



    RETURN 
END

GO

-- fianl Query
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Type) 
                    from Tbl
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT CustomerCode,CustomerName,' + @cols + '
             from 
             (
                select  
                    distinct CustomerCode
                    ,CustomerName
                    ,Type
                    ,F.Items
                    FROM Tbl T
                    CROSS APPLY [fn_GetItemsByType] (T.CustomerCode,T.Type) F
            ) x
            pivot 
            (
                max(Items)
                for Type in (' + @cols + ')
            ) p '

execute(@query) 

How to use the curl command in PowerShell?

Use splatting.

$CurlArgument = '-u', '[email protected]:yyyy',
                '-X', 'POST',
                'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
                '--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument

Passing a method parameter using Task.Factory.StartNew

class Program
{
    static void Main(string[] args)
    {
        Task.Factory.StartNew(() => MyMethod("param value"));
    }

    private static void MyMethod(string p)
    {
        Console.WriteLine(p);
    }
}

How do I return a char array from a function?

A char array is returned by char*, but the function you wrote does not work because you are returning an automatic variable that disappears when the function exits.

Use something like this:

char *testfunc() {
    char* arr = malloc(100);
    strcpy(arr,"xxxx");
    return arr;
}

This is of course if you are returning an array in the C sense, not an std:: or boost:: or something else.

As noted in the comment section: remember to free the memory from the caller.

How many characters in varchar(max)

For future readers who need this answer quickly:

2^31-1 = 2.147.483.647 characters

Jquery Validate custom error message location

JQUERY FORM VALIDATION CUSTOM ERROR MESSAGE

Demo & example

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  $("#registration").validate({_x000D_
    // Specify validation rules_x000D_
    rules: {_x000D_
      firstname: "required",_x000D_
      lastname: "required",_x000D_
      email: {_x000D_
        required: true,_x000D_
        email: true_x000D_
      },      _x000D_
      phone: {_x000D_
        required: true,_x000D_
        digits: true,_x000D_
        minlength: 10,_x000D_
        maxlength: 10,_x000D_
      },_x000D_
      password: {_x000D_
        required: true,_x000D_
        minlength: 5,_x000D_
      }_x000D_
    },_x000D_
    messages: {_x000D_
      firstname: {_x000D_
      required: "Please enter first name",_x000D_
     },      _x000D_
     lastname: {_x000D_
      required: "Please enter last name",_x000D_
     },     _x000D_
     phone: {_x000D_
      required: "Please enter phone number",_x000D_
      digits: "Please enter valid phone number",_x000D_
      minlength: "Phone number field accept only 10 digits",_x000D_
      maxlength: "Phone number field accept only 10 digits",_x000D_
     },     _x000D_
     email: {_x000D_
      required: "Please enter email address",_x000D_
      email: "Please enter a valid email address.",_x000D_
     },_x000D_
    },_x000D_
  _x000D_
  });_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>jQuery Form Validation Using validator()</title>_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> _x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>_x000D_
<style>_x000D_
  .error{_x000D_
    color: red;_x000D_
  }_x000D_
  label,_x000D_
  input,_x000D_
  button {_x000D_
    border: 0;_x000D_
    margin-bottom: 3px;_x000D_
    display: block;_x000D_
    width: 100%;_x000D_
  }_x000D_
 .common_box_body {_x000D_
    padding: 15px;_x000D_
    border: 12px solid #28BAA2;_x000D_
    border-color: #28BAA2;_x000D_
    border-radius: 15px;_x000D_
    margin-top: 10px;_x000D_
    background: #d4edda;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div class="common_box_body test">_x000D_
  <h2>Registration</h2>_x000D_
  <form action="#" name="registration" id="registration">_x000D_
 _x000D_
    <label for="firstname">First Name</label>_x000D_
    <input type="text" name="firstname" id="firstname" placeholder="John"><br>_x000D_
 _x000D_
    <label for="lastname">Last Name</label>_x000D_
    <input type="text" name="lastname" id="lastname" placeholder="Doe"><br>_x000D_
 _x000D_
    <label for="phone">Phone</label>_x000D_
    <input type="text" name="phone" id="phone" placeholder="8889988899"><br>  _x000D_
 _x000D_
    <label for="email">Email</label>_x000D_
    <input type="email" name="email" id="email" placeholder="[email protected]"><br>_x000D_
 _x000D_
    <label for="password">Password</label>_x000D_
    <input type="password" name="password" id="password" placeholder=""><br>_x000D_
 _x000D_
    <input name="submit" type="submit" id="submit" class="submit" value="Submit">_x000D_
  </form>_x000D_
</div>_x000D_
 _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to check if a URL exists or returns 404 with Java?

Based on the given answers and information in the question, this is the code you should use:

public static boolean doesURLExist(URL url) throws IOException
{
    // We want to check the current URL
    HttpURLConnection.setFollowRedirects(false);

    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

    // We don't need to get data
    httpURLConnection.setRequestMethod("HEAD");

    // Some websites don't like programmatic access so pretend to be a browser
    httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
    int responseCode = httpURLConnection.getResponseCode();

    // We only accept response code 200
    return responseCode == HttpURLConnection.HTTP_OK;
}

Of course tested and working.

'python' is not recognized as an internal or external command

Firstly, be sure where your python directory. It is normally in C:\Python27. If yours is different then change it from the below command.

If after you install it python still isn’t recognized, then in PowerShell enter this:

[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")

Close PowerShell and then start it again to make sure Python now runs. If it doesn’t, restart may be required.

enter image description here

.Net: How do I find the .NET version?

To just get the installed version(s) at the command line, I recommend using net-version.

  • It's just a single binary.
  • It uses the guidelines provided my Microsoft to get version information.
  • It doesn't require the SDK to be installed.
  • Or the Visual Studio command prompt.
  • It doesn't require you to use regedit and hunt down registry keys yourself. You can even pipe the output in a command line tool if you need to.

Source code is available on github.com

Full disclosure: I created this tool myself out of frustration.

If Radio Button is selected, perform validation on Checkboxes

You must use the equals operator not the assignment like

if(document.form1.radio1[0].checked == true) {
    alert("You have selected Option 1");
}

How to use foreach with a hash reference?

In Perl 5.14 (it works in now in Perl 5.13), we'll be able to just use keys on the hash reference

use v5.13.7;

foreach my $key (keys $ad_grp_ref) {
    ...
}

Why does .json() return a promise?

In addition to the above answers here is how you might handle a 500 series response from your api where you receive an error message encoded in json:

function callApi(url) {
  return fetch(url)
    .then(response => {
      if (response.ok) {
        return response.json().then(response => ({ response }));
      }

      return response.json().then(error => ({ error }));
    })
  ;
}

let url = 'http://jsonplaceholder.typicode.com/posts/6';

const { response, error } = callApi(url);
if (response) {
  // handle json decoded response
} else {
  // handle json decoded 500 series response
}

Submit form using a button outside the <form> tag

In HTML5, there is the form attribute. Basically

<form id="myform" method="get" action="something.php">
    <input type="text" name="name" />
</form>

<input type="submit" form="myform" />

Mapping composite keys using EF code first

I thought I would add to this question as it is the top google search result.

As has been noted in the comments, in EF Core there is no support for using annotations (Key attribute) and it must be done with fluent.

As I was working on a large migration from EF6 to EF Core this was unsavoury and so I tried to hack it by using Reflection to look for the Key attribute and then apply it during OnModelCreating

// get all composite keys (entity decorated by more than 1 [Key] attribute
foreach (var entity in modelBuilder.Model.GetEntityTypes()
    .Where(t => 
        t.ClrType.GetProperties()
            .Count(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute))) > 1))
{
    // get the keys in the appropriate order
    var orderedKeys = entity.ClrType
        .GetProperties()
        .Where(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute)))
        .OrderBy(p => 
            p.CustomAttributes.Single(x => x.AttributeType == typeof(ColumnAttribute))?
                .NamedArguments?.Single(y => y.MemberName == nameof(ColumnAttribute.Order))
                .TypedValue.Value ?? 0)
        .Select(x => x.Name)
        .ToArray();

    // apply the keys to the model builder
    modelBuilder.Entity(entity.ClrType).HasKey(orderedKeys);
}

I haven't fully tested this in all situations, but it works in my basic tests. Hope this helps someone

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

I had the same problem and later I realised that my app-routing.module.ts was inside a sub folder called app-routing. I moved this file directly under src and now it is working. (Now app-routing file has access to all the components)

How do you do Impersonation in .NET?

I'm aware that I'm quite late for the party, but I consider that the library from Phillip Allan-Harding, it's the best one for this case and similar ones.

You only need a small piece of code like this one:

private const string LOGIN = "mamy";
private const string DOMAIN = "mongo";
private const string PASSWORD = "HelloMongo2017";

private void DBConnection()
{
    using (Impersonator user = new Impersonator(LOGIN, DOMAIN, PASSWORD, LogonType.LOGON32_LOGON_NEW_CREDENTIALS, LogonProvider.LOGON32_PROVIDER_WINNT50))
    {
    }
}

And add his class:

.NET (C#) Impersonation with Network Credentials

My example can be used if you require the impersonated logon to have network credentials, but it has more options.

VBScript: Using WScript.Shell to Execute a Command Line Program That Accesses Active Directory

The issue turned out to be certificate-related. The WCF service called by the console app uses an X509 cert for authentication, which is installed on the servers that this script is hosted and run from.

On other servers, where the same services are consumed, the certificates were configured as follows:

winhttpcertcfg.exe -g -c LOCAL_MACHINE\My -s "certificate-name" -a "NETWORK SERVICE"

As they ran within the context of IIS. However, when the script was being run as it would in production, it's under the context of the user themselves. So, the script needed to be modified to the following:

winhttpcertcfg.exe -g -c LOCAL_MACHINE\My -s "certificate-name" -a "USERS"

Once that change was made, all was well. Thanks to everyone who offered assistance.

Javascript replace with reference to matched group?

"hello _there_".replace(/_(.*?)_/, function(a, b){
    return '<div>' + b + '</div>';
})

Oh, or you could also:

"hello _there_".replace(/_(.*?)_/, "<div>$1</div>")

EDIT by Liran H: For six other people including myself, $1 did not work, whereas \1 did.

concat scope variables into string in angular directive expression

I've created a working CodePen example demonstrating how to do this.

Relevant HTML:

<section ng-app="app" ng-controller="MainCtrl">
  <a href="#" ng-click="doSomething('#/path/{{obj.val1}}/{{obj.val2}}')">Click Me</a><br>
  debug: {{debug.val}}
</section>

Relevant javascript:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.obj = {
    val1: 'hello',
    val2: 'world'
  };

  $scope.debug = {
    val: ''
  };

  $scope.doSomething = function(input) {
    $scope.debug.val = input;
  };
});

How to detect idle time in JavaScript elegantly?

Just a few thoughts, an avenue or two to explore.

Is it possible to have a function run every 10 seconds, and have that check a "counter" variable? If that's possible, you can have an on mouseover for the page, can you not? If so, use the mouseover event to reset the "counter" variable. If your function is called, and the counter is above the range that you pre-determine, then do your action.

Again, just some thoughts... Hope it helps.

Extension gd is missing from your system - laravel composer Update

The solution is quite simple.

In your php.ini, just uncomment the line extension=php_gd2.dll (or .so extension for unix systems.)

Hope it helps.

SELECTING with multiple WHERE conditions on same column

Use:

  SELECT t.contactid
    FROM YOUR_TABLE t
   WHERE flag IN ('Volunteer', 'Uploaded')
GROUP BY t.contactid
  HAVING COUNT(DISTINCT t.flag) = 2

The key thing is that the counting of t.flag needs to equal the number of arguments in the IN clause.

The use of COUNT(DISTINCT t.flag) is in case there isn't a unique constraint on the combination of contactid and flag -- if there's no chance of duplicates you can omit the DISTINCT from the query:

  SELECT t.contactid
    FROM YOUR_TABLE t
   WHERE flag IN ('Volunteer', 'Uploaded')
GROUP BY t.contactid
  HAVING COUNT(t.flag) = 2

What is the &#xA; character?

It is the equivalent to \n -> LF (Line Feed).

Sometimes it is used in HTML and JavaScript. Otherwise in .NET environments, use Environment.NewLine.

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

I know this question is old -- but here's another, extremely simple solution ...

var elements = Array.from(document.querySelectorAll("div"));

Then it can be used like any, standard array.

PHP: Split string

The following will return you the "a" letter:

$a = array_shift(explode('.', 'a.b'));

Visual Studio Community 2015 expiration date

Here is an instructions for the problem:

You can evaluate Visual Studio for free up to 30 days.

To Unlock Visual Studio using an online subscription

Link Microsoft account to Visual Studio 2015

I have encountered this problem: enter image description here

Possible solution can be found at the link above.

This message indicates that while your subscription may still be valid, the license token Visual Studio uses to keep your subscription up to date hasn’t been refreshed and has gone stale due to one of the following reasons: You have not used Visual Studio or have had no internet connection for an extend period of time. You signed out of Visual Studio.

Escape regex special characters in a Python string

I'm surprised no one has mentioned using regular expressions via re.sub():

import re
print re.sub(r'([\"])',    r'\\\1', 'it\'s "this"')  # it's \"this\"
print re.sub(r"([\'])",    r'\\\1', 'it\'s "this"')  # it\'s "this"
print re.sub(r'([\" \'])', r'\\\1', 'it\'s "this"')  # it\'s\ \"this\"

Important things to note:

  • In the search pattern, include \ as well as the character(s) you're looking for. You're going to be using \ to escape your characters, so you need to escape that as well.
  • Put parentheses around the search pattern, e.g. ([\"]), so that the substitution pattern can use the found character when it adds \ in front of it. (That's what \1 does: uses the value of the first parenthesized group.)
  • The r in front of r'([\"])' means it's a raw string. Raw strings use different rules for escaping backslashes. To write ([\"]) as a plain string, you'd need to double all the backslashes and write '([\\"])'. Raw strings are friendlier when you're writing regular expressions.
  • In the substitution pattern, you need to escape \ to distinguish it from a backslash that precedes a substitution group, e.g. \1, hence r'\\\1'. To write that as a plain string, you'd need '\\\\\\1' — and nobody wants that.

How to find out what the date was 5 days ago?

5 days ago from a particular date:

$date = new DateTime('2008-12-02');
$date->sub(new DateInterval('P5D'));
echo $date->format('Y-m-d') . "\n";

How do I Search/Find and Replace in a standard string?

In C++11, you can do this as a one-liner with a call to regex_replace:

#include <string>
#include <regex>

using std::string;

string do_replace( string const & in, string const & from, string const & to )
{
  return std::regex_replace( in, std::regex(from), to );
}

string test = "Remove all spaces";
std::cout << do_replace(test, " ", "") << std::endl;

output:

Removeallspaces

Why can't I define my workbook as an object?

It's actually a sensible question. Here's the answer from Excel 2010 help:

"The Workbook object is a member of the Workbooks collection. The Workbooks collection contains all the Workbook objects currently open in Microsoft Excel."

So, since that workbook isn't open - at least I assume it isn't - it can't be set as a workbook object. If it was open you'd just set it like:

Set wbk = workbooks("Master Benchmark Data Sheet.xlsx")

Java 8 Stream and operation on arrays

Be careful if you have to deal with large numbers.

int[] arr = new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE};
long sum = Arrays.stream(arr).sum(); // Wrong: sum == 0

The sum above is not 2 * Integer.MIN_VALUE. You need to do this in this case.

long sum = Arrays.stream(arr).mapToLong(Long::valueOf).sum(); // Correct

.htaccess File Options -Indexes on Subdirectories

htaccess files affect the directory they are placed in and all sub-directories, that is an htaccess file located in your root directory (yoursite.com) would affect yoursite.com/content, yoursite.com/content/contents, etc.

http://www.javascriptkit.com/howto/htaccess.shtml

What is The difference between ListBox and ListView

Listview derives from listbox control. One most important difference is listview uses the extended selection mode by default . listview also adds a property called view which enables you to customize the view in a richer way than a custom itemspanel. One real life example of listview with gridview is file explorer's details view. Listview with grid view is a less powerful data grid. After the introduction of datagrid control listview lost its importance.

Uncaught TypeError: Cannot set property 'onclick' of null

Try to put all your <script ...></script> tags before the </body> tag. Perhaps the js is trying to access an object of the DOM before it's built up.

Make XAMPP / Apache serve file outside of htdocs folder

You can set Apache to serve pages from anywhere with any restrictions but it's normally distributed in a more secure form.

Editing your apache files (http.conf is one of the more common names) will allow you to set any folder so it appears in your webroot.

EDIT:

alias myapp c:\myapp\

I've edited my answer to include the format for creating an alias in the http.conf file which is sort of like a shortcut in windows or a symlink under un*x where Apache 'pretends' a folder is in the webroot. This is probably going to be more useful to you in the long term.

How to deal with floating point number precision in JavaScript?

How about toLocaleString method?

> 0.1+0.2
< 0.30000000000000004

> (0.1+0.2).toLocaleString()
< 0.3

If you want him to continue his computable.

Number.parseFloat((0.1+0.2).toLocaleString())

Number.prototype.toLocaleString()

Why not look at the document?

> 1000.021+0.02
< 1000.0409999999999


> (1000.021+0.02).toLocaleString()
< "1,000.041"

/// why not use this?
> (1000.021+0.02).toLocaleString("zh",{useGrouping: false,maximumFractionDigits: 10})
< "1000.041"

PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

just create environment variable like this

create environment variable like in the screenshot and make sure to replace with your sdk path in my case it was C:\Users\zeesh\AppData\Local\Android\sdk replace zeesh with your username and make sure to restart android studio to take effect.

Laravel PHP Command Not Found

type on terminal:

nano ~/.bash_profile 

then paste:

export PATH="/Users/yourusername/.composer/vendor/bin:$PATH"

then save (press ctrl+c, press Y, press enter)

now you are ready to use "laravel" on your terminal

How can I open a .tex file?

I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.

I have to assume you are using windows because you have mentioned notepad++.

  1. Use notepad++. Right click on the file and choose "edit with notepad++"

  2. Use notepad Change the filename extension to .txt and double click the file.

  3. Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"

If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.

Shell - How to find directory of some command?

PATH is an environment variable, and can be displayed with the echo command:

echo $PATH

It's a list of paths separated by the colon character ':'

The which command tells you which file gets executed when you run a command:

which lshw

sometimes what you get is a path to a symlink; if you want to trace that link to where the actual executable lives, you can use readlink and feed it the output of which:

readlink -f $(which lshw)

The -f parameter instructs readlink to keep following the symlink recursively.

Here's an example from my machine:

$ which firefox
/usr/bin/firefox

$ readlink -f $(which firefox)
/usr/lib/firefox-3.6.3/firefox.sh

How do I do a not equal in Django queryset filtering?

What you are looking for are all objects that have either a=false or x=5. In Django, | serves as OR operator between querysets:

results = Model.objects.filter(a=false)|Model.objects.filter(x=5)

How to subtract X day from a Date object in Java?

You may also be able to use the Duration class. E.g.

Date currentDate = new Date();
Date oneDayFromCurrentDate = new Date(currentDate.getTime() - Duration.ofDays(1).toMillis());

How to run a PowerShell script from a batch file

Another easy way to execute a ps script from batch is to simply incorporate it between the ECHO and the Redirection characters,(> and >>), example:

@echo off
set WD=%~dp0
ECHO New-Item -Path . -Name "Test.txt" -ItemType "file" -Value "This is a text string." -Force > "%WD%PSHELLFILE.ps1"
ECHO add-content -path "./Test.txt" -value "`r`nThe End" >> "%WD%PSHELLFILE.ps1"
powershell.exe -ExecutionPolicy Bypass -File "%WD%PSHELLFILE.ps1"
del "%WD%PSHELLFILE.ps1"

Last line deletes the created temp file.

Changing tab bar item image and text color iOS

In Swift 5 ioS 13.2 things have changed with TabBar styling, below code work 100%, tested out.

Add the below code in your UITabBarController class.

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let appearance = UITabBarAppearance()
        appearance.backgroundColor = .white

        setTabBarItemColors(appearance.stackedLayoutAppearance)
        setTabBarItemColors(appearance.inlineLayoutAppearance)
        setTabBarItemColors(appearance.compactInlineLayoutAppearance)

        setTabBarItemBadgeAppearance(appearance.stackedLayoutAppearance)
        setTabBarItemBadgeAppearance(appearance.inlineLayoutAppearance)
        setTabBarItemBadgeAppearance(appearance.compactInlineLayoutAppearance)

        tabBar.standardAppearance = appearance
 }

@available(iOS 13.0, *)
private func setTabBarItemColors(_ itemAppearance: UITabBarItemAppearance) {
    itemAppearance.normal.iconColor = .lightGray
    itemAppearance.normal.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.gray]

    itemAppearance.selected.iconColor = .white
    itemAppearance.selected.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.orange]
}

@available(iOS 13.0, *)
private func setTabBarItemBadgeAppearance(_ itemAppearance: UITabBarItemAppearance) {
    //Adjust the badge position as well as set its color
    itemAppearance.normal.badgeBackgroundColor = .orange
    itemAppearance.normal.badgeTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
    itemAppearance.normal.badgePositionAdjustment = UIOffset(horizontal: 1, vertical: -1)
}

Best implementation for hashCode method for a collection

There's a good implementation of the Effective Java's hashcode() and equals() logic in Apache Commons Lang. Checkout HashCodeBuilder and EqualsBuilder.

ASP.Net which user account running Web Service on IIS 7?

You are most likely looking for the IIS_IUSRS account.

How to create an Array, ArrayList, Stack and Queue in Java?

Just a small correction to the first answer in this thread.

Even for Stack, you need to create new object with generics if you are using Stack from java util packages.

Right usage:
    Stack<Integer> s = new Stack<Integer>();
    Stack<String> s1 = new Stack<String>();

    s.push(7);
    s.push(50);

    s1.push("string");
    s1.push("stack");

if used otherwise, as mentioned in above post, which is:

    /*
    Stack myStack = new Stack();
    // add any type of elements (String, int, etc..)
    myStack.push("Hello");
    myStack.push(1);
    */

Although this code works fine, has unsafe or unchecked operations which results in error.

Using Panel or PlaceHolder

A panel expands to a span (or a div), with it's content within it. A placeholder is just that, a placeholder that's replaced by whatever you put in it.

Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing

On a fresh Debian image, cloning https://github.com/python/cpython and running:

sudo apt-get update
sudo apt-get upgrade
sudo apt-get dist-upgrade
sudo apt-get install build-essential python-dev python-setuptools python-pip python-smbus
sudo apt-get install libncursesw5-dev libgdbm-dev libc6-dev
sudo apt-get install zlib1g-dev libsqlite3-dev tk-dev
sudo apt-get install libssl-dev openssl
sudo apt-get install libffi-dev

Now execute the configure file cloned above:

./configure
make # alternatively `make -j 4` will utilize 4 threads
sudo make altinstall

Got 3.7 installed and working for me.

SLIGHT UPDATE

Looks like I said I would update this answer with some more explanation and two years later I don't have much to add.

  • this SO post explains why certain libraries like python-dev might be necessary.
  • this SO post explains why one might use the altinstall as opposed to install argument in the make command.

Aside from that I guess the choice would be to either read through the cpython codebase looking for #include directives that need to be met, but what I usually do is keep trying to install the package and just keep reading through the output installing the required packages until it succeeds.

Reminds me of the story of the Engineer, the Manager and the Programmer whose car rolls down a hill.

How do I use $scope.$watch and $scope.$apply in AngularJS?

I found very in-depth videos which cover $watch, $apply, $digest and digest cycles in:

Following are a couple of slides used in those videos to explain the concepts (just in case, if the above links are removed/not working).

Enter image description here

In the above image, "$scope.c" is not being watched as it is not used in any of the data bindings (in markup). The other two ($scope.a and $scope.b) will be watched.

Enter image description here

From the above image: Based on the respective browser event, AngularJS captures the event, performs digest cycle (goes through all the watches for changes), execute watch functions and update the DOM. If not browser events, the digest cycle can be manually triggered using $apply or $digest.

More about $apply and $digest:

Enter image description here

.gitignore after commit

However, will it automatically remove these committed files from the repository?

No. Even with an existing .gitignore you are able to stage "ignored" files with the -f (force) flag. If they files are already commited, they don't get removed automatically.

git rm --cached path/to/ignored.exe

Aligning two divs side-by-side

The HTML code is for three div align side by side and can be used for two also by some changes

<div id="wrapper">
  <div id="first">first</div>
  <div id="second">second</div>
  <div id="third">third</div>
</div>

The CSS will be

#wrapper {
  display:table;
  width:100%;
}
#row {
  display:table-row;
}
#first {
  display:table-cell;
  background-color:red;
  width:33%;
}
#second {
  display:table-cell;
  background-color:blue;
  width:33%;
}
#third {
  display:table-cell;
  background-color:#bada55;
  width:34%;
}

This code will workup towards responsive layout as it will resize the

<div> 

according to device width. Even one can silent anyone

<div>

as

<!--<div id="third">third</div> --> 

and can use rest two for two

<div> 

side by side.

Is there a way to create interfaces in ES6 / Node 4?

Interfaces are not part of the ES6 but classes are.

If you really need them, you should look at TypeScript which support them.

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

How about using the history replacement function to add the site into the browsers history?

Try executing the following as soon as the window loads-

history.replaceState("example", "title", "http://www.example.com");

This should hopefully make it so even if it is the first page they have accessed, the URL you define in the code will be what they're taken to when they click back.

Chrome disable SSL checking for sites?

Mac Users please execute the below command from terminal to disable the certificate warning.

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --ignore-certificate-errors --ignore-urlfetcher-cert-requests &> /dev/null

Note that this will also have Google Chrome mark all HTTPS sites as insecure in the URL bar.

Turn off auto formatting in Visual Studio

You can tweak the settings of the code formatting. I always turn off all extra line breaks, and then it works fine for how I format the code.

If you tweak the settings as close as you can to your preference, that should leave you minimal work whenever you use refactoring.

Dynamically replace img src attribute with jQuery

You need to check out the attr method in the jQuery docs. You are misusing it. What you are doing within the if statements simply replaces all image tags src with the string specified in the 2nd parameter.

http://api.jquery.com/attr/

A better way to approach replacing a series of images source would be to loop through each and check it's source.

Example:

$('img').each(function () {
  var curSrc = $(this).attr('src');
  if ( curSrc === 'http://example.com/smith.gif' ) {
      $(this).attr('src', 'http://example.com/johnson.gif');
  }
  if ( curSrc === 'http://example.com/williams.gif' ) {
      $(this).attr('src', 'http://example.com/brown.gif');
  }
});

Eclipse, regular expression search and replace

At least at STS (SpringSource Tool Suite) groups are numbered starting form 0, so replace string will be

replace: ((TypeName)$0)

Pagination on a list using ng-repeat

I've built a module that makes in-memory pagination incredibly simple.

It allows you to paginate by simply replacing ng-repeat with dir-paginate, specifying the items per page as a piped filter, and then dropping the controls wherever you like in the form of a single directive, <dir-pagination-controls>

To take the original example asked by Tomarto, it would look like this:

<ul class='phones'>
    <li class='thumbnail' dir-paginate='phone in phones | filter:searchBar | orderBy:orderProp | limitTo:limit | itemsPerPage: limit'>
            <a href='#/phones/{{phone.id}}' class='thumb'><img ng-src='{{phone.imageUrl}}'></a>
            <a href='#/phones/{{phone.id}}'>{{phone.name}}</a>
            <p>{{phone.snippet}}</p>
    </li>
</ul>

<dir-pagination-controls></dir-pagination-controls>

There is no need for any special pagination code in your controller. It's all handled internally by the module.

Demo: http://plnkr.co/edit/Wtkv71LIqUR4OhzhgpqL?p=preview

Source: dirPagination of GitHub

How can I generate a tsconfig.json file?

I recommend to uninstall typescript first with the command:

npm uninstall -g typescript

then use the chocolatey package in order to run:

choco install typescript

in PowerShell.

What is the purpose of Android's <merge> tag in XML layouts?

Another reason to use merge is when using custom viewgroups in ListViews or GridViews. Instead of using the viewHolder pattern in a list adapter, you can use a custom view. The custom view would inflate an xml whose root is a merge tag. Code for adapter:

public class GridViewAdapter extends BaseAdapter {
     // ... typical Adapter class methods
     @Override
     public View getView(int position, View convertView, ViewGroup parent) {
        WallpaperView wallpaperView;
        if (convertView == null)
           wallpaperView = new WallpaperView(activity);
        else
            wallpaperView = (WallpaperView) convertView;

        wallpaperView.loadWallpaper(wallpapers.get(position), imageWidth);
        return wallpaperView;
    }
}

here is the custom viewgroup:

public class WallpaperView extends RelativeLayout {

    public WallpaperView(Context context) {
        super(context);
        init(context);
    }
    // ... typical constructors

    private void init(Context context) {
        View.inflate(context, R.layout.wallpaper_item, this);
        imageLoader = AppController.getInstance().getImageLoader();
        imagePlaceHolder = (ImageView) findViewById(R.id.imgLoader2);
        thumbnail = (NetworkImageView) findViewById(R.id.thumbnail2);
        thumbnail.setScaleType(ImageView.ScaleType.CENTER_CROP);
    }

    public void loadWallpaper(Wallpaper wallpaper, int imageWidth) {
        // ...some logic that sets the views
    }
}

and here is the XML:

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <ImageView
        android:id="@+id/imgLoader"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_centerInParent="true"
        android:src="@drawable/ico_loader" />

    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/thumbnail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</merge>

Allow Access-Control-Allow-Origin header using HTML5 fetch API

Solution to resolve issue in Local env's

I had my front-end code running in http://localhost:3000 and my API(Backend code) running at http://localhost:5000

Was using fetch API to call the API. Initially, it was throwing "cors" error. Then added this below code in my Backend API code, allowing origin and header from anywhere.

let allowCrossDomain = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', "*");
  res.header('Access-Control-Allow-Headers', "*");
  next();
}
app.use(allowCrossDomain);

However you must restrict origins in case of other environments like stage, prod.

Strictly NO for higher environments.

ASP.NET MVC 5 - Identity. How to get current ApplicationUser

My mistake, I shouldn't have used a method inside a LINQ query.

Correct code:

using Microsoft.AspNet.Identity;


string currentUserId = User.Identity.GetUserId();
ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);

Centering brand logo in Bootstrap Navbar

Try this:

.navbar {
    position: relative;
}
.brand {
    position: absolute;
    left: 50%;
    margin-left: -50px !important;  /* 50% of your logo width */
    display: block;
}

Centering your logo by 50% and minus half of your logo width so that it won't have problem when zooming in and out.

See fiddle

Jquery If radio button is checked

$("input").bind('click', function(e){
   if ($(this).val() == 'Yes') {
        $("body").append('whatever');
   }
});

Parsing CSV / tab-delimited txt file with Python

Start by turning the text into a list of lists. That will take care of the parsing part:

lol = list(csv.reader(open('text.txt', 'rb'), delimiter='\t'))

The rest can be done with indexed lookups:

d = dict()
key = lol[6][0]      # cell A7
value = lol[6][3]    # cell D7
d[key] = value       # add the entry to the dictionary
 ...

keyword not supported data source

I had this problem when I started using Entity Framework, it happened when I did not change the old SQL server connection to EntityFrameWork connection.

Solution: in the file where connection is made through web.config file "add name="Entities" connectionString=XYZ", make sure you are referring to the correct connection, in my case I had to do this

        public static string MyEntityFrameworkConnection
    {
        get
        {
             return ConfigurationManager.ConnectionStrings["Entities"].ConnectionString;
        }

    }

call MyEntityFrameworkConnection whenever connection need to be established.

private string strConnection= Library.DataAccessLayer.DBfile.AdoSomething.MyEntityFrameworkConnection;

note: the connection in web.config file will be generated automatically when adding Entity model to the solution.

builder for HashMap

There's ImmutableMap.builder() in Guava.

MySQL timezone change?

If you have the SUPER privilege, you can set the global server time zone value at runtime with this statement:

mysql> SET GLOBAL time_zone = timezone;

Given a DateTime object, how do I get an ISO 8601 date in string format?

DateTime.UtcNow.ToString("s", System.Globalization.CultureInfo.InvariantCulture) should give you what you are looking for as the "s" format specifier is described as a sortable date/time pattern; conforms to ISO 8601.

EDIT: To get the additional Z at the end as the OP requires, use "o" instead of "s".

How to set host_key_checking=false in ansible inventory file?

I could not use:

ansible_ssh_common_args='-o StrictHostKeyChecking=no'

in inventory file. It seems ansible does not consider this option in my case (ansible 2.0.1.0 from pip in ubuntu 14.04)

I decided to use:

server ansible_host=192.168.1.1 ansible_ssh_common_args= '-o UserKnownHostsFile=/dev/null'

It helped me.

Also you could set this variable in group instead for each host:

[servers_group:vars]
ansible_ssh_common_args='-o UserKnownHostsFile=/dev/null'

Eclipse C++ : "Program "g++" not found in PATH"

For me it got fixed with:

Go to: Window -> Preferences -> C/C++ -> Build -> Environment

Then press "Add..."

Name: MINGW_HOME

Value: C:\MinGW (yours might be different if you choose a custom path)

Hit "Apply and Close"

Now, it shoud work if you did everything correctly

Python string to unicode

Decode it with the unicode-escape codec:

>>> a="Hello\u2026"
>>> a.decode('unicode-escape')
u'Hello\u2026'
>>> print _
Hello…

This is because for a non-unicode string the \u2026 is not recognised but is instead treated as a literal series of characters (to put it more clearly, 'Hello\\u2026'). You need to decode the escapes, and the unicode-escape codec can do that for you.

Note that you can get unicode to recognise it in the same way by specifying the codec argument:

>>> unicode(a, 'unicode-escape')
u'Hello\u2026'

But the a.decode() way is nicer.

"id cannot be resolved or is not a field" error?

I also had this error when I was working in a Java class once. My problem was simply that my xml file, with the references in it, was not saved. If you have both the xml file and java class open in tabs, check to make sure the xml file name in the tab doesn't have a * by it.

Hope this helps.

How to get the index of a maximum element in a NumPy array along one axis

>>> import numpy as np
>>> a = np.array([[1,2,3],[4,3,1]])
>>> i,j = np.unravel_index(a.argmax(), a.shape)
>>> a[i,j]
4

Declaring & Setting Variables in a Select Statement

I have tried this and it worked:

define PROPp_START_DT = TO_DATE('01-SEP-1999')

select * from proposal where prop_start_dt = &PROPp_START_DT

 

Find maximum value of a column and return the corresponding row values using Pandas

The country and place is the index of the series, if you don't need the index, you can set as_index=False:

df.groupby(['country','place'], as_index=False)['value'].max()

Edit:

It seems that you want the place with max value for every country, following code will do what you want:

df.groupby("country").apply(lambda df:df.irow(df.value.argmax()))

ReactJS - How to use comments?

According to React's Documentation, you can write comments in JSX like so:

One-line Comment:

<div>
  {/* Comment goes here */}
  Hello, {name}!
</div>

Multi-line Comments:

<div>
  {/* It also works 
  for multi-line comments. */}
  Hello, {name}! 
</div>

Check mySQL version on Mac 10.8.5

Or just call mysql command with --version option.

mysql --version

How to align an input tag to the center without specifying the width?

You need to put the text-align:center on the containing div, not on the input itself.

Gradle finds wrong JAVA_HOME even though it's correctly set

I had the same problem, but I didnt find export command in line 70 in gradle file for the latest version 2.13, but I understand a silly mistake there, that is following,

If you don't find line 70 with export command in gradle file in your gradle folder/bin/ , then check your ~/.bashrc, if you find export JAVA_HOME==/usr/lib/jvm/java-7-openjdk-amd64/bin/java, then remove /bin/java from this line, like JAVA_HOME==/usr/lib/jvm/java-7-openjdk-amd64, and it in path>>> instead of this export PATH=$PATH:$HOME/bin:JAVA_HOME/, it will be export PATH=$PATH:$HOME/bin:JAVA_HOME/bin/java. Then run source ~/.bashrc.

The reason is, if you check your gradle file, you will find in line 70 (if there's no export command) or in line 75,

JAVACMD="$JAVA_HOME/bin/java"
    fi
    if [ ! -x "$JAVACMD" ] ; then
        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME

That means /bin/java is already there, so it needs to be substracted from JAVA_HOME path.

That happened in my case.

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

Angular is automatically adding 'ng-invalid' class on 'required' fields

the accepted answer is correct.. for mobile you can also use this (ng-touched rather ng-dirty)

input.ng-invalid.ng-touched{
  border-bottom: 1px solid #e74c3c !important; 
}

Java switch statement multiple cases

It is possible to handle this using Vavr library

import static io.vavr.API.*;
import static io.vavr.Predicates.*;

Match(variable).of(
    Case($(isIn(5, 6, ... , 100)), () -> doSomething()),
    Case($(), () -> handleCatchAllCase())
);

This is of course only slight improvement since all cases still need to be listed explicitly. But it is easy to define custom predicate:

public static <T extends Comparable<T>> Predicate<T> isInRange(T lower, T upper) {
    return x -> x.compareTo(lower) >= 0 && x.compareTo(upper) <= 0;
}

Match(variable).of(
    Case($(isInRange(5, 100)), () -> doSomething()),
    Case($(), () -> handleCatchAllCase())
);

Match is an expression so here it returns something like Runnable instance instead of invoking methods directly. After match is performed Runnable can be executed.

For further details please see official documentation.

What is a Data Transfer Object (DTO)?

DefN

A DTO is a hardcoded data model. It only solves the problem of modeling a data record handled by a hardcoded production process, where all fields are known at compile-time and therefore accessed via strongly typed properties.

In contrast, a dynamic model or "property bag" solves the problem of modeling a data record when the production process is created at runtime.

The Cvar

A DTO can be modeled with fields or properties, but someone invented a very useful data container called the Cvar. It is a reference to a value. When a DTO is modeled with what I call reference properties, modules can be configured to share heap memory and thereby collaboratively work on it. This completely eliminates parameter passing and O2O communication from your code. In other words, DTOs having reference properties allow code to achieve zero coupling.

    class Cvar { ... }

    class Cvar<T> : Cvar
    {
        public T Value { get; set; }
    }

    class MyDTO
    {
        public Cvar<int> X { get; set; }
        public Cvar<int> Y { get; set; }
        public Cvar<string> mutableString { get; set; } // >;)
    }

Source: http://www.powersemantics.com/

Dynamic DTOs are a necessary component for dynamic software. To instantiate a dynamic process, one compiler step is to bind each machine in the script to the reference properties the script defines. A dynamic DTO is built by adding the Cvars to a collection.

    // a dynamic DTO
    class CvarRegistry : Dictionary<string, Cvar> { }

Contentions

Note: because Wix labeled the use of DTOs for organizing parameters as an "anti-pattern", I will give an authoritative opinion.

    return View(model);  // MVC disagrees

My collaborative architecture replaces design patterns. Refer to my web articles.

Parameters provide immediate control of a stack frame machine. If you use continuous control and therefore do not need immediate control, your modules do not need parameters. My architecture has none. In-process configuration of machines (methods) adds complexity but also value (performance) when the parameters are value types. However, reference type parameters make the consumer cause cache misses to get the values off the heap anyway -- therefore, just configure the consumer with reference properties. Fact from mechanical engineering: reliance on parameters is a kind of preoptimization, because processing (making components) itself is waste. Refer to my W article for more information. http://www.powersemantics.com/w.html.

Fowler and company might realize the benefits of DTOs outside of distributed architecture if they had ever known any other architecture. Programmers only know distributed systems. Integrated collaborative systems (aka production aka manufacturing) are something I had to claim as my own architecture, because I am the first to write code this way.

Some consider the DTO an anemic domain model, meaning it lacks functionality, but this assumes an object must own the data it interacts with. This conceptual model then forces you to deliver the data between objects, which is the model for distributed processing. However on a manufacturing line, each step can access the end product and change it without owning or controlling it. That's the difference between distributed and integrated processing. Manufacturing separates the product from operations and logistics.

There's nothing inherently wrong with modeling processing as a bunch of useless office workers who e-mail work to one another without keeping an e-mail trail, except for all the extra work and headache it creates in handling logistics and return problems. A properly modeled distributed process attaches a document (active routing) to the product describing what operations it came from and will go to. The active routing is a copy of the process source routing, which is written before the process begins. In the event of a defect or other emergency change, the active routing is modified to include the operation steps it will be sent to. This then accounts for all the labor which went into production.

SQL Server - stop or break execution of a SQL script

This was my solution:

...

BEGIN
    raiserror('Invalid database', 15, 10)
    rollback transaction
    return
END

Why can't I use the 'await' operator within the body of a lock statement?

This is just an extension to this answer.

using System;
using System.Threading;
using System.Threading.Tasks;

public class SemaphoreLocker
{
    private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);

    public async Task LockAsync(Func<Task> worker)
    {
        await _semaphore.WaitAsync();
        try
        {
            await worker();
        }
        finally
        {
            _semaphore.Release();
        }
    }

    // overloading variant for non-void methods with return type (generic T)
    public async Task<T> LockAsync<T>(Func<Task<T>> worker)
    {
        await _semaphore.WaitAsync();

        T result = default;

        try
        {
            result = await worker();
        }
        finally
        {
            _semaphore.Release();
        }

        return result;
    }
}

Usage:

public class Test
{
    private static readonly SemaphoreLocker _locker = new SemaphoreLocker();

    public async Task DoTest()
    {
        await _locker.LockAsync(async () =>
        {
            // [async] calls can be used within this block 
            // to handle a resource by one thread. 
        });
        // OR
        var result = await _locker.LockAsync(async () =>
        {
            // [async] calls can be used within this block 
            // to handle a resource by one thread. 
        }
    }
}

Trying to check if username already exists in MySQL database using PHP

change your query to like.

$username = mysql_real_escape_string($username); // escape string before passing it to query.
$query = mysql_query("SELECT username FROM Users WHERE username='".$username."'");

However, MySQL is deprecated. You should instead use MySQLi or PDO

Is Java RegEx case-insensitive?

If your whole expression is case insensitive, you can just specify the CASE_INSENSITIVE flag:

Pattern.compile(regexp, Pattern.CASE_INSENSITIVE)

MySQL select statement with CASE or IF ELSEIF? Not sure how to get the result

Try this query -

SELECT 
  t2.company_name,
  t2.expose_new,
  t2.expose_used,
  t1.title,
  t1.seller,
  t1.status,
  CASE status
      WHEN 'New' THEN t2.expose_new
      WHEN 'Used' THEN t2.expose_used
      ELSE NULL
  END as 'expose'
FROM
  `products` t1
JOIN manufacturers t2
  ON
    t2.id = t1.seller
WHERE
  t1.seller = 4238

jQuery: Performing synchronous AJAX requests

how remote is that url ? is it from the same domain ? the code looks okay

try this

$.ajaxSetup({async:false});
$.get(remote_url, function(data) { remote = data; });
// or
remote = $.get(remote_url).responseText;

Easiest way to compare arrays in C#

I was looking to determine if two sets had equivalent contents, in any order. That meant that, for each element in set A there were equal numbers of elements with that value in both sets. I wanted to account for duplicates (so {1,2,2,3} and {1,2,3,3} should not be considered "the same").

This is what I came up with (note that IsNullOrEmpty is another static extension method that returns true if the enumerable is null or has 0 elements):

    public static bool HasSameContentsAs<T>(this IEnumerable<T> source, IEnumerable<T> target) 
        where T : IComparable
    {
        //If our source is null or empty, then it's just a matter of whether or not the target is too
        if (source.IsNullOrEmpty())
            return target.IsNullOrEmpty();

        //Otherwise, if the target is null/emtpy, they can't be equal
        if (target.IsNullOrEmpty())
            return false;

        //Neither is null or empty, so we'll compare contents.  To account for multiples of 
        //a given value (ex. 1,2,2,3 and 1,1,2,3 are not equal) we'll group the first set
        foreach (var group in source.GroupBy(s => s))
        {
            //If there are a different number of elements in the target set, they don't match
            if (target.Count(t => t.Equals(group.Key)) != group.Count())
                return false;
        }

        //If we got this far, they have the same contents
        return true;
    }

How to select data from 30 days?

You should be using DATEADD is Sql server so if try this simple select you will see the affect

Select DATEADD(Month, -1, getdate())

Result

2013-04-20 14:08:07.177

in your case try this query

SELECT name
FROM (
SELECT name FROM 
Hist_answer
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
UNION ALL
SELECT name FROM 
Hist_internet
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
) x
GROUP BY name ORDER BY name

Load image with jQuery and append it to the DOM

var img = new Image();

$(img).load(function(){

  $('.container').append($(this));

}).attr({

  src: someRemoteImage

}).error(function(){
  //do something if image cannot load
});

starting file download with JavaScript

I suggest to make an invisible iframe on the page and set it's src to url that you've received from the server - download will start without page reloading.

Or you can just set the current document.location.href to received url address. But that's can cause for user to see an error if the requested document actually does not exists.

JavaScript and Threads

With HTML5 specification you do not need to write too much JS for the same or find some hacks.

One of the feature introduced in HTML5 is Web Workers which is JavaScript running in the background,independently of other scripts, without affecting the performance of the page.

It is supported in almost all browsers :

Chrome - 4.0+

IE - 10.0+

Mozilla - 3.5+

Safari - 4.0+

Opera - 11.5+

vbscript output to console

You mean:

Wscript.Echo "Like this?"

If you run that under wscript.exe (the default handler for the .vbs extension, so what you'll get if you double-click the script) you'll get a "MessageBox" dialog with your text in it. If you run that under cscript.exe you'll get output in your console window.

How to push files to an emulator instance using Android Studio

Android Device monitor is no longer available in android studio.

If you are using android studio 3.0 and above.

  1. Go to "Device File Explorer" which is on the bottom right of android studio.
  2. If you have more than one device connected, select the device you want from the drop-down list on top.
  3. mnt>sdcard is the location for SD card on the emulator.
  4. Right click on the folder and click Upload. See the image below.

Note: You can upload folder as well not just individual files.

Device File Explorer

window.onload vs <body onload=""/>

I prefer, generally, to not use the <body onload=""> event. I think it's cleaner to keep behavior separated from content as much as possible.

That said, there are occasions (usually pretty rare for me) where using body onload can give a slight speed boost.

I like to use Prototype so I generally put something like this in the <head> of my page:

document.observe("dom:loaded", function(){
  alert('The DOM is loaded!');
});

or

Event.observe(window, 'load', function(){
  alert('Window onload');
});

The above are tricks I learned here. I'm very fond of the concept of attach event handlers outside of the HTML.

(Edit to correct spelling mistake in code.)

Storing Data in MySQL as JSON

JSON is a valid datatype in PostgreSQL database as well. However, MySQL database has not officially supported JSON yet. But it's baking: http://mysqlserverteam.com/json-labs-release-native-json-data-type-and-binary-format/

I also agree that there are many valid cases that some data is better be serialized to a string in a database. The primary reason might be when it's not regularly queried, and when it's own schema might change - you don't want to change the database schema corresponding to that. The second reason is when the serialized string is directly from external sources, you may not want to parse all of them and feed in the database at any cost until you use any. So I'll be waiting for the new MySQL release to support JSON since it'll be easier for switching between different database then.

Function overloading in Javascript - Best practices

You can user the 'addMethod' from John Resig. With this method you can "overload" methods based on arguments count.

// addMethod - By John Resig (MIT Licensed)
function addMethod(object, name, fn){
    var old = object[ name ];
    object[ name ] = function(){
        if ( fn.length == arguments.length )
            return fn.apply( this, arguments );
        else if ( typeof old == 'function' )
            return old.apply( this, arguments );
    };
}

I have also created an alternative to this method that uses caching to hold the variations of the function. The differencies are described here

// addMethod - By Stavros Ioannidis
function addMethod(obj, name, fn) {
  obj[name] = obj[name] || function() {
    // get the cached method with arguments.length arguments
    var method = obj[name].cache[arguments.length];

    // if method exists call it 
    if ( !! method)
      return method.apply(this, arguments);
    else throw new Error("Wrong number of arguments");
  };

  // initialize obj[name].cache
  obj[name].cache = obj[name].cache || {};

  // Check if a method with the same number of arguments exists  
  if ( !! obj[name].cache[fn.length])
    throw new Error("Cannot define multiple '" + name +
      "' methods with the same number of arguments!");

  // cache the method with fn.length arguments
  obj[name].cache[fn.length] = function() {
    return fn.apply(this, arguments);
  };
}

Can a table row expand and close?

You could do it like this:

HTML

<table>
    <tr>
        <td>Cell 1</td>
        <td>Cell 2</td>
        <td>Cell 3</td>
        <td>Cell 4</td>
        <td><a href="#" id="show_1">Show Extra</a></td>
    </tr>
    <tr>
        <td colspan="5">
            <div id="extra_1" style="display: none;">
                <br>hidden row
                <br>hidden row
                <br>hidden row
            </div>
        </td>
    </tr>
</table>

jQuery

$("a[id^=show_]").click(function(event) {
    $("#extra_" + $(this).attr('id').substr(5)).slideToggle("slow");
    event.preventDefault();
});

See a demo on JSFiddle

How to check existence of user-define table type in SQL Server 2008?

IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = 'MyType')
    --stuff

sys.types... they aren't schema-scoped objects so won't be in sys.objects

Update, Mar 2013

You can use TYPE_ID too

Where is the web server root directory in WAMP?

If you use Bitnami installer for wampstack, go to:

c:/Bitnami/wampstack-5.6.24-0/apache/conf (of course your version number may be different)

Open the file: httpd.conf in a text editor like Visual Studio code or Notepad ++

Do a search for "DocumentRoot". See image.

Screenshot

You will be able to change the directory in this file.

Positive Number to Negative Number in JavaScript?

The reverse of abs is Math.abs(num) * -1.

Accessing bash command line args $@ vs $*

A nice handy overview table from the Bash Hackers Wiki:

Syntax Effective result
$* $1 $2 $3 … ${N}
$@ $1 $2 $3 … ${N}
"$*" "$1c$2c$3c…c${N}"
"$@" "$1" "$2" "$3" … "${N}"

where c in the third row is the first character of $IFS, the Input Field Separator, a shell variable.

If the arguments are to be stored in a script variable and the arguments are expected to contain spaces, I wholeheartedly recommend employing a "$*" trick with the input field separator set to tab IFS=$'\t'.

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

Here you go:

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

        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

        String oeStartDateStr = "04/01/";
        String oeEndDateStr = "11/14/";

        Calendar cal = Calendar.getInstance();
        Integer year = cal.get(Calendar.YEAR);

        oeStartDateStr = oeStartDateStr.concat(year.toString());
        oeEndDateStr = oeEndDateStr.concat(year.toString());

        Date startDate = sdf.parse(oeStartDateStr);
        Date endDate = sdf.parse(oeEndDateStr);
        Date d = new Date();
        String currDt = sdf.format(d);


        if((d.after(startDate) && (d.before(endDate))) || (currDt.equals(sdf.format(startDate)) ||currDt.equals(sdf.format(endDate)))){
            System.out.println("Date is between 1st april to 14th nov...");
        }
        else{
            System.out.println("Date is not between 1st april to 14th nov...");
        }
    }

How to call a javaScript Function in jsp on page load without using <body onload="disableView()">

Either use window.onload this way

<script>
    window.onload = function() {
        // ...
    }
</script>

or alternatively

<script>
    window.onload = functionName;
</script>

(yes, without the parentheses)


Or just put the script at the very bottom of page, right before </body>. At that point, all HTML DOM elements are ready to be accessed by document functions.

<body>
    ...

    <script>
        functionName();
    </script>
</body>

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

I know of enabling or disabling wifi:

WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(status);

where status may be true or false as per requirement.

Edit:

You also need the following permissions in your manifest file:

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

Remove all unused resources from an android project

shift double click on Windows then type "unused", you will find an option Remove unused Resources,
also

 android {
        buildTypes {
            release {
                minifyEnabled true
                shrinkResources true
            }
   }
}

when you set these settings on, AS will automatically remove unused resources.

Where is the Docker daemon log?

Also you can see logs by this command:

docker service ps --no-trunc {serviceName}

How to set array length in c# dynamically

Use this:

 Array.Resize(ref myArr, myArr.Length + 5);

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

A null value cannot be assigned to a primitive type, like int, long, boolean, etc. If the database column that corresponds to the field in your object can be null, then your field should be a wrapper class, like Integer, Long, Boolean, etc.

The danger is that your code will run fine if there are no nulls in the DB, but will fail once nulls are inserted.

And you can always return the primitive type from the getter. Ex:

  private Integer num;

  public void setNum(Integer i) {
    this.num = i;
  }

  public int getNum() {
    return this.num;
  }

But in most cases you will want to return the wrapper class.

So either set your DB column to not allow nulls, or use a wrapper class.

How to transition to a new view controller with code only using Swift

Your code is just fine. The reason you're getting a black screen is because there's nothing on your second view controller.

Try something like:

secondViewController.view.backgroundColor = UIColor.redColor();

Now the view controller it shows should be red.

To actually do something with secondViewController, create a subclass of UIViewController and instead of

let secondViewController:UIViewController = UIViewController()

create an instance of your second view controller:

//If using code
let secondViewController = MyCustomViewController.alloc()

//If using storyboard, assuming you have a view controller with storyboard ID "MyCustomViewController"
let secondViewController = self.storyboard.instantiateViewControllerWithIdentifier("MyCustomViewController") as UIViewController

Eclipse DDMS error "Can't bind to local 8600 for debugger"

Maybe it's too late for an answer to this question but i think i have found a fix for it, what i noticed is within the info.plist file > JVMoption (Mac) with in the application package there is two version of java i.e it was showing "1.6*,1.7+" so i just changed it to "1.8*" which is my current java version and now its working for me

PHP Multidimensional Array Searching (Find key by specific value)

Use this function:

function searchThroughArray($search,array $lists){
        try{
            foreach ($lists as $key => $value) {
                if(is_array($value)){
                    array_walk_recursive($value, function($v, $k) use($search ,$key,$value,&$val){
                        if(strpos($v, $search) !== false )  $val[$key]=$value;
                    });
            }else{
                    if(strpos($value, $search) !== false )  $val[$key]=$value;
                }

            }
            return $val;

        }catch (Exception $e) {
            return false;
        }
    }

and call function.

print_r(searchThroughArray('breville-one-touch-tea-maker-BTM800XL',$products));

Dynamically Add Images React Webpack

Using url-loader, described here (SurviveJS - Loading Images), you can then use in your code :

import LogoImg from 'YOUR_PATH/logo.png';

and

<img src={LogoImg}/>

Edit: a precision, images are inlined in the js archive with this technique. It can be worthy for small images, but use the technique wisely.

How can I set the default value for an HTML <select> element?

If you are in react you can use defaultValue as attribute instead of value in the select tag.

How to get row count in sqlite using Android?

Using DatabaseUtils.queryNumEntries():

public long getProfilesCount() {
    SQLiteDatabase db = this.getReadableDatabase();
    long count = DatabaseUtils.queryNumEntries(db, TABLE_NAME);
    db.close();
    return count;
}

or (more inefficiently)

public int getProfilesCount() {
    String countQuery = "SELECT  * FROM " + TABLE_NAME;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int count = cursor.getCount();
    cursor.close();
    return count;
}

In Activity:

int profile_counts = db.getProfilesCount();
    db.close();

Deep copy of a dict in python

A simpler (in my view) solution is to create a new dictionary and update it with the contents of the old one:

my_dict={'a':1}

my_copy = {}

my_copy.update( my_dict )

my_dict['a']=2

my_dict['a']
Out[34]: 2

my_copy['a']
Out[35]: 1

The problem with this approach is it may not be 'deep enough'. i.e. is not recursively deep. good enough for simple objects but not for nested dictionaries. Here is an example where it may not be deep enough:

my_dict1={'b':2}

my_dict2={'c':3}

my_dict3={ 'b': my_dict1, 'c':my_dict2 }

my_copy = {}

my_copy.update( my_dict3 )

my_dict1['b']='z'

my_copy
Out[42]: {'b': {'b': 'z'}, 'c': {'c': 3}}

By using Deepcopy() I can eliminate the semi-shallow behavior, but I think one must decide which approach is right for your application. In most cases you may not care, but should be aware of the possible pitfalls... final example:

import copy

my_copy2 = copy.deepcopy( my_dict3 )

my_dict1['b']='99'

my_copy2
Out[46]: {'b': {'b': 'z'}, 'c': {'c': 3}}

What is “2's Complement”?

You can also use an online calculator to calculate the two's complement binary representation of a decimal number: http://www.convertforfree.com/twos-complement-calculator/

It says that TypeError: document.getElementById(...) is null

In your code, you can find this function:

// Update a particular HTML element with a new value
function updateHTML(elmId, value) {
  document.getElementById(elmId).innerHTML = value;
}

Later on, you call this function with several params:

updateHTML("videoCurrentTime", secondsToHms(ytplayer.getCurrentTime())+' /');
updateHTML("videoDuration", secondsToHms(ytplayer.getDuration()));
updateHTML("bytesTotal", ytplayer.getVideoBytesTotal());
updateHTML("startBytes", ytplayer.getVideoStartBytes());
updateHTML("bytesLoaded", ytplayer.getVideoBytesLoaded());
updateHTML("volume", ytplayer.getVolume());

The first param is used for the "getElementById", but the elements with ID "bytesTotal", "startBytes", "bytesLoaded" and "volume" don't exist. You'll need to create them, since they'll return null.

Excel VBA - select multiple columns not in sequential order

Working on a project I was stuck for some time on this concept - I ended up with a similar answer to Method 1 by @GSerg that worked great. Essentially I defined two formula ranges (using a few variables) and then used the Union concept. My example is from a larger project that I'm working on but hopefully the portion of code below can help some other people who might not know how to use the Union concept in conjunction with defined ranges and variables. I didn't include the entire code because at this point it's fairly long - if anyone wants more insight feel free to let me know.

First I declared all my variables as Public

Then I defined/set each variable

Lastly I set a new variable "SelectRanges" as the Union between the two other FormulaRanges

Public r As Long
Public c As Long
Public d As Long
Public FormulaRange3 As Range
Public FormulaRange4 As Range
Public SelectRanges As Range

With Sheet8




  c = pvt.DataBodyRange.Columns.Count + 1

  d = 3

  r = .Cells(.Rows.Count, 1).End(xlUp).Row

Set FormulaRange3 = .Range(.Cells(d, c + 2), .Cells(r - 1, c + 2))
    FormulaRange3.NumberFormat = "0"
    Set FormulaRange4 = .Range(.Cells(d, c + c + 2), .Cells(r - 1, c + c + 2))
    FormulaRange4.NumberFormat = "0"
    Set SelectRanges = Union(FormulaRange3, FormulaRange4)

What is the difference between .py and .pyc files?

.pyc contain the compiled bytecode of Python source files. The Python interpreter loads .pyc files before .py files, so if they're present, it can save some time by not having to re-compile the Python source code. You can get rid of them if you want, but they don't cause problems, they're not big, and they may save some time when running programs.

ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

As the error says your router link should match the existing routes configured

It should be just routerLink="/about"

Bootstrap onClick button event

If, like me, you had dynamically created buttons on your page, the

$("#your-bs-button's-id").on("click", function(event) {
                       or
$(".your-bs-button's-class").on("click", function(event) {

methods won't work because they only work on current elements (not future elements). Instead you need to reference a parent item that existed at the initial loading of the web page.

$(document).on("click", "#your-bs-button's-id", function(event) {
                       or more generally
$("#pre-existing-element-id").on("click", ".your-bs-button's-class", function(event) {

There are many other references to this issue on stack overflow here and here.

php how to go one level up on dirname(__FILE__)

You could use PHP's dirname function. <?php echo dirname(__DIR__); ?>. That will give you the name of the parent directory of __DIR__, which stores the current directory.

Get safe area inset top and bottom heights

A more rounded approach

  import SnapKit

  let containerView = UIView()
  containerView.backgroundColor = .red
  self.view.addSubview(containerView)
  containerView.snp.remakeConstraints { (make) -> Void in
        make.width.top.equalToSuperView()
        make.top.equalTo(self.view.safeArea.top)
        make.bottom.equalTo(self.view.safeArea.bottom)
  }




extension UIView {
    var safeArea: ConstraintBasicAttributesDSL {
        if #available(iOS 11.0, *) {
            return self.safeAreaLayoutGuide.snp
        }
        return self.snp
    }


    var isIphoneX: Bool {

        if #available(iOS 11.0, *) {
            if topSafeAreaInset > CGFloat(0) {
                return true
            } else {
                return false
            }
        } else {
            return false
        }

    }

    var topSafeAreaInset: CGFloat {
        let window = UIApplication.shared.keyWindow
        var topPadding: CGFloat = 0
        if #available(iOS 11.0, *) {
            topPadding = window?.safeAreaInsets.top ?? 0
        }

        return topPadding
    }

    var bottomSafeAreaInset: CGFloat {
        let window = UIApplication.shared.keyWindow
        var bottomPadding: CGFloat = 0
        if #available(iOS 11.0, *) {
            bottomPadding = window?.safeAreaInsets.bottom ?? 0
        }

        return bottomPadding
    }
}

Case objects vs Enumerations in Scala

I've seen various versions of making a case class mimic an enumeration. Here is my version:

trait CaseEnumValue {
    def name:String
}

trait CaseEnum {
    type V <: CaseEnumValue
    def values:List[V]
    def unapply(name:String):Option[String] = {
        if (values.exists(_.name == name)) Some(name) else None
    }
    def unapply(value:V):String = {
        return value.name
    }
    def apply(name:String):Option[V] = {
        values.find(_.name == name)
    }
}

Which allows you to construct case classes that look like the following:

abstract class Currency(override name:String) extends CaseEnumValue {
}

object Currency extends CaseEnum {
    type V = Site
    case object EUR extends Currency("EUR")
    case object GBP extends Currency("GBP")
    var values = List(EUR, GBP)
}

Maybe someone could come up with a better trick than simply adding a each case class to the list like I did. This was all I could come up with at the time.

Python: Open file in zip without temporarily extracting it

In theory, yes, it's just a matter of plugging things in. Zipfile can give you a file-like object for a file in a zip archive, and image.load will accept a file-like object. So something like this should work:

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
try:
    image = pygame.image.load(imgfile, 'img_01.png')
finally:
    imgfile.close()

How do I compare 2 rows from the same table (SQL Server)?

You can join a table to itself as many times as you require, it is called a self join.

An alias is assigned to each instance of the table (as in the example below) to differentiate one from another.

SELECT a.SelfJoinTableID
FROM   dbo.SelfJoinTable a
       INNER JOIN dbo.SelfJoinTable b
         ON a.SelfJoinTableID = b.SelfJoinTableID
       INNER JOIN dbo.SelfJoinTable c
         ON a.SelfJoinTableID = c.SelfJoinTableID
WHERE  a.Status = 'Status to filter a'
       AND b.Status = 'Status to filter b'
       AND c.Status = 'Status to filter c' 

How to find encoding of a file via script on Linux?

uchardet - An encoding detector library ported from Mozilla.

Usage:

~> uchardet file.java 
UTF-8

Various Linux distributions (Debian/Ubuntu, OpenSuse-packman, ...) provide binaries.

Spring Boot - Loading Initial Data

I solved similar problem this way:

@Component
public class DataLoader {

    @Autowired
    private UserRepository userRepository;

    //method invoked during the startup
    @PostConstruct
    public void loadData() {
        userRepository.save(new User("user"));
    }

    //method invoked during the shutdown
    @PreDestroy
    public void removeData() {
        userRepository.deleteAll();
    }
}

delete a column with awk or sed

This might work for you (GNU sed):

sed -i -r 's/\S+//3' file

If you want to delete the white space before the 3rd field:

sed -i -r 's/(\s+)?\S+//3' file

Combining COUNT IF AND VLOOK UP EXCEL

You can combine this all into one formula, but you need to use a regular IF first to find out if the VLOOKUP came back with something, then use your COUNTIF if it did.

=IF(ISERROR(VLOOKUP(B1,Sheet2!A1:A9,1,FALSE)),"Not there",COUNTIF(Sheet2!A1:A9,B1))

In this case, Sheet2-A1:A9 is the range I was searching, and Sheet1-B1 had the value I was looking for ("To retire" in your case).

How do I create ColorStateList programmatically?

Sometimes this will be enough:

int colorInt = getResources().getColor(R.color.ColorVerificaLunes);
ColorStateList csl = ColorStateList.valueOf(colorInt);

position: fixed doesn't work on iPad and iPhone

This seems to work for Ionic5 on iphone 6 Plus on iOS 12.4.2

.large_player {
    float: left;
      bottom: 0;
      width: 100%;
      position: fixed;
      background-color: white;
      border-top: black 1px solid;    
      height: 14rem;
      z-index: 100;
      transform: translate3d(0,0,0);
  }

The transform tag makes it work, but it also seems a little clunky in how the scroll works, it is seems to redraw the 'on top' element after it's all moved and sort of resets and makes it jump a little.

Or, you could also use this tag option as well, position: -webkit-sticky;, but then you won't get, or may run in to trouble with WPA/browser or Android builds while having to do version checking and have multiple CSS tags.

.large_player {
    float: left;
      bottom: 0;
      width: 100%;
      position: -webkit-sticky;
      background-color: white;
      border-top: black 1px solid;    
      height: 14rem;
      z-index: 100; 
  }

I don't know at what point it was fixed, but later iOS phones work without the transform tag. I don't know if it's the iOS version, or the phone.

As most iOS devices are usually on the most recent iOS version, it's pretty safe with go with a weird work around - such as using the transform tag, rather than building in a quirky detection routine for the sake of less than 1% of users.

Update:

After thinking about this answer further, this is just another way of doing this by platform for ionic5+:

.TS

import {Platform } from '@ionic/angular';

constructor(
public platform: Platform 
) 
{  
    // This next bit is so that the CSS is shown correctly for each platform    

    platform.ready().then(() => {
    if (this.platform.is('android')) {
        console.log("running on Android device!");
        this.css_iOS = false;
    }
    if (this.platform.is('ios')) {
        console.log("running on iOS device!");
        this.css_iOS = true;
    }     
    if (this.platform.is('ipad')) {
        console.log("running on iOS device!");
        this.css_iOS = true;
    }
    });
}
css_iOS: boolean = false;

.HTML

<style *ngIf="css_iOS">
    .small_player {
      position: -webkit-sticky !important;
    }
    .large_player {
      position: -webkit-sticky !important;
    }
    </style>
    
    
    <style>
    .small_player {
    float: left;
      bottom: 0;
      width: 100%;
      position: fixed;
      background-color: white;
      border-top: black 1px solid;    
      height: 4rem;
      z-index: 100;
      /*transform: translate3d(0,0,0);*/
    }
    
    .large_player {
    float: left;
      bottom: 0;
      width: 100%;
      position: fixed;
      background-color: white;
      border-top: black 1px solid;    
      height: 14rem;
      z-index: 100;
      /*transform: translate3d(0,0,0);*/
    }
    </style>

How do you dismiss the keyboard when editing a UITextField

Swift 4.2 and It will work 100%

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField!


    override func viewDidLoad() {
        super.viewDidLoad()

        self.textField.delegate = self

    }

    // hide key board when the user touches outside keyboard

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

    // user presses return key

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }

}

Reasons for a 409/Conflict HTTP error when uploading a file to sharepoint using a .NET WebRequest?

I encountered similar issue when uploading a file returned 409.

Besides issues mentioned above it can also happen due to file size restrictions for POST on the server side. For example, tomcat (java web server) have POST size limit of 2MB by default.

Warning as error - How to get rid of these

View -> Error list -> Right click on specific Error/Warning.

You can change Severity as You want.

When should a class be Comparable and/or Comparator?

My annotation lib for implementing Comparable and Comparator:

public class Person implements Comparable<Person> {         
    private String firstName;  
    private String lastName;         
    private int age;         
    private char gentle;         

    @Override         
    @CompaProperties({ @CompaProperty(property = "lastName"),              
        @CompaProperty(property = "age",  order = Order.DSC) })           
    public int compareTo(Person person) {                 
        return Compamatic.doComparasion(this, person);         
    }  
} 

Click the link to see more examples. compamatic

How do I fix a merge conflict due to removal of a file in a branch?

I normally just run git mergetool and it will prompt me if I want to keep the modified file or keep it deleted. This is the quickest way IMHO since it's one command instead of several per file.

If you have a bunch of deleted files in a specific subdirectory and you want all of them to be resolved by deleting the files, you can do this:

yes d | git mergetool -- the/subdirectory

The d is provided to choose deleting each file. You can also use m to keep the modified file. Taken from the prompt you see when you run mergetool:

Use (m)odified or (d)eleted file, or (a)bort?

How to search for file names in Visual Studio?

In the search dropdown on the standard toolbar, you can use the "open file" macro, >of, to find files. Click in said dropdown (or hit Ctrl-D) then start typing (minus the quotes) ">of CoreEdit.cs", and you'll get a dynamic list that narrows as you type.

"Couldn't read dependencies" error with npm

I figured out I wasn't in the correct folder. I needed goto the folder I just cloned before I ran this command.

How to stop an unstoppable zombie job on Jenkins without restarting the server?

Had this same issue but there was not stack thread. We deleted the job by using this snippet in the Jenkins Console. Replace jobname and buil dnumber with yours.

def jobname = "Main/FolderName/BuildDefinition"
def buildnum = 6
Jenkins.instance.getItemByFullName(jobname).getBuildByNumber(buildnum).delete(); 

What is dtype('O'), in pandas?

When you see dtype('O') inside dataframe this means Pandas string.

What is dtype?

Something that belongs to pandas or numpy, or both, or something else? If we examine pandas code:

df = pd.DataFrame({'float': [1.0],
                    'int': [1],
                    'datetime': [pd.Timestamp('20180310')],
                    'string': ['foo']})
print(df)
print(df['float'].dtype,df['int'].dtype,df['datetime'].dtype,df['string'].dtype)
df['string'].dtype

It will output like this:

   float  int   datetime string    
0    1.0    1 2018-03-10    foo
---
float64 int64 datetime64[ns] object
---
dtype('O')

You can interpret the last as Pandas dtype('O') or Pandas object which is Python type string, and this corresponds to Numpy string_, or unicode_ types.

Pandas dtype    Python type     NumPy type          Usage
object          str             string_, unicode_   Text

Like Don Quixote is on ass, Pandas is on Numpy and Numpy understand the underlying architecture of your system and uses the class numpy.dtype for that.

Data type object is an instance of numpy.dtype class that understand the data type more precise including:

  • Type of the data (integer, float, Python object, etc.)
  • Size of the data (how many bytes is in e.g. the integer)
  • Byte order of the data (little-endian or big-endian)
  • If the data type is structured, an aggregate of other data types, (e.g., describing an array item consisting of an integer and a float)
  • What are the names of the "fields" of the structure
  • What is the data-type of each field
  • Which part of the memory block each field takes
  • If the data type is a sub-array, what is its shape and data type

In the context of this question dtype belongs to both pands and numpy and in particular dtype('O') means we expect the string.


Here is some code for testing with explanation: If we have the dataset as dictionary

import pandas as pd
import numpy as np
from pandas import Timestamp

data={'id': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}, 'date': {0: Timestamp('2018-12-12 00:00:00'), 1: Timestamp('2018-12-12 00:00:00'), 2: Timestamp('2018-12-12 00:00:00'), 3: Timestamp('2018-12-12 00:00:00'), 4: Timestamp('2018-12-12 00:00:00')}, 'role': {0: 'Support', 1: 'Marketing', 2: 'Business Development', 3: 'Sales', 4: 'Engineering'}, 'num': {0: 123, 1: 234, 2: 345, 3: 456, 4: 567}, 'fnum': {0: 3.14, 1: 2.14, 2: -0.14, 3: 41.3, 4: 3.14}}
df = pd.DataFrame.from_dict(data) #now we have a dataframe

print(df)
print(df.dtypes)

The last lines will examine the dataframe and note the output:

   id       date                  role  num   fnum
0   1 2018-12-12               Support  123   3.14
1   2 2018-12-12             Marketing  234   2.14
2   3 2018-12-12  Business Development  345  -0.14
3   4 2018-12-12                 Sales  456  41.30
4   5 2018-12-12           Engineering  567   3.14
id               int64
date    datetime64[ns]
role            object
num              int64
fnum           float64
dtype: object

All kind of different dtypes

df.iloc[1,:] = np.nan
df.iloc[2,:] = None

But if we try to set np.nan or None this will not affect the original column dtype. The output will be like this:

print(df)
print(df.dtypes)

    id       date         role    num   fnum
0  1.0 2018-12-12      Support  123.0   3.14
1  NaN        NaT          NaN    NaN    NaN
2  NaN        NaT         None    NaN    NaN
3  4.0 2018-12-12        Sales  456.0  41.30
4  5.0 2018-12-12  Engineering  567.0   3.14
id             float64
date    datetime64[ns]
role            object
num            float64
fnum           float64
dtype: object

So np.nan or None will not change the columns dtype, unless we set the all column rows to np.nan or None. In that case column will become float64 or object respectively.

You may try also setting single rows:

df.iloc[3,:] = 0 # will convert datetime to object only
df.iloc[4,:] = '' # will convert all columns to object

And to note here, if we set string inside a non string column it will become string or object dtype.

How to insert image in mysql database(table)?

This is on mysql workbench -- give the image file path:

INSERT INTO XX_SAMPLE(id,image) VALUES(3,'/home/ganesan-pc/Documents/aios_database/confe.jpg');

How to have Ellipsis effect on Text

You can use ellipsizeMode and numberOfLines. e.g

<Text ellipsizeMode='tail' numberOfLines={2}>
  This very long text should be truncated with dots in the beginning.
</Text>

https://facebook.github.io/react-native/docs/text.html

Could not load file or assembly '' or one of its dependencies

Try checking if the "Copy to Local" property for the reference is set to true and the specific version is set to true. This is relevant for applications in Visual Studio.

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

Right now, this is the only way

- name: Ensures {{project_root}}/conf dir exists
  file: path={{project_root}}/conf state=directory
- name: Copy file
  template:
    src: code.conf.j2
    dest: "{{project_root}}/conf/code.conf"

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

One thing I found is the path of your image must be relative to wherever the notebook was originally loaded from. if you cd to a different directory, such as Pictures your Markdown path is still relative to the original loading directory.

How to call an action after click() in Jquery?

you can write events on elements like chain,

$(element).on('click',function(){
   //action on click
}).on('mouseup',function(){
   //action on mouseup (just before click event)
});

i've used it for removing cart items. same object, doing some action, after another action

How to require a controller in an angularjs directive

I got lucky and answered this in a comment to the question, but I'm posting a full answer for the sake of completeness and so we can mark this question as "Answered".


It depends on what you want to accomplish by sharing a controller; you can either share the same controller (though have different instances), or you can share the same controller instance.

Share a Controller

Two directives can use the same controller by passing the same method to two directives, like so:

app.controller( 'MyCtrl', function ( $scope ) {
  // do stuff...
});

app.directive( 'directiveOne', function () {
  return {
    controller: 'MyCtrl'
  };
});

app.directive( 'directiveTwo', function () {
  return {
    controller: 'MyCtrl'
  };
});

Each directive will get its own instance of the controller, but this allows you to share the logic between as many components as you want.

Require a Controller

If you want to share the same instance of a controller, then you use require.

require ensures the presence of another directive and then includes its controller as a parameter to the link function. So if you have two directives on one element, your directive can require the presence of the other directive and gain access to its controller methods. A common use case for this is to require ngModel.

^require, with the addition of the caret, checks elements above directive in addition to the current element to try to find the other directive. This allows you to create complex components where "sub-components" can communicate with the parent component through its controller to great effect. Examples could include tabs, where each pane can communicate with the overall tabs to handle switching; an accordion set could ensure only one is open at a time; etc.

In either event, you have to use the two directives together for this to work. require is a way of communicating between components.

Check out the Guide page of directives for more info: http://docs.angularjs.org/guide/directive

Convert UTC/GMT time to local time

I'd look into using the System.TimeZoneInfo class if you are in .NET 3.5. See http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx. This should take into account the daylight savings changes correctly.

// Coordinated Universal Time string from 
// DateTime.Now.ToUniversalTime().ToString("u");
string date = "2009-02-25 16:13:00Z"; 
// Local .NET timeZone.
DateTime localDateTime = DateTime.Parse(date); 
DateTime utcDateTime = localDateTime.ToUniversalTime();

// ID from: 
// "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Time Zone"
// See http://msdn.microsoft.com/en-us/library/system.timezoneinfo.id.aspx
string nzTimeZoneKey = "New Zealand Standard Time";
TimeZoneInfo nzTimeZone = TimeZoneInfo.FindSystemTimeZoneById(nzTimeZoneKey);
DateTime nzDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, nzTimeZone);

Setting selected values for ng-options bound select elements

You can use the ID field as the equality identifier. You can't use the adhoc object for this case because AngularJS checks references equality when comparing objects.

<select 
    ng-model="Choice.SelectedOption.ID" 
    ng-options="choice.ID as choice.Name for choice in Choice.Options">
</select>

Git: Merge a Remote branch locally

You can reference those remote tracking branches ~(listed with git branch -r) with the name of their remote.

You need to fetch the remote branch:

git fetch origin aRemoteBranch

If you want to merge one of those remote branches on your local branch:

git checkout master
git merge origin/aRemoteBranch

Note 1: For a large repo with a long history, you will want to add the --depth=1 option when you use git fetch.

Note 2: These commands also work with other remote repos so you can setup an origin and an upstream if you are working on a fork.

Note 3: user3265569 suggests the following alias in the comments:

From aLocalBranch, run git combine remoteBranch
Alias:

combine = !git fetch origin ${1} && git merge origin/${1}

Opposite scenario: If you want to merge one of your local branch on a remote branch (as opposed to a remote branch to a local one, as shown above), you need to create a new local branch on top of said remote branch first:

git checkout -b myBranch origin/aBranch
git merge anotherLocalBranch

The idea here, is to merge "one of your local branch" (here anotherLocalBranch) to a remote branch (origin/aBranch).
For that, you create first "myBranch" as representing that remote branch: that is the git checkout -b myBranch origin/aBranch part.
And then you can merge anotherLocalBranch to it (to myBranch).

Where and how is the _ViewStart.cshtml layout file linked?

From ScottGu's blog:

Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:

The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:

Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).

Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.

This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.

Also see this.


In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".

Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.

Wikipedia

There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.

how to create a list of lists

Just came across the same issue today...

In order to create a list of lists you will have firstly to store your data, array, or other type of variable into a list. Then, create a new empty list and append to it the lists that you just created. At the end you should end up with a list of lists:

list_1=data_1.tolist()
list_2=data_2.tolist()
listoflists = []
listoflists.append(list_1)
listoflists.append(list_2)

Having services in React application

I am from Angular as well and trying out React, as of now, one recommended(?) way seems to be using High-Order Components:

A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature.

Let's say you have input and textarea and like to apply the same validation logic:

const Input = (props) => (
  <input type="text"
    style={props.style}
    onChange={props.onChange} />
)
const TextArea = (props) => (
  <textarea rows="3"
    style={props.style}
    onChange={props.onChange} >
  </textarea>
)

Then write a HOC that does validate and style wrapped component:

function withValidator(WrappedComponent) {
  return class extends React.Component {
    constructor(props) {
      super(props)

      this.validateAndStyle = this.validateAndStyle.bind(this)
      this.state = {
        style: {}
      }
    }

    validateAndStyle(e) {
      const value = e.target.value
      const valid = value && value.length > 3 // shared logic here
      const style = valid ? {} : { border: '2px solid red' }
      console.log(value, valid)
      this.setState({
        style: style
      })
    }

    render() {
      return <WrappedComponent
        onChange={this.validateAndStyle}
        style={this.state.style}
        {...this.props} />
    }
  }
}

Now those HOCs share the same validating behavior:

const InputWithValidator = withValidator(Input)
const TextAreaWithValidator = withValidator(TextArea)

render((
  <div>
    <InputWithValidator />
    <TextAreaWithValidator />
  </div>
), document.getElementById('root'));

I created a simple demo.

Edit: Another demo is using props to pass an array of functions so that you can share logic composed by multiple validating functions across HOCs like:

<InputWithValidator validators={[validator1,validator2]} />
<TextAreaWithValidator validators={[validator1,validator2]} />

Edit2: React 16.8+ provides a new feature, Hook, another nice way to share logic.

const Input = (props) => {
  const inputValidation = useInputValidation()

  return (
    <input type="text"
    {...inputValidation} />
  )
}

function useInputValidation() {
  const [value, setValue] = useState('')
  const [style, setStyle] = useState({})

  function handleChange(e) {
    const value = e.target.value
    setValue(value)
    const valid = value && value.length > 3 // shared logic here
    const style = valid ? {} : { border: '2px solid red' }
    console.log(value, valid)
    setStyle(style)
  }

  return {
    value,
    style,
    onChange: handleChange
  }
}

https://stackblitz.com/edit/react-shared-validation-logic-using-hook?file=index.js

Formatting ISODate from Mongodb

MongoDB's ISODate() is just a helper function that wraps a JavaScript date object and makes it easier to work with ISO date strings.

You can still use all of the same methods as working with a normal JS Date, such as:

ISODate("2012-07-14T01:00:00+01:00").toLocaleTimeString()

// Note that getHours() and getMinutes() do not include leading 0s for single digit #s
ISODate("2012-07-14T01:00:00+01:00").getHours()
ISODate("2012-07-14T01:00:00+01:00").getMinutes()

jQuery UI Dialog - missing close icon

  just add in css
 .ui-icon-closethick{
 margin-top: -8px!important;
margin-left: -8px!important;

}