Programs & Examples On #Time and attendance

Time and Attendance systems are those that keep track of people's comings and goings. Typically this refers to employees working in a business. However it can also be used in other contexts, such as students attending a class.

String to byte array in php

In PHP, strings are bytestreams. What exactly are you trying to do?

Re: edit

Ps. Why do I need this at all!? Well I need to send via fputs() bytearray to server written in java...

fputs takes a string as argument. Most likely, you just need to pass your string to it. On the Java side of things, you should decode the data in whatever encoding, you're using in php (the default is iso-8859-1).

How to get the current date/time in Java

Create object of date and simply print it down.

Date d = new Date(System.currentTimeMillis());
System.out.print(d);

iOS how to set app icon and launch images

In the left list, right click on "AppIcon" and click on "Open in finder" A folder with name "AppIcon.appiconset" will open. Paste all the graphics with required resolution there. Once done, all those images will be visible in this same screen(one in your screen shot). then drag them to appropriate box. App icons have been added. Same process for Launch images. Launch images through this process are added for iOS 7 and below. For iOS 8 separate LaunchScreen.xib file is made by default.

How to pass an array into a SQL Server stored procedure

CREATE TYPE dumyTable
AS TABLE
(
  RateCodeId int,
  RateLowerRange int,
  RateHigherRange int,
  RateRangeValue int
);
GO
CREATE PROCEDURE spInsertRateRanges
  @dt AS dumyTable READONLY
AS
BEGIN
  SET NOCOUNT ON;

  INSERT  tblRateCodeRange(RateCodeId,RateLowerRange,RateHigherRange,RateRangeValue) 
  SELECT * 
  FROM @dt 
END

Array of arrays (Python/NumPy)

It seems strange that you would write arrays without commas (is that a MATLAB syntax?)

Have you tried going through NumPy's documentation on multi-dimensional arrays?

It seems NumPy has a "Python-like" append method to add items to a NumPy n-dimensional array:

>>> p = np.array([[1,2],[3,4]])

>>> p = np.append(p, [[5,6]], 0)

>>> p = np.append(p, [[7],[8],[9]],1)

>>> p
array([[1, 2, 7], [3, 4, 8], [5, 6, 9]])

It has also been answered already...

From the documentation for MATLAB users:

You could use a matrix constructor which takes a string in the form of a matrix MATLAB literal:

mat("1 2 3; 4 5 6")

or

matrix("[1 2 3; 4 5 6]")

Please give it a try and tell me how it goes.

"Non-static method cannot be referenced from a static context" error

setLoanItem is an instance method, meaning you need an instance of the Media class in order to call it. You're attempting to call it on the Media type itself.

You may want to look into some basic object-oriented tutorials to see how static/instance members work.

How to detect when facebook's FB.init is complete

While some of the above solutions work, I thought I'd post our eventual solution - which defines a 'ready' method that will fire as soon as FB is initialized and ready to go. It has the advantage over other solutions that it's safe to call either before or after FB is ready.

It can be used like so:

f52.fb.ready(function() {
    // safe to use FB here
});

Here's the source file (note that it's defined within a 'f52.fb' namespace).

if (typeof(f52) === 'undefined') { f52 = {}; }
f52.fb = (function () {

    var fbAppId = f52.inputs.base.fbAppId,
        fbApiInit = false;

    var awaitingReady = [];

    var notifyQ = function() {
        var i = 0,
            l = awaitingReady.length;
        for(i = 0; i < l; i++) {
            awaitingReady[i]();
        }
    };

    var ready = function(cb) {
        if (fbApiInit) {
            cb();
        } else {
            awaitingReady.push(cb);
        }
    };

    window.fbAsyncInit = function() {
        FB.init({
            appId: fbAppId,
            xfbml: true,
            version: 'v2.0'
        });

        FB.getLoginStatus(function(response){
            fbApiInit = true;
            notifyQ();
        });
    };

    return {
        /**
         * Fires callback when FB is initialized and ready for api calls.
         */
        'ready': ready
    };

})();

Benefits of inline functions in C++?

Inlining is a suggestion to the compiler which it is free to ignore. It's ideal for small bits of code.

If your function is inlined, it's basically inserted in the code where the function call is made to it, rather than actually calling a separate function. This can assist with speed as you don't have to do the actual call.

It also assists CPUs with pipelining as they don't have to reload the pipeline with new instructions caused by a call.

The only disadvantage is possible increased binary size but, as long as the functions are small, this won't matter too much.

I tend to leave these sorts of decisions to the compilers nowadays (well, the smart ones anyway). The people who wrote them tend to have far more detailed knowledge of the underlying architectures.

Is there a Newline constant defined in Java like Environment.Newline in C#?

Be aware that this property isn't as useful as many people think it is. Just because your app is running on a Windows machine, for example, doesn't mean the file it's reading will be using Windows-style line separators. Many web pages contain a mixture of "\n" and "\r\n", having been cobbled together from disparate sources. When you're reading text as a series of logical lines, you should always look for all three of the major line-separator styles: Windows ("\r\n"), Unix/Linux/OSX ("\n") and pre-OSX Mac ("\r").

When you're writing text, you should be more concerned with how the file will be used than what platform you're running on. For example, if you expect people to read the file in Windows Notepad, you should use "\r\n" because it only recognizes the one kind of separator.

Static methods in Python?

Yep, using the staticmethod decorator

class MyClass(object):
    @staticmethod
    def the_static_method(x):
        print(x)

MyClass.the_static_method(2)  # outputs 2

Note that some code might use the old method of defining a static method, using staticmethod as a function rather than a decorator. This should only be used if you have to support ancient versions of Python (2.2 and 2.3)

class MyClass(object):
    def the_static_method(x):
        print(x)
    the_static_method = staticmethod(the_static_method)

MyClass.the_static_method(2)  # outputs 2

This is entirely identical to the first example (using @staticmethod), just not using the nice decorator syntax

Finally, use staticmethod sparingly! There are very few situations where static-methods are necessary in Python, and I've seen them used many times where a separate "top-level" function would have been clearer.


The following is verbatim from the documentation::

A static method does not receive an implicit first argument. To declare a static method, use this idiom:

class C:
    @staticmethod
    def f(arg1, arg2, ...): ...

The @staticmethod form is a function decorator – see the description of function definitions in Function definitions for details.

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class.

Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see classmethod().

For more information on static methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.

New in version 2.2.

Changed in version 2.4: Function decorator syntax added.

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

I had a similar issue today, and this is most certainly not the answer to your question. But I'd like to inform everyone, and possibly provide a spark of insight.

I have a ASP.NET application. The build process is set to clean and then build.

I have two Jenkins CI scripts. One for production and one for staging. I deployed my application to staging and everything worked fine. Deployed to production and was missing a DLL file that was referenced. This DLL file was just in the root of the project. Not in any NuGet repository. The DLL was set to do not copy.

The CI script and the application was the same between the two deployments. Still after the clean and deploy in the staging environment the DLL file was replaced in the deploy location of the ASP.NET application (bin/). This was not the case for the production environment.

It turns out in a testing branch I had added a step to the build process to copy over this DLL file to the bin directory. Now the part that took a little while to figure out. The CI process was not cleaning itself. The DLL was left in the working directory and was being accidentally packaged with the ASP.NET .zip file. The production branch never had the DLL file copied in the same way and was never accidentally deploying this.

TLDR; Check and make sure you know what your build server is doing.

How can I dynamically add a directive in AngularJS?

The accepted answer by Josh David Miller works great if you are trying to dynamically add a directive that uses an inline template. However if your directive takes advantage of templateUrl his answer will not work. Here is what worked for me:

.directive('helperModal', [, "$compile", "$timeout", function ($compile, $timeout) {
    return {
        restrict: 'E',
        replace: true,
        scope: {}, 
        templateUrl: "app/views/modal.html",
        link: function (scope, element, attrs) {
            scope.modalTitle = attrs.modaltitle;
            scope.modalContentDirective = attrs.modalcontentdirective;
        },
        controller: function ($scope, $element, $attrs) {
            if ($attrs.modalcontentdirective != undefined && $attrs.modalcontentdirective != '') {
                var el = $compile($attrs.modalcontentdirective)($scope);
                $timeout(function () {
                    $scope.$digest();
                    $element.find('.modal-body').append(el);
                }, 0);
            }
        }
    }
}]);

Facebook Javascript SDK Problem: "FB is not defined"

So the issue is actually that you are not waiting for the init to complete. This will cause random results. Here is what I use.

window.fbAsyncInit = function () {
    FB.init({ appId: 'your-app-id', cookie: true, xfbml: true, oauth: true });

    // *** here is my code ***
    if (typeof facebookInit == 'function') {
        facebookInit();
    }
};

(function(d){
    var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
    js = d.createElement('script'); js.id = id; js.async = true;
    js.src = "//connect.facebook.net/en_US/all.js";
    d.getElementsByTagName('head')[0].appendChild(js);
}(document));

This will ensure that once everything is loaded, the function facebookInit is available and executed. That way you don't have to duplicate the init code every time you want to use it.

function facebookInit() {
   // do what you would like here
}

Angular2: child component access parent class variable/function

The main article in the Angular2 documentation on this subject is :

https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child

It covers the following:

  • Pass data from parent to child with input binding

  • Intercept input property changes with a setter

  • Intercept input property changes with ngOnChanges

  • Parent listens for child event

  • Parent interacts with child via a local variable

  • Parent calls a ViewChild

  • Parent and children communicate via a service

How to get current user in asp.net core

I got my solution

var claim = HttpContext.User.CurrentUserID();

public static class XYZ
{
    public static int CurrentUserID(this ClaimsPrincipal claim)
    {
        var userID = claimsPrincipal.Claims.ToList().Find(r => r.Type == 
         "UserID").Value;
        return Convert.ToInt32(userID);
    }
    public static string CurrentUserRole(this ClaimsPrincipal claim)
    {
        var role = claimsPrincipal.Claims.ToList().Find(r => r.Type == 
        "Role").Value;
        return role;
    }
}

Error message "Forbidden You don't have permission to access / on this server"

With Apache 2.2

Order Deny,Allow
Allow from all

With Apache 2.4

Require all granted

From http://httpd.apache.org/docs/2.4/en/upgrading.html

C# - Substring: index and length must refer to a location within the string

The second parameter in Substring is the length of the substring, not the end index.

You should probably include handling to check that it does indeed start with what you expect, end with what you expect, and is at least as long as you expect. And then if it doesn't match, you can either do something else or throw a meaningful error.

Here's some example code that validates that url contains your strings, that also is refactored a bit to make it easier to change the prefix/suffix to strip:

var prefix = "www.example.com/";
var suffix = ".jpg";
string url = "www.example.com/aaa/bbb.jpg";

if (url.StartsWith(prefix) && url.EndsWith(suffix) && url.Length >= (prefix.Length + suffix.Length))
{
    string newString = url.Substring(prefix.Length, url.Length - prefix.Length - suffix.Length);
    Console.WriteLine(newString);
}
else
    //handle invalid state

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

With JQuery this stuff is pretty easy to do. Since you can bind to sets.

Its NOT enough to do the onbeforeunload, you want to only trigger the navigate away if someone started editing stuff.

Using ping in c#

Using ping in C# is achieved by using the method Ping.Send(System.Net.IPAddress), which runs a ping request to the provided (valid) IP address or URL and gets a response which is called an Internet Control Message Protocol (ICMP) Packet. The packet contains a header of 20 bytes which contains the response data from the server which received the ping request. The .Net framework System.Net.NetworkInformation namespace contains a class called PingReply that has properties designed to translate the ICMP response and deliver useful information about the pinged server such as:

  • IPStatus: Gets the address of the host that sends the Internet Control Message Protocol (ICMP) echo reply.
  • IPAddress: Gets the number of milliseconds taken to send an Internet Control Message Protocol (ICMP) echo request and receive the corresponding ICMP echo reply message.
  • RoundtripTime (System.Int64): Gets the options used to transmit the reply to an Internet Control Message Protocol (ICMP) echo request.
  • PingOptions (System.Byte[]): Gets the buffer of data received in an Internet Control Message Protocol (ICMP) echo reply message.

The following is a simple example using WinForms to demonstrate how ping works in c#. By providing a valid IP address in textBox1 and clicking button1, we are creating an instance of the Ping class, a local variable PingReply, and a string to store the IP or URL address. We assign PingReply to the ping Send method, then we inspect if the request was successful by comparing the status of the reply to the property IPAddress.Success status. Finally, we extract from PingReply the information we need to display for the user, which is described above.

    using System;
    using System.Net.NetworkInformation;
    using System.Windows.Forms;

    namespace PingTest1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private void button1_Click(object sender, EventArgs e)
            {
                Ping p = new Ping();
                PingReply r;
                string s;
                s = textBox1.Text;
                r = p.Send(s);

                if (r.Status == IPStatus.Success)
                {
                    lblResult.Text = "Ping to " + s.ToString() + "[" + r.Address.ToString() + "]" + " Successful"
                       + " Response delay = " + r.RoundtripTime.ToString() + " ms" + "\n";
                }
            }

            private void textBox1_Validated(object sender, EventArgs e)
            {
                if (string.IsNullOrWhiteSpace(textBox1.Text) || textBox1.Text == "")
                {
                    MessageBox.Show("Please use valid IP or web address!!");
                }
            }
        }
    }

How to run wget inside Ubuntu Docker image?

I had this problem recently where apt install wget does not find anything. As it turns out apt update was never run.

apt update
apt install wget

After discussing this with a coworker we mused that apt update is likely not run in order to save both time and space in the docker image.

Android - Center TextView Horizontally in LinearLayout

What's happening is that since the the TextView is filling the whole width of the inner LinearLayout it is already in the horizontal center of the layout. When you use android:layout_gravity it places the widget, as a whole, in the gravity specified. Instead of placing the whole widget center what you're really trying to do is place the content in the center which can be accomplished with android:gravity="center_horizontal" and the android:layout_gravity attribute can be removed.

Maven command to determine which settings.xml file Maven is using

You can use the maven help plugin to tell you the contents of your user and global settings files.

mvn help:effective-settings

will ask maven to spit out the combined global and user settings.

Angularjs action on click of button

The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity changes.

Instead you could try the following approach. Change your markup to the following:

<div ng-controller="myAppController" style="text-align:center">
  <p style="font-size:28px;">Enter Quantity:
      <input type="text" ng-model="quantity"/>
  </p>
  <button ng-click="calculateQuantity()">Calculate</button>
  <h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>

Next, update your controller:

myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.quantity=1;
  $scope.quantityResult = 0;

  $scope.calculateQuantity = function() {
    $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  };
});

Here's a JSBin example that demonstrates the above approach.

The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity changes.

This would involve updating the template to add an ng-change on the input, and an ng-if on the result:

<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>

and

<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>

In the controller add:

$scope.showQuantityResult = false;

$scope.calculateQuantity = function() {
  $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  $scope.showQuantityResult = true;
};

$scope.hideQuantityResult = function() {
  $scope.showQuantityResult = false;
}; 

These updates can be seen in this JSBin demo.

How to trigger Jenkins builds remotely and to pass parameters

In your Jenkins job configuration, tick the box named "This build is parameterized", click the "Add Parameter" button and select the "String Parameter" drop down value.

Now define your parameter - example:

Enter image description here

Now you can use your parameter in your job / build pipeline, example:

Enter image description here

Next to trigger the build with own/custom parameter, invoke the following URL (using either POST or GET):

http://JENKINS_SERVER_ADDRESS/job/YOUR_JOB_NAME/buildWithParameters?myparam=myparam_value

SQL Server "AFTER INSERT" trigger doesn't see the just-inserted row

UPDATE: DELETE from a trigger works on both MSSql 7 and MSSql 2008.

I'm no relational guru, nor a SQL standards wonk. However - contrary to the accepted answer - MSSQL deals just fine with both recursive and nested trigger evaluation. I don't know about other RDBMSs.

The relevant options are 'recursive triggers' and 'nested triggers'. Nested triggers are limited to 32 levels, and default to 1. Recursive triggers are off by default, and there's no talk of a limit - but frankly, I've never turned them on, so I don't know what happens with the inevitable stack overflow. I suspect MSSQL would just kill your spid (or there is a recursive limit).

Of course, that just shows that the accepted answer has the wrong reason, not that it's incorrect. However, prior to INSTEAD OF triggers, I recall writing ON INSERT triggers that would merrily UPDATE the just inserted rows. This all worked fine, and as expected.

A quick test of DELETEing the just inserted row also works:

 CREATE TABLE Test ( Id int IDENTITY(1,1), Column1 varchar(10) )
 GO

 CREATE TRIGGER trTest ON Test 
 FOR INSERT 
 AS
    SET NOCOUNT ON
    DELETE FROM Test WHERE Column1 = 'ABCDEF'
 GO

 INSERT INTO Test (Column1) VALUES ('ABCDEF')
 --SCOPE_IDENTITY() should be the same, but doesn't exist in SQL 7
 PRINT @@IDENTITY --Will print 1. Run it again, and it'll print 2, 3, etc.
 GO

 SELECT * FROM Test --No rows
 GO

You have something else going on here.

How to JSON serialize sets?

If you need just quick dump and don't want to implement custom encoder. You can use the following:

json_string = json.dumps(data, iterable_as_array=True)

This will convert all sets (and other iterables) into arrays. Just beware that those fields will stay arrays when you parse the json back. If you want to preserve the types, you need to write custom encoder.

jQuery - Illegal invocation

Just for the record it can also happen if you try to use undeclared variable in data like

var layout = {};
$.ajax({
  ...
  data: {
    layout: laoyut // notice misspelled variable name
  },
  ...
});

Why can a function modify some arguments as perceived by the caller, but not others?

You've got a number of answers already, and I broadly agree with J.F. Sebastian, but you might find this useful as a shortcut:

Any time you see varname =, you're creating a new name binding within the function's scope. Whatever value varname was bound to before is lost within this scope.

Any time you see varname.foo() you're calling a method on varname. The method may alter varname (e.g. list.append). varname (or, rather, the object that varname names) may exist in more than one scope, and since it's the same object, any changes will be visible in all scopes.

[note that the global keyword creates an exception to the first case]

phpMyAdmin - The MySQL Extension is Missing

Just as others stated you need to remove the ';' from:
;extension=php_mysql.dll and
;extension=php_mysqli.dll

in your php.ini to enable mysql and mysqli extensions. But MOST IMPORTANT of all, you should set the extension_dir in your php.ini to point to your extensions directory. The default most of the time is "ext". You should change it to the absolute path to the extensions folder. i.e. if you have your xampp installed on drive C, then C:/xampp/php/ext is the absolute path to the ext folder, and It should work like a charm!

JQuery get data from JSON array

You need to iterate both the groups and the items. $.each() takes a collection as first parameter and data.response.venue.tips.groups.items.text tries to point to a string. Both groups and items are arrays.

Verbose version:

$.getJSON(url, function (data) {

    // Iterate the groups first.
    $.each(data.response.venue.tips.groups, function (index, value) {

        // Get the items
        var items = this.items; // Here 'this' points to a 'group' in 'groups'

        // Iterate through items.
        $.each(items, function () {
            console.log(this.text); // Here 'this' points to an 'item' in 'items'
        });
    });
});

Or more simply:

$.getJSON(url, function (data) {
    $.each(data.response.venue.tips.groups, function (index, value) {
        $.each(this.items, function () {
            console.log(this.text);
        });
    });
});

In the JSON you specified, the last one would be:

$.getJSON(url, function (data) {
    // Get the 'items' from the first group.
    var items = data.response.venue.tips.groups[0].items;

    // Find the last index and the last item.
    var lastIndex = items.length - 1;
    var lastItem = items[lastIndex];

    console.log("User: " + lastItem.user.firstName + " " + lastItem.user.lastName);
    console.log("Date: " + lastItem.createdAt);
    console.log("Text: " + lastItem.text);
});

This would give you:

User: Damir P.
Date: 1314168377
Text: ajd da vidimo hocu li znati ponoviti

Background thread with QThread in PyQt

Take this answer updated for PyQt5, python 3.4

Use this as a pattern to start a worker that does not take data and return data as they are available to the form.

1 - Worker class is made smaller and put in its own file worker.py for easy memorization and independent software reuse.

2 - The main.py file is the file that defines the GUI Form class

3 - The thread object is not subclassed.

4 - Both thread object and the worker object belong to the Form object

5 - Steps of the procedure are within the comments.

# worker.py
from PyQt5.QtCore import QThread, QObject, pyqtSignal, pyqtSlot
import time


class Worker(QObject):
    finished = pyqtSignal()
    intReady = pyqtSignal(int)


    @pyqtSlot()
    def procCounter(self): # A slot takes no params
        for i in range(1, 100):
            time.sleep(1)
            self.intReady.emit(i)

        self.finished.emit()

And the main file is:

  # main.py
  from PyQt5.QtCore import QThread
  from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QGridLayout
  import sys
  import worker


  class Form(QWidget):

    def __init__(self):
       super().__init__()
       self.label = QLabel("0")

       # 1 - create Worker and Thread inside the Form
       self.obj = worker.Worker()  # no parent!
       self.thread = QThread()  # no parent!

       # 2 - Connect Worker`s Signals to Form method slots to post data.
       self.obj.intReady.connect(self.onIntReady)

       # 3 - Move the Worker object to the Thread object
       self.obj.moveToThread(self.thread)

       # 4 - Connect Worker Signals to the Thread slots
       self.obj.finished.connect(self.thread.quit)

       # 5 - Connect Thread started signal to Worker operational slot method
       self.thread.started.connect(self.obj.procCounter)

       # * - Thread finished signal will close the app if you want!
       #self.thread.finished.connect(app.exit)

       # 6 - Start the thread
       self.thread.start()

       # 7 - Start the form
       self.initUI()


    def initUI(self):
        grid = QGridLayout()
        self.setLayout(grid)
        grid.addWidget(self.label,0,0)

        self.move(300, 150)
        self.setWindowTitle('thread test')
        self.show()

    def onIntReady(self, i):
        self.label.setText("{}".format(i))
        #print(i)

    app = QApplication(sys.argv)

    form = Form()

    sys.exit(app.exec_())

Certificate has either expired or has been revoked

With Xcode Version 10.1 I solved with these steps:

  1. Go to Xcode, Preferences and select the Accounts tab
  2. In the accounts section click on the gear in the bottom left of the window corner and then click on Export Apple ID and Code Signing Assets... exporting this in a file, for example Test.developerprofile
  3. Delete the profile that you are using
  4. Clicking again on the gear select Import Apple ID and Code Signing Assets... and select your previously exported file Test.developerprofile
  5. Now perform a Clean (Shift(?)+Command(?)+K) and a Build (Command(?)+B)
  6. Run again

How to pass parameters in $ajax POST?

Jquery.ajax does not encode POST data for you automatically the way that it does for GET data. Jquery expects your data to be pre-formated to append to the request body to be sent directly across the wire.

A solution is to use the jQuery.param function to build a query string that most scripts that process POST requests expect.

$.ajax({
    url: 'superman',
    type: 'POST',
    data: jQuery.param({ field1: "hello", field2 : "hello2"}) ,
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    success: function (response) {
        alert(response.status);
    },
    error: function () {
        alert("error");
    }
}); 

In this case the param method formats the data to:

field1=hello&field2=hello2

The Jquery.ajax documentation says that there is a flag called processData that controls whether this encoding is done automatically or not. The documentation says that it defaults to true, but that is not the behavior I observe when POST is used.

How to read XML using XPath in Java

Read XML file using XPathFactory, SAXParserFactory and StAX (JSR-173).

Using XPath get node and its child data.

public static void main(String[] args) {
    String xml = "<soapenv:Body xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'>"
            + "<Yash:Data xmlns:Yash='http://Yash.stackoverflow.com/Services/Yash'>"
            + "<Yash:Tags>Java</Yash:Tags><Yash:Tags>Javascript</Yash:Tags><Yash:Tags>Selenium</Yash:Tags>"
            + "<Yash:Top>javascript</Yash:Top><Yash:User>Yash-777</Yash:User>"
            + "</Yash:Data></soapenv:Body>";
    String jsonNameSpaces = "{'soapenv':'http://schemas.xmlsoap.org/soap/envelope/',"
            + "'Yash':'http://Yash.stackoverflow.com/Services/Yash'}";
    String xpathExpression = "//Yash:Data";

    Document doc1 = getDocument(false, "fileName", xml);
    getNodesFromXpath(doc1, xpathExpression, jsonNameSpaces);
    System.out.println("\n===== ***** =====");
    Document doc2 = getDocument(true, "./books.xml", xml);
    getNodesFromXpath(doc2, "//person", "{}");
}
static Document getDocument( boolean isFileName, String fileName, String xml ) {
    Document doc = null;
    try {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(true);
        factory.setIgnoringComments(true);
        factory.setIgnoringElementContentWhitespace(true);

        DocumentBuilder builder = factory.newDocumentBuilder();
        if( isFileName ) {
            File file = new File( fileName );
            FileInputStream stream = new FileInputStream( file );
            doc = builder.parse( stream );
        } else {
            doc = builder.parse( string2Source( xml ) );
        }
    } catch (SAXException | IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    return doc;
}

/**
 * ELEMENT_NODE[1],ATTRIBUTE_NODE[2],TEXT_NODE[3],CDATA_SECTION_NODE[4],
 * ENTITY_REFERENCE_NODE[5],ENTITY_NODE[6],PROCESSING_INSTRUCTION_NODE[7],
 * COMMENT_NODE[8],DOCUMENT_NODE[9],DOCUMENT_TYPE_NODE[10],DOCUMENT_FRAGMENT_NODE[11],NOTATION_NODE[12]
 */
public static void getNodesFromXpath( Document doc, String xpathExpression, String jsonNameSpaces ) {
    try {
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();

        JSONObject namespaces = getJSONObjectNameSpaces(jsonNameSpaces);
        if ( namespaces.size() > 0 ) {
            NamespaceContextImpl nsContext = new NamespaceContextImpl();

            Iterator<?> key = namespaces.keySet().iterator();
            while (key.hasNext()) { // Apache WebServices Common Utilities
                String pPrefix = key.next().toString();
                String pURI = namespaces.get(pPrefix).toString();
                nsContext.startPrefixMapping(pPrefix, pURI);
            }
            xpath.setNamespaceContext(nsContext );
        }

        XPathExpression compile = xpath.compile(xpathExpression);
        NodeList nodeList = (NodeList) compile.evaluate(doc, XPathConstants.NODESET);
        displayNodeList(nodeList);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
}

static void displayNodeList( NodeList nodeList ) {
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        String NodeName = node.getNodeName();

        NodeList childNodes = node.getChildNodes();
        if ( childNodes.getLength() > 1 ) {
            for (int j = 0; j < childNodes.getLength(); j++) {

                Node child = childNodes.item(j);
                short nodeType = child.getNodeType();
                if ( nodeType == 1 ) {
                    System.out.format( "\n\t Node Name:[%s], Text[%s] ", child.getNodeName(), child.getTextContent() );
                }
            }
        } else {
            System.out.format( "\n Node Name:[%s], Text[%s] ", NodeName, node.getTextContent() );
        }

    }
}
static InputSource string2Source( String str ) {
    InputSource inputSource = new InputSource( new StringReader( str ) );
    return inputSource;
}
static JSONObject getJSONObjectNameSpaces( String jsonNameSpaces ) {
    if(jsonNameSpaces.indexOf("'") > -1)    jsonNameSpaces = jsonNameSpaces.replace("'", "\"");
    JSONParser parser = new JSONParser();
    JSONObject namespaces = null;
    try {
        namespaces = (JSONObject) parser.parse(jsonNameSpaces);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return namespaces;
}

XML Document

<?xml version="1.0" encoding="UTF-8"?>
<book>
<person>
  <first>Yash</first>
  <last>M</last>
  <age>22</age>
</person>
<person>
  <first>Bill</first>
  <last>Gates</last>
  <age>46</age>
</person>
<person>
  <first>Steve</first>
  <last>Jobs</last>
  <age>40</age>
</person>
</book>

Out put for the given XPathExpression:

String xpathExpression = "//person/first";
/*OutPut:
 Node Name:[first], Text[Yash] 
 Node Name:[first], Text[Bill] 
 Node Name:[first], Text[Steve] */

String xpathExpression = "//person";
/*OutPut:
     Node Name:[first], Text[Yash] 
     Node Name:[last], Text[M] 
     Node Name:[age], Text[22] 
     Node Name:[first], Text[Bill] 
     Node Name:[last], Text[Gates] 
     Node Name:[age], Text[46] 
     Node Name:[first], Text[Steve] 
     Node Name:[last], Text[Jobs] 
     Node Name:[age], Text[40] */

String xpathExpression = "//Yash:Data";
/*OutPut:
     Node Name:[Yash:Tags], Text[Java] 
     Node Name:[Yash:Tags], Text[Javascript] 
     Node Name:[Yash:Tags], Text[Selenium] 
     Node Name:[Yash:Top], Text[javascript] 
     Node Name:[Yash:User], Text[Yash-777] */

See this link for our own Implementation of NamespaceContext

Applying .gitignore to committed files

Follow these steps:

  1. Add path to gitignore file

  2. Run this command

    git rm -r --cached foldername
    
  3. commit changes as usually.

jQuery UI themes and HTML tables

I've got a one liner to make HTML Tables look BootStrapped:

<table class="table table-striped table-bordered table-hover">

The theme suits other controls and it supports alternate row highlighting.

How to remove folders with a certain name

This command works for me. It does its work recursively

find . -name "node_modules" -type d -prune -exec rm -rf '{}' +

. - current folder

"node_modules" - folder name

Increasing Heap Size on Linux Machines

Changing Tomcat config wont effect all JVM instances to get theses settings. This is not how it works, the setting will be used only to launch JVMs used by Tomcat, not started in the shell.

Look here for permanently changing the heap size.

Excel Calculate the date difference from today from a cell of "7/6/2012 10:26:42"

=ROUND((TODAY()-A1)/365,0) will provide number of years between date in cell A1 and today's date

How do I read a specified line in a text file?

A variation. Produces an error if line number is greater than number of lines.

string GetLine(string fileName, int lineNum)
{
    using (StreamReader sr = new StreamReader(fileName))
    {
        string line;
        int count = 1;
        while ((line = sr.ReadLine()) != null)
        {
            if(count == lineNum)
            {
                return line;
            }
            count++;
        }
    }
    return "line number is bigger than number of lines";  
}

Giving UIView rounded corners

Swift 4 - Using IBDesignable

   @IBDesignable
    class DesignableView: UIView {
    }

    extension UIView
    {

        @IBInspectable
        var cornerRadius: CGFloat {
            get {
                return layer.cornerRadius
            }
            set {
            layer.cornerRadius = newValue
        }
    }
}

SQL Server: Invalid Column Name

I was getting the same error when creating a view.

Imagine a select query that executes without issue:

select id
from products

Attempting to create a view from the same query would produce an error:

create view app.foobar as
select id
from products

Msg 207, Level 16, State 1, Procedure foobar, Line 2
Invalid column name 'id'.

For me it turned out to be a scoping issue; note the view is being created in a different schema. Specifying the schema of the products table solved the issue. Ie.. using dbo.products instead of just products.

Java error: Comparison method violates its general contract

It might also be an OpenJDK bug... (not in this case but it is the same error)

If somebody like me stumbles upon this answer regarding the

java.lang.IllegalArgumentException: Comparison method violates its general contract!

then it might also be a bug in the Java-Version. I have a compareTo running since several years now in some applications. But suddenly it stopped working and throws the error after all compares were done (i compare 6 Attributes before returning "0").

Now I just found this Bugreport of OpenJDK:

Laravel: Auth::user()->id trying to get a property of a non-object

 if(Auth::check() && Auth::user()->role->id == 2){ 
         $tags = Tag::latest()->get();
        return view('admin.tag.index',compact('tags'));
    }

How to tell if UIViewController's view is visible

I needed this to check if the view controller is the current viewed controller, I did it via checking if there's any presented view controller or pushed through the navigator, I'm posting it in case anyone needed such a solution:

if presentedViewController != nil || navigationController?.topViewController != self {
      //Viewcontroller isn't viewed
}else{
     // Now your viewcontroller is being viewed 
}

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

I usually use git on my linux machine, but at work I have to use Windows. I had the same problem when trying to commit the first commit in a Windows environment.

For those still facing this problem, I was able to resolve it as follows:

$ git commit --allow-empty -n -m "Initial commit".

Update and left outer join statements

Update t 
SET 
       t.Column1=100
FROM 
       myTableA t 
LEFT JOIN 
       myTableB t2 
ON 
       t2.ID=t.ID

Replace myTableA with your table name and replace Column1 with your column name.

After this simply LEFT JOIN to tableB. t in this case is just an alias for myTableA. t2 is an alias for your joined table, in my example that is myTableB. If you don't like using t or t2 use any alias name you prefer - it doesn't matter - I just happen to like using those.

Bootstrap 3: how to make head of dropdown link clickable in navbar

Alternatively here's a simple jQuery solution:

$('#menu-main > li > .dropdown-toggle').click(function () {
    window.location = $(this).attr('href');
});

Take screenshots in the iOS simulator

  1. Focus simulator
  2. Go to menu File->Save Screen Shot

    or

    Press ?+S

Screen shot saves in desktop

Iterator Loop vs index loop

The special thing about iterators is that they provide the glue between algorithms and containers. For generic code, the recommendation would be to use a combination of STL algorithms (e.g. find, sort, remove, copy) etc. that carries out the computation that you have in mind on your data structure (vector, list, map etc.), and to supply that algorithm with iterators into your container.

Your particular example could be written as a combination of the for_each algorithm and the vector container (see option 3) below), but it's only one out of four distinct ways to iterate over a std::vector:

1) index-based iteration

for (std::size_t i = 0; i != v.size(); ++i) {
    // access element as v[i]

    // any code including continue, break, return
}

Advantages: familiar to anyone familiar with C-style code, can loop using different strides (e.g. i += 2).

Disadvantages: only for sequential random access containers (vector, array, deque), doesn't work for list, forward_list or the associative containers. Also the loop control is a little verbose (init, check, increment). People need to be aware of the 0-based indexing in C++.

2) iterator-based iteration

for (auto it = v.begin(); it != v.end(); ++it) {
    // if the current index is needed:
    auto i = std::distance(v.begin(), it); 

    // access element as *it

    // any code including continue, break, return
}

Advantages: more generic, works for all containers (even the new unordered associative containers, can also use different strides (e.g. std::advance(it, 2));

Disadvantages: need extra work to get the index of the current element (could be O(N) for list or forward_list). Again, the loop control is a little verbose (init, check, increment).

3) STL for_each algorithm + lambda

std::for_each(v.begin(), v.end(), [](T const& elem) {
     // if the current index is needed:
     auto i = &elem - &v[0];

     // cannot continue, break or return out of the loop
});

Advantages: same as 2) plus small reduction in loop control (no check and increment), this can greatly reduce your bug rate (wrong init, check or increment, off-by-one errors).

Disadvantages: same as explicit iterator-loop plus restricted possibilities for flow control in the loop (cannot use continue, break or return) and no option for different strides (unless you use an iterator adapter that overloads operator++).

4) range-for loop

for (auto& elem: v) {
     // if the current index is needed:
     auto i = &elem - &v[0];

    // any code including continue, break, return
}

Advantages: very compact loop control, direct access to the current element.

Disadvantages: extra statement to get the index. Cannot use different strides.

What to use?

For your particular example of iterating over std::vector: if you really need the index (e.g. access the previous or next element, printing/logging the index inside the loop etc.) or you need a stride different than 1, then I would go for the explicitly indexed-loop, otherwise I'd go for the range-for loop.

For generic algorithms on generic containers I'd go for the explicit iterator loop unless the code contained no flow control inside the loop and needed stride 1, in which case I'd go for the STL for_each + a lambda.

implement time delay in c

you can simply call delay() function. So if you want to delay the process in 3 seconds, call delay(3000)...

twitter bootstrap text-center when in xs mode

@media (max-width: 767px) {
    footer .text-right, 
    footer .text-left {
        text-align: center;
    } 
}

I updated @loddn's answer, making two changes

  • max-width of xs screens in bootstrap is 767px (768px is the start of sm screens)
  • (this one is a matter of preference) I used footer instead of col-* so that if the column widths change, the CSS doesn't need to be updated.

Prime numbers between 1 to 100 in C Programming Language

#include<stdio.h>
int main()
{
    int a,b,i,c,j;
    printf("\n Enter the two no. in between you want to check:");
    scanf("%d%d",&a,&c);
    printf("%d-%d\n",a,c);
    for(j=a;j<=c;j++)
    {
        b=0;
        for(i=1;i<=c;i++)
        {
            if(j%i==0)
            {
                 b++;
            }
        }
        if(b==2)
        {
            printf("\nPrime number:%d\n",j);
        }
        else
        {
            printf("\n\tNot prime:%d\n",j);
        }
    }
}

What does "atomic" mean in programming?

In Java reading and writing fields of all types except long and double occurs atomically, and if the field is declared with the volatile modifier, even long and double are atomically read and written. That is, we get 100% either what was there, or what happened there, nor can there be any intermediate result in the variables.

overlay opaque div over youtube iframe

Hmm... what's different this time? http://jsfiddle.net/fdsaP/2/

Renders in Chrome fine. Do you need it cross-browser? It really helps being specific.

EDIT: Youtube renders the object and embed with no explicit wmode set, meaning it defaults to "window" which means it overlays everything. You need to either:


a) Host the page that contains the object/embed code yourself and add wmode="transparent" param element to object and attribute to embed if you choose to serve both elements

b) Find a way for youtube to specify those.


How to create permanent PowerShell Aliases

Just to add to this list of possible locations...

This didn't work for me: \Users\{ME}\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

However this did: \Users\{ME}\OneDrive\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

If you don't have a profile or you're looking to set one up, run the following command, it will create the folder/files necessary and even tell you where it lives! New-Item -path $profile -type file -force

Apply pandas function to column to create multiple new columns?

Just use result_type="expand"

df = pd.DataFrame(np.random.randint(0,10,(10,2)), columns=["random", "a"])
df[["sq_a","cube_a"]] = df.apply(lambda x: [x.a**2, x.a**3], axis=1, result_type="expand")

How to horizontally center an element

Yes, this is short and clean code for horizontal align.

.classname {
   display: box;
   margin: 0 auto;
   width: 500px /* Width set as per your requirement. */;
}

How to remove element from array in forEach loop?

You could also use indexOf instead to do this

var i = review.indexOf('\u2022 \u2022 \u2022');
if (i !== -1) review.splice(i,1);

Write a number with two decimal places SQL Server

This will allow total 10 digits with 2 values after the decimal. It means that it can accomodate the value value before decimal upto 8 digits and 2 after decimal.

To validate, put the value in the following query.

DECLARE vtest  number(10,2);
BEGIN
SELECT 10.008 INTO vtest FROM dual;
dbms_output.put_line(vtest);
END;

auto refresh for every 5 mins

Page should be refresh auto using meta tag

<meta http-equiv="Refresh" content="60"> 

content value in seconds.after one minute page should be refresh

Click through div to underlying elements

You can place an AP overlay like...

#overlay {
  position: absolute;
  top: -79px;
  left: -60px;
  height: 80px;
  width: 380px;
  z-index: 2;
  background: url(fake.gif);
}
<div id="overlay"></div>

just put it over where you dont want ie cliked. Works in all.

print highest value in dict with key

just :

 mydict = {'A':4,'B':10,'C':0,'D':87}
 max(mydict.items(), key=lambda x: x[1])

How to disable Django's CSRF validation?

CSRF can be enforced at the view level, which can't be disabled globally.

In some cases this is a pain, but um, "it's for security". Gotta retain those AAA ratings.

https://docs.djangoproject.com/en/dev/ref/csrf/#contrib-and-reusable-apps

Rails 4: before_filter vs. before_action

before_filter/before_action: means anything to be executed before any action executes.

Both are same. they are just alias for each other as their behavior is same.

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

In order to avoid having to fully specify the git push command you could alternatively modify your git config file:

[remote "gerrit"]
    url = https://your.gerrit.repo:44444/repo
    fetch = +refs/heads/master:refs/remotes/origin/master
    push = refs/heads/master:refs/for/master

Now you can simply:

git fetch gerrit
git push gerrit

This is according to Gerrit

When do I need to use AtomicBoolean in Java?

There are two main reasons why you can use an atomic boolean. First its mutable, you can pass it in as a reference and change the value that is a associated to the boolean itself, for example.

public final class MyThreadSafeClass{

    private AtomicBoolean myBoolean = new AtomicBoolean(false);
    private SomeThreadSafeObject someObject = new SomeThreadSafeObject();

    public boolean doSomething(){
         someObject.doSomeWork(myBoolean);
         return myBoolean.get(); //will return true
    }
}

and in the someObject class

public final class SomeThreadSafeObject{
    public void doSomeWork(AtomicBoolean b){
        b.set(true);
    }
}

More importantly though, its thread safe and can indicate to developers maintaining the class, that this variable is expected to be modified and read from multiple threads. If you do not use an AtomicBoolean you must synchronize the boolean variable you are using by declaring it volatile or synchronizing around the read and write of the field.

What's the difference between HEAD, working tree and index, in Git?

The difference between HEAD (current branch or last committed state on current branch), index (aka. staging area) and working tree (the state of files in checkout) is described in "The Three States" section of the "1.3 Git Basics" chapter of Pro Git book by Scott Chacon (Creative Commons licensed).

Here is the image illustrating it from this chapter:

Local Operations - working directory vs. staging area (index) vs git repository (HEAD)

In the above image "working directory" is the same as "working tree", the "staging area" is an alternate name for git "index", and HEAD points to currently checked out branch, which tip points to last commit in the "git directory (repository)"

Note that git commit -a would stage changes and commit in one step.

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

Python update a key in dict if it doesn't exist

With the following you can insert multiple values and also have default values but you're creating a new dictionary.

d = {**{ key: value }, **default_values}

I've tested it with the most voted answer and on average this is faster as it can be seen in the following example, .

Speed test comparing a for loop based method with a dict comprehension with unpack operator Speed test comparing a for loop based method with a dict comprehension with unpack operator method.

if no copy (d = default_vals.copy()) is made on the first case then the most voted answer would be faster once we reach orders of magnitude of 10**5 and greater. Memory footprint of both methods are the same.

Rendering React Components from Array of Objects

this.data presumably contains all the data, so you would need to do something like this:

var stations = [];
var stationData = this.data.stations;

for (var i = 0; i < stationData.length; i++) {
    stations.push(
        <div key={stationData[i].call} className="station">
            Call: {stationData[i].call}, Freq: {stationData[i].frequency}
        </div>
    )
}

render() {
  return (
    <div className="stations">{stations}</div>
  )
}

Or you can use map and arrow functions if you're using ES6:

const stations = this.data.stations.map(station =>
    <div key={station.call} className="station">
      Call: {station.call}, Freq: {station.frequency}
    </div>
);

Using %s in C correctly - very basic level

%s is the representation of an array of char

char string[10] // here is a array of chars, they max length is 10;
char character; // just a char 1 letter/from the ascii map

character = 'a'; // assign 'a' to character
printf("character %c  ",a); //we will display 'a' to stout

so string is an array of char we can assign multiple character per space of memory

string[0]='h';
string[1]='e';
string[2]='l';
string[3]='l';
string[4]='o';
string[5]=(char) 0;//asigning the last element of the 'word' a mark so the string ends

this assignation can be done at initialization like char word="this is a word" // the word array of chars got this string now and is statically defined

toy can also assign values to the array of chars assigning it with functions like strcpy;

strcpy(string,"hello" );

this do the same as the example and automatically add the (char) 0 at the end

so if you print it with %S printf("my string %s",string);

and how string is a array we can just display part of it

//                         the array    one char
printf("first letter of wrd %s     is    :%c ",string,string[1]  );

How to print a float with 2 decimal places in Java?

You can use DecimalFormat. One way to use it:

DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
System.out.println(df.format(decimalNumber));

Another one is to construct it using the #.## format.

I find all formatting options less readable than calling the formatting methods, but that's a matter of preference.

Test for non-zero length string in Bash: [ -n "$var" ] or [ "$var" ]

Here are some more tests

True if string is not empty:

[ -n "$var" ]
[[ -n $var ]]
test -n "$var"
[ "$var" ]
[[ $var ]]
(( ${#var} ))
let ${#var}
test "$var"

True if string is empty:

[ -z "$var" ]
[[ -z $var ]]
test -z "$var"
! [ "$var" ]
! [[ $var ]]
! (( ${#var} ))
! let ${#var}
! test "$var"

getting a checkbox array value from POST

Because your <form> element is inside the foreach loop, you are generating multiple forms. I assume you want multiple checkboxes in one form.

Try this...

<form method="post">
foreach{
<?php echo'
<input id="'.$userid.'" value="'.$userid.'"  name="invite[]" type="checkbox">
<input type="submit">';
?>
}
</form>

Mocking member variables of a class using Mockito

Yes, this can be done, as the following test shows (written with the JMockit mocking API, which I develop):

@Test
public void testFirst(@Mocked final Second sec) {
    new NonStrictExpectations() {{ sec.doSecond(); result = "Stubbed Second"; }};

    First first = new First();
    assertEquals("Stubbed Second", first.doSecond());
}

With Mockito, however, such a test cannot be written. This is due to the way mocking is implemented in Mockito, where a subclass of the class to be mocked is created; only instances of this "mock" subclass can have mocked behavior, so you need to have the tested code use them instead of any other instance.

Hibernate Error executing DDL via JDBC Statement

I have got this error when trying to create JPA entity with the name "User" (in Postgres) that is reserved. So the way it is resolved is to change the table name by @Table annotation:

@Entity
@Table(name="users")
public class User {..}

Or change the table name manually.

How to create unique keys for React elements?

Keys helps React identify which items have changed/added/removed and should be given to the elements inside the array to give the elements a stable identity.

With that in mind, there are basically three different strategies as described bellow:

  1. Static Elements (when you don't need to keep html state (focus, cursor position, etc)
  2. Editable and sortable elements
  3. Editable but not sortable elements

As React Documentation explains, we need to give stable identity to the elements and because of that, carefully choose the strategy that best suits your needs:

STATIC ELEMENTS

As we can see also in React Documentation, is not recommended the use of index for keys "if the order of items may change. This can negatively impact performance and may cause issues with component state".

In case of static elements like tables, lists, etc, I recommend using a tool called shortid.

1) Install the package using NPM/YARN:

npm install shortid --save

2) Import in the class file you want to use it:

import shortid from 'shortid';

2) The command to generate a new id is shortid.generate().

3) Example:

  renderDropdownItems = (): React.ReactNode => {
    const { data, isDisabled } = this.props;
    const { selectedValue } = this.state;
    const dropdownItems: Array<React.ReactNode> = [];

    if (data) {
      data.forEach(item => {
        dropdownItems.push(
          <option value={item.value} key={shortid.generate()}>
            {item.text}
          </option>
        );
      });
    }

    return (
      <select
        value={selectedValue}
        onChange={this.onSelectedItemChanged}
        disabled={isDisabled}
      >
        {dropdownItems}
      </select>
    );
  };

IMPORTANT: As React Virtual DOM relies on the key, with shortid every time the element is re-rendered a new key will be created and the element will loose it's html state like focus or cursor position. Consider this when deciding how the key will be generated as the strategy above can be useful only when you are building elements that won't have their values changed like lists or read only fields.

EDITABLE (sortable) FIELDS

If the element is sortable and you have a unique ID of the item, combine it with some extra string (in case you need to have the same information twice in a page). This is the most recommended scenario.

Example:

  renderDropdownItems = (): React.ReactNode => {
    const elementKey:string = 'ddownitem_'; 
    const { data, isDisabled } = this.props;
    const { selectedValue } = this.state;
    const dropdownItems: Array<React.ReactNode> = [];

    if (data) {
      data.forEach(item => {
        dropdownItems.push(
          <option value={item.value} key={${elementKey}${item.id}}>
            {item.text}
          </option>
        );
      });
    }

    return (
      <select
        value={selectedValue}
        onChange={this.onSelectedItemChanged}
        disabled={isDisabled}
      >
        {dropdownItems}
      </select>
    );
  };

EDITABLE (non sortable) FIELDS (e.g. INPUT ELEMENTS)

As a last resort, for editable (but non sortable) fields like input, you can use some the index with some starting text as element key cannot be duplicated.

Example:

  renderDropdownItems = (): React.ReactNode => {
    const elementKey:string = 'ddownitem_'; 
    const { data, isDisabled } = this.props;
    const { selectedValue } = this.state;
    const dropdownItems: Array<React.ReactNode> = [];

    if (data) {
      data.forEach((item:any index:number) => {
        dropdownItems.push(
          <option value={item.value} key={${elementKey}${index}}>
            {item.text}
          </option>
        );
      });
    }

    return (
      <select
        value={selectedValue}
        onChange={this.onSelectedItemChanged}
        disabled={isDisabled}
      >
        {dropdownItems}
      </select>
    );
  };

Hope this helps.

Make copy of an array

I had a similar problem with 2D arrays and ended here. I was copying the main array and changing the inner arrays' values and was surprised when the values changed in both copies. Basically both copies were independent but contained references to the same inner arrays and I had to make an array of copies of the inner arrays to get what I wanted.

This is sometimes called a deep copy. The same term "deep copy" can also have a completely different and arguably more complex meaning, which can be confusing, especially to someone not figuring out why their copied arrays don't behave as they should. It probably isn't the OP's problem, but I hope it can still be helpful.

How can I find an element by CSS class with XPath?

Match against one class that has whitespace.

<div class="hello "></div>
//div[normalize-space(@class)="hello"]

Set transparent background using ImageMagick and commandline prompt

You can Use this to make the background transparent

convert test.png -background rgba(0,0,0,0) test1.png

The above gives the prefect transparent background

How do I debug Node.js applications?

A lot of great answers here, but I'd like to add my view (based on how my approach evolved)

Debug Logs

Let's face it, we all love a good console.log('Uh oh, if you reached here, you better run.') and sometimes that works great, so if you're reticent to move too far away from it at least add some bling to your logs with Visionmedia's debug.

Interactive Debugging

As handy as console logging can be, to debug professionally you need to roll up your sleeves and get stuck in. Set breakpoints, step through your code, inspect scopes and variables to see what's causing that weird behaviour. As others have mentioned, node-inspector really is the bees-knees. It does everything you can do with the built-in debugger, but using that familiar Chrome DevTools interface. If, like me, you use Webstorm, then here is a handy guide to debugging from there.

Stack Traces

By default, we can't trace a series of operations across different cycles of the event loop (ticks). To get around this have a look at longjohn (but not in production!).

Memory Leaks

With Node.js we can have a server process expected to stay up for considerable time. What do you do if you think it has sprung some nasty leaks? Use heapdump and Chrome DevTools to compare some snapshots and see what's changing.


For some useful articles, check out

If you feel like watching a video(s) then

Whatever path you choose, just be sure you understand how you are debugging

enter image description here

It is a painful thing
To look at your own trouble and know
That you yourself and no one else has made it

Sophocles, Ajax

Getting current directory in .NET web application

The current directory is a system-level feature; it returns the directory that the server was launched from. It has nothing to do with the website.

You want HttpRuntime.AppDomainAppPath.

If you're in an HTTP request, you can also call Server.MapPath("~/Whatever").

Can one class extend two classes?

Also, instead of inner classes, you can use your 2 or more classes as fields.

For example:

Class Man{
private Phone ownPhone;
private DeviceInfo info;
//sets; gets
}
Class Phone{
private String phoneType;
private Long phoneNumber;
//sets; gets
}

Class DeviceInfo{

String phoneModel;
String cellPhoneOs;
String osVersion;
String phoneRam;
//sets; gets

}

So, here you have a man who can have some Phone with its number and type, also you have DeviceInfo for that Phone.

Also, it's possible is better to use DeviceInfo as a field into Phone class, like

class Phone {
DeviceInfo info;
String phoneNumber;
Stryng phoneType;
//sets; gets
}

XML Document to String

First you need to get rid of all newline characters in all your text nodes. Then you can use an identity transform to output your DOM tree. Look at the javadoc for TransformerFactory#newTransformer().

Wi-Fi Direct and iOS Support

According to this thread:

The peer-to-peer Wi-Fi implemented by iOS (and recent versions of OS X) is not compatible with Wi-Fi Direct. Note Just as an aside, you can access peer-to-peer Wi-Fi without using Multipeer Connectivity. The underlying technology is Bonjour + TCP/IP, and you can access that directly from your app. The WiTap sample code shows how.

Find and replace specific text characters across a document with JS

Here is something that might help someone looking for this answer: The following uses jquery it searches the whole document and only replaces the text. for example if we had

<a href="/i-am/123/a/overpopulation">overpopulation</a>

and we wanted to add a span with the class overpop around the word overpopulation

<a href="/i-am/123/a/overpopulation"><span class="overpop">overpopulation</span></a>

we would run the following

        $("*:containsIN('overpopulation')").filter(
            function() {
                return $(this).find("*:contains('" + str + "')").length == 0
            }
        ).html(function(_, html) {
            if (html != 'undefined') {
                return html.replace(/(overpopulation)/gi, '<span class="overpop">$1</span>');
            }

        });

the search is case insensitive searches the whole document and only replaces the text portions in this case we are searching for the string 'overpopulation'

    $.extend($.expr[":"], {
        "containsIN": function(elem, i, match, array) {
            return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
        }
    });

Import SQL dump into PostgreSQL database

I believe that you want to run in psql:

\i C:/database/db-backup.sql

How to use Macro argument as string literal?

Use the preprocessor # operator:

#define CALL_DO_SOMETHING(VAR) do_something(#VAR, VAR);

How do I view an older version of an SVN file?

It is also interesting to compare the file of the current working revision with the same file of another revision.

You can do as follows:

$ svn diff -r34 file

How can I embed a YouTube video on GitHub wiki pages?

If you like HTML tags more than markdown + center alignment:

_x000D_
_x000D_
<div align="center">_x000D_
  <a href="https://www.youtube.com/watch?v=YOUTUBE_VIDEO_ID_HERE"><img src="https://img.youtube.com/vi/YOUTUBE_VIDEO_ID_HERE/0.jpg" alt="IMAGE ALT TEXT"></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

cannot import name patterns

Pattern module in not available from django 1.8. So you need to remove pattern from your import and do something similar to the following:

from django.conf.urls import include, url
from django.contrib import admin

admin.autodiscover()

urlpatterns = [                 
    # here we are not using pattern module like in previous django versions
    url(r'^admin/', include(admin.site.urls)),
]

How to use multiprocessing queue in Python?

I had a look at multiple answers across stack overflow and the web while trying to set-up a way of doing multiprocessing using queues for passing around large pandas dataframes. It seemed to me that every answer was re-iterating the same kind of solutions without any consideration of the multitude of edge cases one will definitely come across when setting up calculations like these. The problem is that there is many things at play at the same time. The number of tasks, the number of workers, the duration of each task and possible exceptions during task execution. All of these make synchronization tricky and most answers do not address how you can go about it. So this is my take after fiddling around for a few hours, hopefully this will be generic enough for most people to find it useful.

Some thoughts before any coding examples. Since queue.Empty or queue.qsize() or any other similar method is unreliable for flow control, any code of the like

while True:
    try:
        task = pending_queue.get_nowait()
    except queue.Empty:
        break

is bogus. This will kill the worker even if milliseconds later another task turns up in the queue. The worker will not recover and after a while ALL the workers will disappear as they randomly find the queue momentarily empty. The end result will be that the main multiprocessing function (the one with the join() on the processes) will return without all the tasks having completed. Nice. Good luck debugging through that if you have thousands of tasks and a few are missing.

The other issue is the use of sentinel values. Many people have suggested adding a sentinel value in the queue to flag the end of the queue. But to flag it to whom exactly? If there is N workers, assuming N is the number of cores available give or take, then a single sentinel value will only flag the end of the queue to one worker. All the other workers will sit waiting for more work when there is none left. Typical examples I've seen are

while True:
    task = pending_queue.get()
    if task == SOME_SENTINEL_VALUE:
        break

One worker will get the sentinel value while the rest will wait indefinitely. No post I came across mentioned that you need to submit the sentinel value to the queue AT LEAST as many times as you have workers so that ALL of them get it.

The other issue is the handling of exceptions during task execution. Again these should be caught and managed. Moreover, if you have a completed_tasks queue you should independently count in a deterministic way how many items are in the queue before you decide that the job is done. Again relying on queue sizes is bound to fail and returns unexpected results.

In the example below, the par_proc() function will receive a list of tasks including the functions with which these tasks should be executed alongside any named arguments and values.

import multiprocessing as mp
import dill as pickle
import queue
import time
import psutil

SENTINEL = None


def do_work(tasks_pending, tasks_completed):
    # Get the current worker's name
    worker_name = mp.current_process().name

    while True:
        try:
            task = tasks_pending.get_nowait()
        except queue.Empty:
            print(worker_name + ' found an empty queue. Sleeping for a while before checking again...')
            time.sleep(0.01)
        else:
            try:
                if task == SENTINEL:
                    print(worker_name + ' no more work left to be done. Exiting...')
                    break

                print(worker_name + ' received some work... ')
                time_start = time.perf_counter()
                work_func = pickle.loads(task['func'])
                result = work_func(**task['task'])
                tasks_completed.put({work_func.__name__: result})
                time_end = time.perf_counter() - time_start
                print(worker_name + ' done in {} seconds'.format(round(time_end, 5)))
            except Exception as e:
                print(worker_name + ' task failed. ' + str(e))
                tasks_completed.put({work_func.__name__: None})


def par_proc(job_list, num_cpus=None):

    # Get the number of cores
    if not num_cpus:
        num_cpus = psutil.cpu_count(logical=False)

    print('* Parallel processing')
    print('* Running on {} cores'.format(num_cpus))

    # Set-up the queues for sending and receiving data to/from the workers
    tasks_pending = mp.Queue()
    tasks_completed = mp.Queue()

    # Gather processes and results here
    processes = []
    results = []

    # Count tasks
    num_tasks = 0

    # Add the tasks to the queue
    for job in job_list:
        for task in job['tasks']:
            expanded_job = {}
            num_tasks = num_tasks + 1
            expanded_job.update({'func': pickle.dumps(job['func'])})
            expanded_job.update({'task': task})
            tasks_pending.put(expanded_job)

    # Use as many workers as there are cores (usually chokes the system so better use less)
    num_workers = num_cpus

    # We need as many sentinels as there are worker processes so that ALL processes exit when there is no more
    # work left to be done.
    for c in range(num_workers):
        tasks_pending.put(SENTINEL)

    print('* Number of tasks: {}'.format(num_tasks))

    # Set-up and start the workers
    for c in range(num_workers):
        p = mp.Process(target=do_work, args=(tasks_pending, tasks_completed))
        p.name = 'worker' + str(c)
        processes.append(p)
        p.start()

    # Gather the results
    completed_tasks_counter = 0
    while completed_tasks_counter < num_tasks:
        results.append(tasks_completed.get())
        completed_tasks_counter = completed_tasks_counter + 1

    for p in processes:
        p.join()

    return results

And here is a test to run the above code against

def test_parallel_processing():
    def heavy_duty1(arg1, arg2, arg3):
        return arg1 + arg2 + arg3

    def heavy_duty2(arg1, arg2, arg3):
        return arg1 * arg2 * arg3

    task_list = [
        {'func': heavy_duty1, 'tasks': [{'arg1': 1, 'arg2': 2, 'arg3': 3}, {'arg1': 1, 'arg2': 3, 'arg3': 5}]},
        {'func': heavy_duty2, 'tasks': [{'arg1': 1, 'arg2': 2, 'arg3': 3}, {'arg1': 1, 'arg2': 3, 'arg3': 5}]},
    ]

    results = par_proc(task_list)

    job1 = sum([y for x in results if 'heavy_duty1' in x.keys() for y in list(x.values())])
    job2 = sum([y for x in results if 'heavy_duty2' in x.keys() for y in list(x.values())])

    assert job1 == 15
    assert job2 == 21

plus another one with some exceptions

def test_parallel_processing_exceptions():
    def heavy_duty1_raises(arg1, arg2, arg3):
        raise ValueError('Exception raised')
        return arg1 + arg2 + arg3

    def heavy_duty2(arg1, arg2, arg3):
        return arg1 * arg2 * arg3

    task_list = [
        {'func': heavy_duty1_raises, 'tasks': [{'arg1': 1, 'arg2': 2, 'arg3': 3}, {'arg1': 1, 'arg2': 3, 'arg3': 5}]},
        {'func': heavy_duty2, 'tasks': [{'arg1': 1, 'arg2': 2, 'arg3': 3}, {'arg1': 1, 'arg2': 3, 'arg3': 5}]},
    ]

    results = par_proc(task_list)

    job1 = sum([y for x in results if 'heavy_duty1' in x.keys() for y in list(x.values())])
    job2 = sum([y for x in results if 'heavy_duty2' in x.keys() for y in list(x.values())])

    assert not job1
    assert job2 == 21

Hope that is helpful.

How to Disable landscape mode in Android?

In kotlin same can be programatically achieved using below

requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT

Excel tab sheet names vs. Visual Basic sheet names

In the Excel object model a Worksheet has 2 different name properties:

Worksheet.Name
Worksheet.CodeName

the Name property is read/write and contains the name that appears on the sheet tab. It is user and VBA changeable

the CodeName property is read-only

You can reference a particular sheet as Worksheets("Fred").Range("A1") where Fred is the .Name property or as Sheet1.Range("A1") where Sheet1 is the codename of the worksheet.

List of <p:ajax> events

You might want to look at "JavaScript HTML DOM Events" for a general overview of events:

http://www.w3schools.com/jsref/dom_obj_event.asp

PrimeFaces is built on jQuery, so here's jQuery's "Events" documentation:

http://api.jquery.com/category/events/

http://api.jquery.com/category/events/form-events/

http://api.jquery.com/category/events/keyboard-events/

http://api.jquery.com/category/events/mouse-events/

http://api.jquery.com/category/events/browser-events/

Below, I've listed some of the more common events, with comments about where they can be used (taken from jQuery documentation).

Mouse Events

(Any HTML element can receive these events.)

click

dblclick

mousedown

mousemove

mouseover

mouseout

mouseup

Keyboard Events

(These events can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for these event types.)

keydown

keypress

keyup

Form Events

blur (In recent browsers, the domain of the event has been extended to include all element types.)

change (This event is limited to <input> elements, <textarea> boxes and <select> elements.)

focus (This event is implicitly applicable to a limited set of elements, such as form elements (<input>, <select>, etc.) and links (<a href>). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.)

select (This event is limited to <input type="text"> fields and <textarea> boxes.)

submit (It can only be attached to <form> elements.)

Docker compose port mapping

It seems like the other answers here all misunderstood your question. If I understand correctly, you want to make requests to localhost:6379 (the default for redis) and have them be forwarded, automatically, to the same port on your redis container.

https://unix.stackexchange.com/a/101906/38639 helped me get to the right answer.

First, you'll need to install the nc command on your image. On CentOS, this package is called nmap-ncat, so in the example below, just replace this with the appropriate package if you are using a different OS as your base image.

Next, you'll need to tell it to run a certain command each time the container boots up. You can do this using CMD.

# Add this to your Dockerfile
RUN yum install -y --setopt=skip_missing_names_on_install=False nmap-ncat
COPY cmd.sh /usr/local/bin/cmd.sh
RUN chmod +x /usr/local/bin/cmd.sh
CMD ["/usr/local/bin/cmd.sh"]

Finally, we'll need to set up port-forwarding in cmd.sh. I found that nc, even with the -l and -k options, will occasionally terminate when a request is completed, so I'm using a while-loop to ensure that it's always running.

# cmd.sh
#! /usr/bin/env bash

while nc -l -p 6379 -k -c "nc redis 6379" || true; do true; done &

tail -f /dev/null # Or any other command that never exits

How to create a file in Linux from terminal window?

Depending on what you want the file to contain:

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.

      eg: grep --help > randomtext.txt
          echo "This is some text" > randomtext.txt
    
  • nano /path/to/file or vi /path/to/file (or any other editor emacs,gedit etc)
    It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist


Create the file using cat

$ cat > myfile.txt

Now, just type whatever you want in the file:

Hello World!

CTRL-D to save and exit


There are several possible solutions:

Create an empty file

touch file

>file

echo -n > file

printf '' > file

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file

printf '\n' > file

This is a valid "text file" because it ends in a newline.

Write text into a file

"$EDITOR" file

echo 'text' > file

cat > file <<END \
text
END

printf 'text\n' > file

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

Failed to import new Gradle project: failed to find Build Tools revision *.0.0

It happens because Build Tools revision x doesn't exist.

Today, the latest version is 23.0.2 (subject to change all the time).

The buildToolsVersions you want are included in the Android SDK, normally installed in the <sdk>/build-tools/<buildToolsVersion> directory.

Don't confuse the Android SDK Tools with SDK Build Tools.


Change in your build.gradle's buildToolsVersion to some version installed in <sdk>/build-tools

android {
   buildToolsVersion "23.0.2"
   // ...

}

How do I split a string on a delimiter in Bash?

Two bourne-ish alternatives where neither require bash arrays:

Case 1: Keep it nice and simple: Use a NewLine as the Record-Separator... eg.

IN="[email protected]
[email protected]"

while read i; do
  # process "$i" ... eg.
    echo "[email:$i]"
done <<< "$IN"

Note: in this first case no sub-process is forked to assist with list manipulation.

Idea: Maybe it is worth using NL extensively internally, and only converting to a different RS when generating the final result externally.

Case 2: Using a ";" as a record separator... eg.

NL="
" IRS=";" ORS=";"

conv_IRS() {
  exec tr "$1" "$NL"
}

conv_ORS() {
  exec tr "$NL" "$1"
}

IN="[email protected];[email protected]"
IN="$(conv_IRS ";" <<< "$IN")"

while read i; do
  # process "$i" ... eg.
    echo -n "[email:$i]$ORS"
done <<< "$IN"

In both cases a sub-list can be composed within the loop is persistent after the loop has completed. This is useful when manipulating lists in memory, instead storing lists in files. {p.s. keep calm and carry on B-) }

Python str vs unicode types

unicode is meant to handle text. Text is a sequence of code points which may be bigger than a single byte. Text can be encoded in a specific encoding to represent the text as raw bytes(e.g. utf-8, latin-1...).

Note that unicode is not encoded! The internal representation used by python is an implementation detail, and you shouldn't care about it as long as it is able to represent the code points you want.

On the contrary str in Python 2 is a plain sequence of bytes. It does not represent text!

You can think of unicode as a general representation of some text, which can be encoded in many different ways into a sequence of binary data represented via str.

Note: In Python 3, unicode was renamed to str and there is a new bytes type for a plain sequence of bytes.

Some differences that you can see:

>>> len(u'à')  # a single code point
1
>>> len('à')   # by default utf-8 -> takes two bytes
2
>>> len(u'à'.encode('utf-8'))
2
>>> len(u'à'.encode('latin1'))  # in latin1 it takes one byte
1
>>> print u'à'.encode('utf-8')  # terminal encoding is utf-8
à
>>> print u'à'.encode('latin1') # it cannot understand the latin1 byte
?

Note that using str you have a lower-level control on the single bytes of a specific encoding representation, while using unicode you can only control at the code-point level. For example you can do:

>>> 'àèìòù'
'\xc3\xa0\xc3\xa8\xc3\xac\xc3\xb2\xc3\xb9'
>>> print 'àèìòù'.replace('\xa8', '')
à?ìòù

What before was valid UTF-8, isn't anymore. Using a unicode string you cannot operate in such a way that the resulting string isn't valid unicode text. You can remove a code point, replace a code point with a different code point etc. but you cannot mess with the internal representation.

Can I force a UITableView to hide the separator between empty cells?

For Swift:

self.tableView.tableFooterView = UIView(frame: CGRectZero)

For newest Swift:

self.tableView.tableFooterView = UIView(frame: CGRect.zero)

Drop primary key using script in SQL Server database

You can look up the constraint name in the sys.key_constraints table:

SELECT name
FROM   sys.key_constraints
WHERE  [type] = 'PK'
       AND [parent_object_id] = Object_id('dbo.Student');

If you don't care about the name, but simply want to drop it, you can use a combination of this and dynamic sql:

DECLARE @table NVARCHAR(512), @sql NVARCHAR(MAX);

SELECT @table = N'dbo.Student';

SELECT @sql = 'ALTER TABLE ' + @table 
    + ' DROP CONSTRAINT ' + name + ';'
    FROM sys.key_constraints
    WHERE [type] = 'PK'
    AND [parent_object_id] = OBJECT_ID(@table);

EXEC sp_executeSQL @sql;

This code is from Aaron Bertrand (source).

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

MySQL (and subsequently SQLite) also support the REPLACE INTO syntax:

REPLACE INTO my_table (pk_id, col1) VALUES (5, '123');

This automatically identifies the primary key and finds a matching row to update, inserting a new one if none is found.

Method with a bool return

You are missing the else portion. If all the conditions are false then else will work where you haven't declared and returned anything from else branch.

private bool CheckALl()
{
  if(condition)
  {
    return true
  }
  else
  {
    return false
  }
}

Timeout on a function call

Building on and and enhancing the answer by @piro , you can build a contextmanager. This allows for very readable code which will disable the alaram signal after a successful run (sets signal.alarm(0))

@contextmanager
def timeout(duration):
    def timeout_handler(signum, frame):
        raise Exception(f'block timedout after {duration} seconds')
    signal.signal(signal.SIGALRM, timeout_handler)
    signal.alarm(duration)
    yield
    signal.alarm(0)

def sleeper(duration):
    time.sleep(duration)
    print('finished')

Example usage:

In [19]: with timeout(2):
    ...:     sleeper(1)
    ...:     
finished

In [20]: with timeout(2):
    ...:     sleeper(3)
    ...:         
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
<ipython-input-20-66c78858116f> in <module>()
      1 with timeout(2):
----> 2     sleeper(3)
      3 

<ipython-input-7-a75b966bf7ac> in sleeper(t)
      1 def sleeper(t):
----> 2     time.sleep(t)
      3     print('finished')
      4 

<ipython-input-18-533b9e684466> in timeout_handler(signum, frame)
      2 def timeout(duration):
      3     def timeout_handler(signum, frame):
----> 4         raise Exception(f'block timedout after {duration} seconds')
      5     signal.signal(signal.SIGALRM, timeout_handler)
      6     signal.alarm(duration)

Exception: block timedout after 2 seconds

Update built-in vim on Mac OS X

brew install vim --override-system-vi

Use tnsnames.ora in Oracle SQL Developer

I had the same problem, tnsnames.ora worked fine for all other tools but SQL Developer would not use it. I tried all the suggestions on the web I could find, including the solutions on the link provided here.
Nothing worked.

It turns out that the database was caching backup copies of tnsnames.ora like tnsnames.ora.bk2, tnsnames09042811AM4501.bak, tnsnames.ora.bk etc. These files were not readable by the average user.

I suspect sqldeveloper is pattern matching for the name and it was trying to read one of these backup copies and couldn't. So it just fails gracefully and shows nothing in drop down list.

The solution is to make all the files readable or delete or move the backup copies out of the Admin directory.

Matplotlib-Animation "No MovieWriters Available"

For fellow googlers using Anaconda, install the ffmpeg package:

conda install -c conda-forge ffmpeg

This works on Windows too.

(Original answer used menpo package owner but as mentioned by @harsh their version is a little behind at time of writing)

Cookies on localhost with explicit domain

Cookie needs to specify SameSite attribute, None value used to be the default, but recent browser versions made Lax the default value to have reasonably robust defense against some classes of cross-site request forgery (CSRF) attacks.

Along with SameSite=Lax you should also have Domain=localhost, so your cookie will be associated to localhost and kept. It should look something like this:

document.cookie = `${name}=${value}${expires}; Path=/; Domain=localhost; SameSite=Lax`;

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite

Set up DNS based URL forwarding in Amazon Route53

If you're still having issues with the simple approach, creating an empty bucket then Redirect all requests to another host name under Static web hosting in properties via the console. Ensure that you have set 2 A records in route53, one for final-destination.com and one for redirect-to.final-destination.com. The settings for each of these will be identical, but the name will be different so it matches the names that you set for your buckets / URLs.

Checking for an empty field with MySQL

Yes, what you are doing is correct. You are checking to make sure the email field is not an empty string. NULL means the data is missing. An empty string "" is a blank string with the length of 0.

You can add the null check also

AND (email != "" OR email IS NOT NULL)

How to join (merge) data frames (inner, outer, left, right)

For an inner join on all columns, you could also use fintersect from the data.table-package or intersect from the dplyr-package as an alternative to merge without specifying the by-columns. this will give the rows that are equal between two dataframes:

merge(df1, df2)
#   V1 V2
# 1  B  2
# 2  C  3
dplyr::intersect(df1, df2)
#   V1 V2
# 1  B  2
# 2  C  3
data.table::fintersect(setDT(df1), setDT(df2))
#    V1 V2
# 1:  B  2
# 2:  C  3

Example data:

df1 <- data.frame(V1 = LETTERS[1:4], V2 = 1:4)
df2 <- data.frame(V1 = LETTERS[2:3], V2 = 2:3)

Cannot read property 'getContext' of null, using canvas

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

How to use JNDI DataSource provided by Tomcat in Spring?

I found this solution very helpful in a clean way to remove xml configuration entirely.

Please check this db configuration using JNDI and spring framework. http://www.unotions.com/design/how-to-create-oracleothersql-db-configuration-using-spring-and-maven/

By this article, it explain how easy to create a db confguration based on database jndi(db/test) configuration. once you are done with configuration then all the db repositories are loaded using this jndi. I did find useful. If @Pierre has issue with this then let me know. It's complete solution to write db configuration.

Alter table add multiple columns ms sql

ALTER TABLE Regions
ADD ( HasPhotoInReadyStorage  bit,
     HasPhotoInWorkStorage  bit,
     HasPhotoInMaterialStorage bit *(Missing ,)*
     HasText  bit);

Show default value in Spinner in android

Spinner don't support Hint, i recommend you to make a custom spinner adapter.

check this link : https://stackoverflow.com/a/13878692/1725748

How to clean project cache in Intellij idea like Eclipse's clean?

Try this:

Go into Settings (File > Settings or ctrl+alt+S). Under Project Settings, select the "Compiler" node. On the left, uncheck "Clear output directory on rebuild".

Note that this is a per project setting. If desired, change it in the project template settigs (Settings > Other Settings > Template Settings).

Where is the Docker daemon log?

Docker for Mac (Beta)

~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/log/d??ocker.log

Run JavaScript in Visual Studio Code

Just install nodemon and run

nodemon your_file.js

on vs code terminal.

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

In my case I am using ionic and I simply closed the dialog went to apps in the emulator and ran my app from there instead. This worked. I got the idea of that from here since it was just a time out issue.

Convert timestamp to date in Oracle SQL

You can use:

select to_date(to_char(date_field,'dd/mm/yyyy')) from table

Terminal Commands: For loop with echo

The default shell on OS X is bash. You could write this:

for i in {1..100}; do echo http://www.example.com/${i}.jpg; done

Here is a link to the reference manual of bash concerning loop constructs.

Asynchronously wait for Task<T> to complete with timeout

This is a slightly enhanced version of previous answers.

  • In addition to Lawrence's answer, it cancels the original task when timeout occurs.
  • In addtion to sjb's answer variants 2 and 3, you can provide CancellationToken for the original task, and when timeout occurs, you get TimeoutException instead of OperationCanceledException.
async Task<TResult> CancelAfterAsync<TResult>(
    Func<CancellationToken, Task<TResult>> startTask,
    TimeSpan timeout, CancellationToken cancellationToken)
{
    using (var timeoutCancellation = new CancellationTokenSource())
    using (var combinedCancellation = CancellationTokenSource
        .CreateLinkedTokenSource(cancellationToken, timeoutCancellation.Token))
    {
        var originalTask = startTask(combinedCancellation.Token);
        var delayTask = Task.Delay(timeout, timeoutCancellation.Token);
        var completedTask = await Task.WhenAny(originalTask, delayTask);
        // Cancel timeout to stop either task:
        // - Either the original task completed, so we need to cancel the delay task.
        // - Or the timeout expired, so we need to cancel the original task.
        // Canceling will not affect a task, that is already completed.
        timeoutCancellation.Cancel();
        if (completedTask == originalTask)
        {
            // original task completed
            return await originalTask;
        }
        else
        {
            // timeout
            throw new TimeoutException();
        }
    }
}

Usage

InnerCallAsync may take a long time to complete. CallAsync wraps it with a timeout.

async Task<int> CallAsync(CancellationToken cancellationToken)
{
    var timeout = TimeSpan.FromMinutes(1);
    int result = await CancelAfterAsync(ct => InnerCallAsync(ct), timeout,
        cancellationToken);
    return result;
}

async Task<int> InnerCallAsync(CancellationToken cancellationToken)
{
    return 42;
}

How to prevent XSS with HTML/PHP?

<?php
function xss_clean($data)
{
// Fix &entity\n;
$data = str_replace(array('&amp;','&lt;','&gt;'), array('&amp;amp;','&amp;lt;','&amp;gt;'), $data);
$data = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $data);
$data = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $data);
$data = html_entity_decode($data, ENT_COMPAT, 'UTF-8');

// Remove any attribute starting with "on" or xmlns
$data = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data);

// Remove javascript: and vbscript: protocols
$data = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $data);

// Only works in IE: <span style="width: expression(alert('Ping!'));"></span>
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', '$1>', $data);

// Remove namespaced elements (we do not need them)
$data = preg_replace('#</*\w+:\w[^>]*+>#i', '', $data);

do
{
    // Remove really unwanted tags
    $old_data = $data;
    $data = preg_replace('#</*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|i(?:frame|layer)|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|title|xml)[^>]*+>#i', '', $data);
}
while ($old_data !== $data);

// we are done...
return $data;
}

How to avoid "RuntimeError: dictionary changed size during iteration" error?

You only need to use "copy":

On that's way you iterate over the original dictionary fields and on the fly can change the desired dict (d dict). It's work on each python version, so it's more clear.

In [1]: d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]}

In [2]: for i in d.copy():
   ...:     if not d[i]:
   ...:         d.pop(i)
   ...:         

In [3]: d
Out[3]: {'a': [1], 'b': [1, 2]}

How to pass a JSON array as a parameter in URL

As @RE350 suggested passing the JSON data in the body in the post would be ideal. However, you could still send the json object as a parameter in a GET request, decode the json string in the server-side logic and use it as an object.

For example, if you are on php you could do this (use the appropriate json decode in other languages):

Server request:

http://<php script>?param1={"nameservice":[{"id":89},{"id":3}]}

In the server:

$obj = json_decode($_GET['param1'], true);
$obj["nameservice"][0]["id"]

out put:

89

Parsing string as JSON with single quotes?

If you are sure your JSON is safely under your control (not user input) then you can simply evaluate the JSON. Eval accepts all quote types as well as unquoted property names.

var str = "{'a':1}";
var myObject = (0, eval)('(' + str + ')');

The extra parentheses are required due to how the eval parser works. Eval is not evil when it is used on data you have control over. For more on the difference between JSON.parse and eval() see JSON.parse vs. eval()

UITableView - change section header color

With RubyMotion / RedPotion, paste this into your TableScreen:

  def tableView(_, willDisplayHeaderView: view, forSection: section)
    view.textLabel.textColor = rmq.color.your_text_color
    view.contentView.backgroundColor = rmq.color.your_background_color
  end

Works like a charm!

What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?

enter image description here

Summary:

  • PagingAndSortingRepository extends CrudRepository

  • JpaRepository extends PagingAndSortingRepository

The CrudRepository interface provides methods for CRUD operations, so it allows you to create, read, update and delete records without having to define your own methods.

The PagingAndSortingRepository provides additional methods to retrieve entities using pagination and sorting.

Finally the JpaRepository add some more functionality that is specific to JPA.

How to display items side-by-side without using tables?

What about display:inline?

<html>
      <img src='#' style='display:inline;'/>
      <p style='display:inline;'> Some text </p>
</html>

What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS

In addition to the previous comments browser support for word-wrap seems to be a bit better than for word-break.

Error: Could not find or load main class in intelliJ IDE

Elaborating on Brad Turek's solution... One of the default IntelliJ Java project templates expects a file called Main defining the class Main and main() method entry point. If the method is contained in another file (and class), change the Run configuration:

Run Configuration Window

  1. With the project open in IntelliJ, use the Run:Edit Configurations... menu to open the build configuration window.
  2. If the entry for Main class doesn't list the name of your file containing the class exposing the main() entry method, enter the correct file name. (The configuration in the image is wrong, which is why it's red in the configuration panel.)
  3. My main() entry method is in the class (and file) ScrabbleTest. So changing Main class: to ScrabbleTest fixes the runtime error.

As others have noted you have to ReBuild using the new configuration. I am using a package, but that doesn't seem to make a difference IME. Hope this helps.

How to replace deprecated android.support.v4.app.ActionBarDrawerToggle

you must use import android.support.v7.app.ActionBarDrawerToggle;

and use the constructor

public CustomActionBarDrawerToggle(Activity mActivity,DrawerLayout mDrawerLayout)
{
    super(mActivity, mDrawerLayout, R.string.ns_menu_open, R.string.ns_menu_close);
}

and if the drawer toggle button becomes dark then you must use the supportActionBar provided in the support library.

You can implement supportActionbar from this link: http://developer.android.com/training/basics/actionbar/setting-up.html

Why can't I call a public method in another class?

You have to create a variable of the type of the class, and set it equal to a new instance of the object first.

GradeBook myGradeBook = new GradeBook();

Then call the method on the obect you just created.

myGradeBook.[method you want called]

How can I "disable" zoom on a mobile web page?

Seems like just adding meta tags to index.html doesn't prevent page from zooming. Adding below style will do the magic.

:root {
  touch-action: pan-x pan-y;
  height: 100% 
}

EDIT: Demo: https://no-mobile-zoom.stackblitz.io

Find all files with name containing string

Use grep as follows:

grep -R "touch" .

-R means recurse. If you would rather not go into the subdirectories, then skip it.

-i means "ignore case". You might find this worth a try as well.

How to configure WAMP (localhost) to send email using Gmail?

PEAR: Mail worked for me sending email messages from Gmail. Also, the instructions: How to Send Email from a PHP Script Using SMTP Authentication (Using PEAR::Mail) helped greatly. Thanks, CMS!

substring of an entire column in pandas dataframe

I needed to convert a single column of strings of form nn.n% to float. I needed to remove the % from the element in each row. The attend data frame has two columns.

attend.iloc[:,1:2]=attend.iloc[:,1:2].applymap(lambda x: float(x[:-1]))

Its an extenstion to the original answer. In my case it takes a dataframe and applies a function to each value in a specific column. The function removes the last character and converts the remaining string to float.

How to keep footer at bottom of screen

set its position:fixed and bottom:0 so that it will always reside at bottom of your browser windows

How to always show the vertical scrollbar in a browser?

Add the class to the div you want to be scrollable.

overflow-x: hidden; hides the horizantal scrollbar. While overflow-y: scroll; allows you to scroll vertically.

<!DOCTYPE html>
<html>
<head>
<style>
.scroll {
    width: 500px;
    height: 300px;
    overflow-x: hidden; 
    overflow-y: scroll;
}


</style>
</head>
<body>

<div class="scroll"><h1> DATA </h1></div>

Items in JSON object are out of order using "json.dumps"?

hey i know it is so late for this answer but add sort_keys and assign false to it as follows :

json.dumps({'****': ***},sort_keys=False)

this worked for me

Generate signed apk android studio

  1. Go to Build -> Generate Signed APK in Android Studio.
  2. In the new window appeared, click on Create new... button.
  3. Next enter details as like shown below and click OK -> Next. enter image description here
  4. Select the Build Type as release and click Finish button.
  5. Wait until APK generated successfully message is displayed as like shown below.enter image description here
  6. Click on Show in Explorer to see the signed APK file.

For more details go to this link.

The type or namespace name 'DbContext' could not be found

Visual Studio Express SP1 Right click in Solution Explorer > References > Add Library Package Reference > EntityFramework

What do *args and **kwargs mean?

Also, we use them for managing inheritance.

class Super( object ):
   def __init__( self, this, that ):
       self.this = this
       self.that = that

class Sub( Super ):
   def __init__( self, myStuff, *args, **kw ):
       super( Sub, self ).__init__( *args, **kw )
       self.myStuff= myStuff

x= Super( 2.7, 3.1 )
y= Sub( "green", 7, 6 )

This way Sub doesn't really know (or care) what the superclass initialization is. Should you realize that you need to change the superclass, you can fix things without having to sweat the details in each subclass.

How to specify the actual x axis values to plot as x axis ticks in R

Hope this coding will helps you :)

plot(x,y,xaxt = 'n')

axis(side=1,at=c(1,20,30,50),labels=c("1975","1980","1985","1990"))

Decimal precision and scale in EF Code First

Apparently, you can override the DbContext.OnModelCreating() method and configure the precision like this:

protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Product>().Property(product => product.Price).Precision = 10;
    modelBuilder.Entity<Product>().Property(product => product.Price).Scale = 2;
}

But this is pretty tedious code when you have to do it with all your price-related properties, so I came up with this:

    protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
    {
        var properties = new[]
        {
            modelBuilder.Entity<Product>().Property(product => product.Price),
            modelBuilder.Entity<Order>().Property(order => order.OrderTotal),
            modelBuilder.Entity<OrderDetail>().Property(detail => detail.Total),
            modelBuilder.Entity<Option>().Property(option => option.Price)
        };

        properties.ToList().ForEach(property =>
        {
            property.Precision = 10;
            property.Scale = 2;
        });

        base.OnModelCreating(modelBuilder);
    }

It's good practice that you call the base method when you override a method, even though the base implementation does nothing.

Update: This article was also very helpful.

JavaFX FXML controller - constructor vs initialize method

The initialize method is called after all @FXML annotated members have been injected. Suppose you have a table view you want to populate with data:

class MyController { 
    @FXML
    TableView<MyModel> tableView; 

    public MyController() {
        tableView.getItems().addAll(getDataFromSource()); // results in NullPointerException, as tableView is null at this point. 
    }

    @FXML
    public void initialize() {
        tableView.getItems().addAll(getDataFromSource()); // Perfectly Ok here, as FXMLLoader already populated all @FXML annotated members. 
    }
}

How does "304 Not Modified" work exactly?

Last-Modified : The last modified date for the requested object

If-Modified-Since : Allows a 304 Not Modified to be returned if last modified date is unchanged.

ETag : An ETag is an opaque identifier assigned by a web server to a specific version of a resource found at a URL. If the resource representation at that URL ever changes, a new and different ETag is assigned.

If-None-Match : Allows a 304 Not Modified to be returned if ETag is unchanged.

the browser store cache with a date(Last-Modified) or id(ETag), when you need to request the URL again, the browser send request message with the header:

enter image description here

the server will return 304 when the if statement is False, and browser will use cache.

"Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP

"For me to make it work again I just deleted the files

ib_logfile0 and

ib_logfile1 .

from :

/Applications/MAMP/db/mysql56/ib_logfile0 "

On XAMPP its Xampp/xamppfiles/var/mysql

Got this from PHP Warning: mysqli_connect(): (HY000/2002): Connection refused

JSON - Iterate through JSONArray

JsonArray jsonArray;
Iterator<JsonElement> it = jsonArray.iterator();
while(it.hasNext()){
    System.out.println(it.next());
}

Display a float with two decimal places in Python

String Formatting:

a = 6.789809823
print('%.2f' %a)

OR

print ("{0:.2f}".format(a)) 

Round Function can be used:

print(round(a, 2))

Good thing about round() is that, we can store this result to another variable, and then use it for other purposes.

b = round(a, 2)
print(b)

Difference between JE/JNE and JZ/JNZ

JE and JZ are just different names for exactly the same thing: a conditional jump when ZF (the "zero" flag) is equal to 1.

(Similarly, JNE and JNZ are just different names for a conditional jump when ZF is equal to 0.)

You could use them interchangeably, but you should use them depending on what you are doing:

  • JZ/JNZ are more appropriate when you are explicitly testing for something being equal to zero:

    dec  ecx
    jz   counter_is_now_zero
    
  • JE and JNE are more appropriate after a CMP instruction:

    cmp  edx, 42
    je   the_answer_is_42
    

    (A CMP instruction performs a subtraction, and throws the value of the result away, while keeping the flags; which is why you get ZF=1 when the operands are equal and ZF=0 when they're not.)

3-dimensional array in numpy

No need to go in such deep technicalities, and get yourself blasted. Let me explain it in the most easiest way. We all have studied "Sets" during our school-age in Mathematics. Just consider 3D numpy array as the formation of "sets".

x = np.zeros((2,3,4)) 

Simply Means:

2 Sets, 3 Rows per Set, 4 Columns

Example:

Input

x = np.zeros((2,3,4))

Output

Set # 1 ---- [[[ 0.,  0.,  0.,  0.],  ---- Row 1
               [ 0.,  0.,  0.,  0.],  ---- Row 2
               [ 0.,  0.,  0.,  0.]], ---- Row 3 
    
Set # 2 ----  [[ 0.,  0.,  0.,  0.],  ---- Row 1
               [ 0.,  0.,  0.,  0.],  ---- Row 2
               [ 0.,  0.,  0.,  0.]]] ---- Row 3

Explanation: See? we have 2 Sets, 3 Rows per Set, and 4 Columns.

Note: Whenever you see a "Set of numbers" closed in double brackets from both ends. Consider it as a "set". And 3D and 3D+ arrays are always built on these "sets".

dotnet ef not found in .NET Core 3

For me, The problem was solved after I close Visual Studio and Open it again

XAMPP Object not found error

Make sure you also start the MySQL service in Xampp control panel. This might resolve this.

Leaflet - How to find existing markers, and delete markers?

Have you tried layerGroup yet?

Docs here https://leafletjs.com/reference-1.2.0.html#layergroup

Just create a layer, add all marker to this layer, then you can find and destroy marker easily.

var markers = L.layerGroup()
const marker = L.marker([], {})
markers.addLayer(marker)

Deep-Learning Nan loss reasons

Regularization can help. For a classifier, there is a good case for activity regularization, whether it is binary or a multi-class classifier. For a regressor, kernel regularization might be more appropriate.

Session timeout in ASP.NET

Since ASP.Net core 1.0 (vNext or whatever name is used for it) sessions are implemented differently. I changed the session timeout value in Startup.cs, void ConfigureServices using:

services.AddSession(options => options.IdleTimeout = TimeSpan.FromSeconds(42));

Or if you want to use the appsettings.json file, you can do something like:

// Appsettings.json
"SessionOptions": {
    "IdleTimeout": "00:30:00"
}

// Startup.cs
services.AddSession(options => options.IdleTimeout = TimeSpan.Parse(Config.GetSection("SessionOptions")["IdleTimeout"]));

SeekBar and media player in android

Code in Kotlin:

var updateSongTime = object : Runnable {
            override fun run() {
                val getCurrent = mediaPlayer?.currentPosition
                startTimeText?.setText(String.format("%d:%d",
                        TimeUnit.MILLISECONDS.toMinutes(getCurrent?.toLong() as Long),
                        TimeUnit.MILLISECONDS.toSeconds(getCurrent?.toLong()) -
                                TimeUnit.MINUTES.toSeconds(
                                        TimeUnit.MILLISECONDS.toMinutes(getCurrent?.toLong()))))
                seekBar?.setProgress(getCurrent?.toInt() as Int)
                Handler().postDelayed(this, 1000)
            }
        }

For changing media player audio file every second

If user drags the seek bar then following code snippet can be use

Statified.seekBar?.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
                if(b && Statified.mediaPlayer != null){
                    Statified.mediaPlayer?.seekTo(i)
                }

            }
            override fun onStartTrackingTouch(seekBar: SeekBar) {}
            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        })

Returning a pointer to a vector element in c++

You can use the data function of the vector:

Returns a pointer to the first element in the vector.

If don't want the pointer to the first element, but by index, then you can try, for example:

//the index to the element that you want to receive its pointer:
int i = n; //(n is whatever integer you want)

std::vector<myObject> vec;
myObject* ptr_to_first = vec.data();

//or

std::vector<myObject>* vec;
myObject* ptr_to_first = vec->data();

//then

myObject element = ptr_to_first[i]; //element at index i
myObject* ptr_to_element = &element;

Python style - line continuation with strings?

Since adjacent string literals are automatically joint into a single string, you can just use the implied line continuation inside parentheses as recommended by PEP 8:

print("Why, hello there wonderful "
      "stackoverflow people!")

Fastest way to update 120 Million records

If your int_field is indexed, remove the index before running the update. Then create your index again...

5 hours seem like a lot for 120 million recs.

What is "stdafx.h" used for in Visual Studio?

"Stdafx.h" is a precompiled header.It include file for standard system include files and for project-specific include files that are used frequently but are changed infrequently.which reduces compile time and Unnecessary Processing.

Precompiled Header stdafx.h is basically used in Microsoft Visual Studio to let the compiler know the files that are once compiled and no need to compile it from scratch. You can read more about it

http://www.cplusplus.com/articles/1TUq5Di1/

https://docs.microsoft.com/en-us/cpp/ide/precompiled-header-files?view=vs-2017

laravel Eloquent ORM delete() method

$model=User::where('id',$id)->delete();

How to print like printf in Python3?

Python 3.6 introduced f-strings for inline interpolation. What's even nicer is it extended the syntax to also allow format specifiers with interpolation. Something I've been working on while I googled this (and came across this old question!):

print(f'{account:40s} ({ratio:3.2f}) -> AUD {splitAmount}')

PEP 498 has the details. And... it sorted my pet peeve with format specifiers in other langs -- allows for specifiers that themselves can be expressions! Yay! See: Format Specifiers.

Specify the date format in XMLGregorianCalendar

There isn’t really an ideal conversion, but I would like to supply a couple of options.

java.time

First, you should use LocalDate from java.time, the modern Java date and time API, for parsing and holding your date. Avoid Date and SimpleDateFormat since they have design problems and also are long outdated. The latter in particular is notoriously troublesome.

    DateTimeFormatter originalDateFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");

    String dateString = "13/06/1983";
    LocalDate date = LocalDate.parse(dateString, originalDateFormatter);
    System.out.println(date);

The output is:

1983-06-13

Do you need to go any further? LocalDate.toString() produces the format you asked about.

Format and parse

Assuming that you do require an XMLGregorianCalendar the first and easy option for converting is:

    XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
            .newXMLGregorianCalendar(date.toString());
    System.out.println(xmlDate);

1983-06-13

Formatting to a string and parsing it back feels like a waste to me, but as I said, it’s easy and I don’t think that there are any surprises about the result being as expected.

Pass year, month and day of month individually

    XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
            .newXMLGregorianCalendarDate(date.getYear(), date.getMonthValue(),
                    date.getDayOfMonth(), DatatypeConstants.FIELD_UNDEFINED);

The result is the same as before. We need to make explicit that we don’t want a time zone offset (this is what DatatypeConstants.FIELD_UNDEFINED specifies). In case someone is wondering, both LocalDate and XMLGregorianCalendar number months the way humans do, so there is no adding or subtracting 1.

Convert through GregorianCalendar

I only show you this option because I somehow consider it the official way: convert LocalDate to ZonedDateTime, then to GregorianCalendar and finally to XMLGregorianCalendar.

    ZonedDateTime dateTime = date.atStartOfDay(ZoneOffset.UTC);
    GregorianCalendar gregCal = GregorianCalendar.from(dateTime);
    XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
            .newXMLGregorianCalendar(gregCal);
    xmlDate.setTime(DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED,
            DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED);
    xmlDate.setTimezone(DatatypeConstants.FIELD_UNDEFINED);

I like the conversion itself since we neither need to use strings nor need to pass individual fields (with care to do it in the right order). What I don’t like is that we have to pass a time of day and a time zone offset and then wipe out those fields manually afterwards.

Access Controller method from another controller in Laravel 5

You can access your controller method like this:

app('App\Http\Controllers\PrintReportController')->getPrintReport();

This will work, but it's bad in terms of code organisation (remember to use the right namespace for your PrintReportController)

You can extend the PrintReportController so SubmitPerformanceController will inherit that method

class SubmitPerformanceController extends PrintReportController {
     // ....
}

But this will also inherit all other methods from PrintReportController.

The best approach will be to create a trait (e.g. in app/Traits), implement the logic there and tell your controllers to use it:

trait PrintReport {

    public function getPrintReport() {
        // .....
    }
}

Tell your controllers to use this trait:

class PrintReportController extends Controller {
     use PrintReport;
}

class SubmitPerformanceController extends Controller {
     use PrintReport;
}

Both solutions make SubmitPerformanceController to have getPrintReport method so you can call it with $this->getPrintReport(); from within the controller or directly as a route (if you mapped it in the routes.php)

You can read more about traits here.

CMD (command prompt) can't go to the desktop

You need to use the change directory command 'cd' to change directory

cd C:\Users\MyName\Desktop

you can use cd \d to change the drive as well.

link for additional resources http://ss64.com/nt/cd.html

AngularJs ReferenceError: $http is not defined

Just to complete Amit Garg answer, there are several ways to inject dependencies in AngularJS.


You can also use $inject to add a dependency:

var MyController = function($scope, $http) {
  // ...
}
MyController.$inject = ['$scope', '$http'];

Regular expression to find two strings anywhere in input

This is fairly easy on processing power required:

(string1(.|\n)*string2)|(string2(.|\n)*string1)

I used this in visual studio 2013 to find all files that had both string 1 and 2 in it.

Better way to convert an int to a boolean

Joking aside, if you're only expecting your input integer to be a zero or a one, you should really be checking that this is the case.

int yourInteger = whatever;
bool yourBool;
switch (yourInteger)
{
    case 0: yourBool = false; break;
    case 1: yourBool = true;  break;
    default:
        throw new InvalidOperationException("Integer value is not valid");
}

The out-of-the-box Convert won't check this; nor will yourInteger (==|!=) (0|1).

Aligning textviews on the left and right edges in Android layout

Dave Webb's answer did work for me. Thanks! Here my code, hope this helps someone!

<RelativeLayout
    android:background="#FFFFFF"
    android:layout_width="match_parent"
    android:minHeight="30dp"
    android:layout_height="wrap_content">
    <TextView
        android:height="25dp"
        android:layout_width="wrap_content"
        android:layout_marginLeft="20dp"
        android:text="ABA Type"
        android:padding="3dip"
        android:layout_gravity="center_vertical"
        android:gravity="left|center_vertical"
        android:layout_height="match_parent" />
    <TextView
        android:background="@color/blue"
        android:minWidth="30px"
        android:minHeight="30px"
        android:layout_column="1"
        android:id="@+id/txtABAType"
        android:singleLine="false"
        android:layout_gravity="center_vertical"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginRight="20dp"
        android:layout_width="wrap_content" />
</RelativeLayout>

Image: Image

How to pause / sleep thread or process in Android?

I know this is an old thread, but in the Android documentation I found a solution that worked very well for me...

new CountDownTimer(30000, 1000) {

    public void onTick(long millisUntilFinished) {
        mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
    }

    public void onFinish() {
        mTextField.setText("done!");
    }
}.start();

https://developer.android.com/reference/android/os/CountDownTimer.html

Hope this helps someone...

What is JSONP, and why was it created?

Because you can ask the server to prepend a prefix to the returned JSON object. E.g

function_prefix(json_object);

in order for the browser to eval "inline" the JSON string as an expression. This trick makes it possible for the server to "inject" javascript code directly in the Client browser and this with bypassing the "same origin" restrictions.

In other words, you can achieve cross-domain data exchange.


Normally, XMLHttpRequest doesn't permit cross-domain data-exchange directly (one needs to go through a server in the same domain) whereas:

<script src="some_other_domain/some_data.js&prefix=function_prefix>` one can access data from a domain different than from the origin.


Also worth noting: even though the server should be considered as "trusted" before attempting that sort of "trick", the side-effects of possible change in object format etc. can be contained. If a function_prefix (i.e. a proper js function) is used to receive the JSON object, the said function can perform checks before accepting/further processing the returned data.

Add new attribute (element) to JSON object using JavaScript

With ECMAScript since 2015 you can use Spread Syntax ( …three dots):

let  people = { id: 4 ,firstName: 'John'};
people = { ...people, secondName: 'Fogerty'};

It's allow you to add sub objects:

people = { ...people, city: { state: 'California' }};

the result would be:

{  
   "id": 4,
   "firstName": "John",
   "secondName": "Forget",
   "city": {  
      "state": "California"
   }
}

You also can merge objects:

var mergedObj = { ...obj1, ...obj2 };

How do I create/edit a Manifest file?

The simplest way to create a manifest is:

Project Properties -> Security -> Click "enable ClickOnce security settings" 
(it will generate default manifest in your project Properties) -> then Click 
it again in order to uncheck that Checkbox -> open your app.maifest and edit 
it as you wish.

Manifest location preview

How do I create a Bash alias?

I just open zshrc with sublime, and edit it.

subl .zshrc

And add this on sublime:

alias blah="/usr/bin/blah"

Run this in terminal:

source ~/.bashrc

Done.

How do you use NSAttributedString?

I think, it is a very convenient way to use regular expressions to find a range for applying attributes. This is how I did it:

NSMutableAttributedString *goodText = [[NSMutableAttributedString alloc] initWithString:articleText];

NSRange range = [articleText rangeOfString:@"\\[.+?\\]" options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
if (range.location != NSNotFound) {
    [goodText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Georgia" size:16] range:range];
    [goodText addAttribute:NSForegroundColorAttributeName value:[UIColor brownColor] range:range];
}

NSString *regEx = [NSString stringWithFormat:@"%@.+?\\s", [self.article.titleText substringToIndex:0]];
range = [articleText rangeOfString:regEx options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
if (range.location != NSNotFound) {
    [goodText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Georgia-Bold" size:20] range:range];
    [goodText addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range];
}

[self.textView setAttributedText:goodText];

I was searching for a list of available attributes and didn't find them here and in a class reference's first page. So I decided to post here information on that.

Standard Attributes

Attributed strings support the following standard attributes for text. If the key is not in the dictionary, then use the default values described below.

NSString *NSFontAttributeName;
NSString *NSParagraphStyleAttributeName;
NSString *NSForegroundColorAttributeName;
NSString *NSUnderlineStyleAttributeName;
NSString *NSSuperscriptAttributeName;
NSString *NSBackgroundColorAttributeName;
NSString *NSAttachmentAttributeName;
NSString *NSLigatureAttributeName;
NSString *NSBaselineOffsetAttributeName;
NSString *NSKernAttributeName;
NSString *NSLinkAttributeName;
NSString *NSStrokeWidthAttributeName;
NSString *NSStrokeColorAttributeName;
NSString *NSUnderlineColorAttributeName;
NSString *NSStrikethroughStyleAttributeName;
NSString *NSStrikethroughColorAttributeName;
NSString *NSShadowAttributeName;
NSString *NSObliquenessAttributeName;
NSString *NSExpansionAttributeName;
NSString *NSCursorAttributeName;
NSString *NSToolTipAttributeName;
NSString *NSMarkedClauseSegmentAttributeName;
NSString *NSWritingDirectionAttributeName;
NSString *NSVerticalGlyphFormAttributeName;
NSString *NSTextAlternativesAttributeName;

NSAttributedString programming guide

A full class reference is here.

Is it possible to dynamically compile and execute C# code fragments?

I recently needed to spawn processes for unit testing. This post was useful as I created a simple class to do that with either code as a string or code from my project. To build this class, you'll need the ICSharpCode.Decompiler and Microsoft.CodeAnalysis NuGet packages. Here's the class:

using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.CSharp;
using ICSharpCode.Decompiler.TypeSystem;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

public static class CSharpRunner
{
   public static object Run(string snippet, IEnumerable<Assembly> references, string typeName, string methodName, params object[] args) =>
      Invoke(Compile(Parse(snippet), references), typeName, methodName, args);

   public static object Run(MethodInfo methodInfo, params object[] args)
   {
      var refs = methodInfo.DeclaringType.Assembly.GetReferencedAssemblies().Select(n => Assembly.Load(n));
      return Invoke(Compile(Decompile(methodInfo), refs), methodInfo.DeclaringType.FullName, methodInfo.Name, args);
   }

   private static Assembly Compile(SyntaxTree syntaxTree, IEnumerable<Assembly> references = null)
   {
      if (references is null) references = new[] { typeof(object).Assembly, typeof(Enumerable).Assembly };
      var mrefs = references.Select(a => MetadataReference.CreateFromFile(a.Location));
      var compilation = CSharpCompilation.Create(Path.GetRandomFileName(), new[] { syntaxTree }, mrefs, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

      using (var ms = new MemoryStream())
      {
         var result = compilation.Emit(ms);
         if (result.Success)
         {
            ms.Seek(0, SeekOrigin.Begin);
            return Assembly.Load(ms.ToArray());
         }
         else
         {
            throw new InvalidOperationException(string.Join("\n", result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error).Select(d => $"{d.Id}: {d.GetMessage()}")));
         }
      }
   }

   private static SyntaxTree Decompile(MethodInfo methodInfo)
   {
      var decompiler = new CSharpDecompiler(methodInfo.DeclaringType.Assembly.Location, new DecompilerSettings());
      var typeInfo = decompiler.TypeSystem.MainModule.Compilation.FindType(methodInfo.DeclaringType).GetDefinition();
      return Parse(decompiler.DecompileTypeAsString(typeInfo.FullTypeName));
   }

   private static object Invoke(Assembly assembly, string typeName, string methodName, object[] args)
   {
      var type = assembly.GetType(typeName);
      var obj = Activator.CreateInstance(type);
      return type.InvokeMember(methodName, BindingFlags.Default | BindingFlags.InvokeMethod, null, obj, args);
   }

   private static SyntaxTree Parse(string snippet) => CSharpSyntaxTree.ParseText(snippet);
}

To use it, call the Run methods as below:

void Demo1()
{
   const string code = @"
   public class Runner
   {
      public void Run() { System.IO.File.AppendAllText(@""C:\Temp\NUnitTest.txt"", System.DateTime.Now.ToString(""o"") + ""\n""); }
   }";

   CSharpRunner.Run(code, null, "Runner", "Run");
}

void Demo2()
{
   CSharpRunner.Run(typeof(Runner).GetMethod("Run"));
}

public class Runner
{
   public void Run() { System.IO.File.AppendAllText(@"C:\Temp\NUnitTest.txt", System.DateTime.Now.ToString("o") + "\n"); }
}

Convert String to Date in MS Access Query

If you need to display all the records after 2014-09-01, add this to your query:

SELECT * FROM Events
WHERE Format(Events.DATE_TIME,'yyyy-MM-dd hh:mm:ss')  >= Format("2014-09-01 00:00:00","yyyy-MM-dd hh:mm:ss")

How to create an email form that can send email using html

As the others said, you can't. You can find good examples of HTML-php forms on the web, here's a very useful link that combines HTML with javascript for validation and php for sending the email.

Please check the full article (includes zip example) in the source: http://www.html-form-guide.com/contact-form/php-email-contact-form.html

HTML:

<form method="post" name="contact_form"
action="contact-form-handler.php">
    Your Name:
    <input type="text" name="name">
    Email Address:
    <input type="text" name="email">
    Message:
    <textarea name="message"></textarea>
    <input type="submit" value="Submit">
</form>

JS:

<script language="JavaScript">
var frmvalidator  = new Validator("contactform");
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email");
frmvalidator.addValidation("email","email",
  "Please enter a valid email address");
</script>

PHP:

<?php
$errors = '';
$myemail = '[email protected]';//<-----Put Your email address here.
if(empty($_POST['name'])  ||
   empty($_POST['email']) ||
   empty($_POST['message']))
{
    $errors .= "\n Error: all fields are required";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
    $errors .= "\n Error: Invalid email address";
}

if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email_address\n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.html');
}
?>

Calculate median in c#

Thanks Rafe, this takes into account the issues your replyers posted.

public static double GetMedian(double[] sourceNumbers) {
        //Framework 2.0 version of this method. there is an easier way in F4        
        if (sourceNumbers == null || sourceNumbers.Length == 0)
            throw new System.Exception("Median of empty array not defined.");

        //make sure the list is sorted, but use a new array
        double[] sortedPNumbers = (double[])sourceNumbers.Clone();
        Array.Sort(sortedPNumbers);

        //get the median
        int size = sortedPNumbers.Length;
        int mid = size / 2;
        double median = (size % 2 != 0) ? (double)sortedPNumbers[mid] : ((double)sortedPNumbers[mid] + (double)sortedPNumbers[mid - 1]) / 2;
        return median;
    }

How to send parameters from a notification-click to an activity?

AndroidManifest.xml

Include launchMode="singleTop"

<activity android:name=".MessagesDetailsActivity"
        android:launchMode="singleTop"
        android:excludeFromRecents="true"
        />

SMSReceiver.java

Set the flags for the Intent and PendingIntent

Intent intent = new Intent(context, MessagesDetailsActivity.class);
    intent.putExtra("smsMsg", smsObject.getMsg());
    intent.putExtra("smsAddress", smsObject.getAddress());
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent contentIntent = PendingIntent.getActivity(context, notification_id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

MessageDetailsActivity.java

onResume() - gets called everytime, load the extras.

Intent intent = getIntent();
    String extraAddress = intent.getStringExtra("smsAddress");
    String extraBody = intent.getStringExtra("smsMsg");

Hope it helps, it was based on other answers here on stackoverflow, but this is the most updated that worked for me.

Complex JSON nesting of objects and arrays

Make sure you follow the language definition for JSON. In your second example, the section:

"labs":[{
    ""
}]

Is invalid since an object must be composed of zero or more key-value pairs "a" : "b", where "b" may be any valid value. Some parsers may automatically interpret { "" } to be { "" : null }, but this is not a clearly defined case.

Also, you are using a nested array of objects [{}] quite a bit. I would only do this if:

  1. There is no good "identifier" string for each object in the array.
  2. There is some clear reason for having an array over a key-value for that entry.

Is there a way that I can check if a data attribute exists?

I've found this works better with dynamically set data elements:

if ($("#myelement").data('myfield')) {
  ...
}

Append text using StreamWriter

using(StreamWriter writer = new StreamWriter("debug.txt", true))
{
  writer.WriteLine("whatever you text is");
}

The second "true" parameter tells it to append.

http://msdn.microsoft.com/en-us/library/36b035cb.aspx

Update Item to Revision vs Revert to Revision

To understand how the state of your working copy is different in both scenarios, you must understand the concept of the BASE revision:

BASE

The revision number of an item in a working copy. If the item has been locally modified, this refers to the way the item appears without those local modifications.

Your working copy contains a snapshot of each file (hidden in a .svn folder) in this BASE revision, meaning as it was when last retrieved from the repository. This explains why working copies take 2x the space and how it is possible that you can examine and even revert local modifications without a network connection.

Update item to Revision changes this base revision, making BASE out of date. When you try to commit local modifications, SVN will notice that your BASE does not match the repository HEAD. The commit will be refused until you do an update (and possibly a merge) to fix this.

Revert to revision does not change BASE. It is conceptually almost the same as manually editing the file to match an earlier revision.

Java variable number or arguments for a method

Variable number of arguments

It is possible to pass a variable number of arguments to a method. However, there are some restrictions:

  • The variable number of parameters must all be the same type
  • They are treated as an array within the method
  • They must be the last parameter of the method

To understand these restrictions, consider the method, in the following code snippet, used to return the largest integer in a list of integers:

private static int largest(int... numbers) {
     int currentLargest = numbers[0];
     for (int number : numbers) {
        if (number > currentLargest) {
            currentLargest = number;
        }
     }
     return currentLargest;
}

source Oracle Certified Associate Java SE 7 Programmer Study Guide 2012

How to Make A Chevron Arrow Using CSS?

Left Right Arrow with hover effect using Roko C. Buljan box-shadow trick

_x000D_
_x000D_
.arr {_x000D_
  display: inline-block;_x000D_
  padding: 1.2em;_x000D_
  box-shadow: 8px 8px 0 2px #777 inset;_x000D_
}_x000D_
.arr.left {_x000D_
  transform: rotate(-45deg);_x000D_
}_x000D_
.arr.right {_x000D_
  transform: rotate(135deg);_x000D_
}_x000D_
.arr:hover {_x000D_
  box-shadow: 8px 8px 0 2px #000 inset_x000D_
}
_x000D_
<div class="arr left"></div>_x000D_
<div class="arr right"></div>
_x000D_
_x000D_
_x000D_

After MySQL install via Brew, I get the error - The server quit without updating PID file

Solved this using sudo chown -R _mysql:_mysql /usr/local/var/mysql Thanks to Matteo Alessani

Can I Set "android:layout_below" at Runtime Programmatically?

Kotlin version with infix function

infix fun View.below(view: View) {
      (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.BELOW, view.id)
}

Then you can write:

view1 below view2

Or you can call it as a normal function:

view1.below(view2)

How to remove the last character from a string?

Suppose total length of my string=24 I want to cut last character after position 14 to end, mean I want starting 14 to be there. So I apply following solution.

String date = "2019-07-31T22:00:00.000Z";
String result = date.substring(0, date.length() - 14);

Find an item in List by LINQ?

You want to search an object in object list.

This will help you in getting the first or default value in your Linq List search.

var item = list.FirstOrDefault(items =>  items.Reference == ent.BackToBackExternalReferenceId);

or

var item = (from items in list
    where items.Reference == ent.BackToBackExternalReferenceId
    select items).FirstOrDefault();

jQuery function to get all unique elements from an array?

function array_unique(array) {
    var unique = [];
    for ( var i = 0 ; i < array.length ; ++i ) {
        if ( unique.indexOf(array[i]) == -1 )
            unique.push(array[i]);
    }
    return unique;
}

Java Error opening registry key

I had the same:

Error opening registry key 'Software\JavaSoft\Java Runtime Environment

Clearing Windows\SysWOW64 doesn't help for Win7

In my case it installing JDK8 offline helped (from link)