Programs & Examples On #Wcf 4

Adobe Acrobat Pro make all pages the same dimension

You have to use the Print to a New PDF option using the PDF printer. Once in the dialog box, set the page scaling to 100% and set your page size. Once you do that, your new PDF will be uniform in page sizes.

Set element width or height in Standards Mode

The style property lets you specify values for CSS properties.

The CSS width property takes a length as its value.

Lengths require units. In quirks mode, browsers tend to assume pixels if provided with an integer instead of a length. Specify units.

e1.style.width = "400px";

Why is HttpClient BaseAddress not working?

It turns out that, out of the four possible permutations of including or excluding trailing or leading forward slashes on the BaseAddress and the relative URI passed to the GetAsync method -- or whichever other method of HttpClient -- only one permutation works. You must place a slash at the end of the BaseAddress, and you must not place a slash at the beginning of your relative URI, as in the following example.

using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
    client.BaseAddress = new Uri("http://something.com/api/");
    var response = await client.GetAsync("resource/7");
}

Even though I answered my own question, I figured I'd contribute the solution here since, again, this unfriendly behavior is undocumented. My colleague and I spent most of the day trying to fix a problem that was ultimately caused by this oddity of HttpClient.

Javascript Object push() function

Objects does not support push property, but you can save it as well using the index as key,

_x000D_
_x000D_
var tempData = {};_x000D_
for ( var index in data ) {_x000D_
  if ( data[index].Status == "Valid" ) { _x000D_
    tempData[index] = data; _x000D_
  } _x000D_
 }_x000D_
data = tempData;
_x000D_
_x000D_
_x000D_

I think this is easier if remove the object if its status is invalid, by doing.

_x000D_
_x000D_
for(var index in data){_x000D_
  if(data[index].Status == "Invalid"){ _x000D_
    delete data[index]; _x000D_
  } _x000D_
}
_x000D_
_x000D_
_x000D_

And finally you don't need to create a var temp –

PHP Pass by reference in foreach

I had to spend a few hours to figure out why a[3] is changing on each iteration. This is the explanation at which I arrived.

There are two types of variables in PHP: normal variables and reference variables. If we assign a reference of a variable to another variable, the variable becomes a reference variable.

for example in

$a = array('zero', 'one', 'two', 'three');

if we do

$v = &$a[0]

the 0th element ($a[0]) becomes a reference variable. $v points towards that variable; therefore, if we make any change to $v, it will be reflected in $a[0] and vice versa.

now if we do

$v = &$a[1]

$a[1] will become a reference variable and $a[0] will become a normal variable (Since no one else is pointing to $a[0] it is converted to a normal variable. PHP is smart enough to make it a normal variable when no one else is pointing towards it)

This is what happens in the first loop

foreach ($a as &$v) {

}

After the last iteration $a[3] is a reference variable.

Since $v is pointing to $a[3] any change to $v results in a change to $a[3]

in the second loop,

foreach ($a as $v) {
  echo $v.'-'.$a[3].PHP_EOL;
}

in each iteration as $v changes, $a[3] changes. (because $v still points to $a[3]). This is the reason why $a[3] changes on each iteration.

In the iteration before the last iteration, $v is assigned the value 'two'. Since $v points to $a[3], $a[3] now gets the value 'two'. Keep this in mind.

In the last iteration, $v (which points to $a[3]) now has the value of 'two', because $a[3] was set to two in the previous iteration. two is printed. This explains why 'two' is repeated when $v is printed in the last iteration.

Sending data from HTML form to a Python script in Flask

You need a Flask view that will receive POST data and an HTML form that will send it.

from flask import request

@app.route('/addRegion', methods=['POST'])
def addRegion():
    ...
    return (request.form['projectFilePath'])
<form action="{{ url_for('addRegion') }}" method="post">
    Project file path: <input type="text" name="projectFilePath"><br>
    <input type="submit" value="Submit">
</form>

Add default value of datetime field in SQL Server to a timestamp

While the marked answer is correct with:

ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn

You should always be aware of timezones when adding default datetime values in to a column.

Say for example, this datetime value is designed to indicate when a member joined a website and you want it to be displayed back to the user, GETDATE() will give you the server time so could show discrepancies if the user is in a different locale to the server.

If you expect to deal with international users, it is better in some cases to use GETUTCDATE(), which:

Returns the current database system timestamp as a datetime value. The database time zone offset is not included. This value represents the current UTC time (Coordinated Universal Time). This value is derived from the operating system of the computer on which the instance of SQL Server is running.

ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETUTCDATE() FOR YourColumn

When retrieving the values, the front end application/website should transform this value from UTC time to the locale/culture of the user requesting it.

Python: BeautifulSoup - get an attribute value based on the name attribute

One can also try this solution :

To find the value, which is written in span of table

htmlContent


<table>
    <tr>
        <th>
            ID
        </th>
        <th>
            Name
        </th>
    </tr>


    <tr>
        <td>
            <span name="spanId" class="spanclass">ID123</span>
        </td>

        <td>
            <span>Bonny</span>
        </td>
    </tr>
</table>

Python code


soup = BeautifulSoup(htmlContent, "lxml")
soup.prettify()

tables = soup.find_all("table")

for table in tables:
   storeValueRows = table.find_all("tr")
   thValue = storeValueRows[0].find_all("th")[0].string

   if (thValue == "ID"): # with this condition I am verifying that this html is correct, that I wanted.
      value = storeValueRows[1].find_all("span")[0].string
      value = value.strip()

      # storeValueRows[1] will represent <tr> tag of table located at first index and find_all("span")[0] will give me <span> tag and '.string' will give me value

      # value.strip() - will remove space from start and end of the string.

     # find using attribute :

     value = storeValueRows[1].find("span", {"name":"spanId"})['class']
     print value
     # this will print spanclass

How to measure elapsed time

Even better!

long tStart = System.nanoTime();
long tEnd = System.nanoTime();
long tRes = tEnd - tStart; // time in nanoseconds

Read the documentation about nanoTime()!

Cannot find mysql.sock

(Q1) How can I find the socket file?

The default location for the socket file is /tmp/mysql.sock, to find the socket file for your system use this.

mysqladmin variables | grep socket

If you have just installed MySql the mysql.sock file will not be created until the server is started. Use this command to start it.

sudo launchctl load -F /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist

If prompted for a password you can pass the username root or other username like this. Terminal will prompt you for the password.

mysqladmin --user root --password variables | grep socket

(Q2) How can I refresh locate index

Refresh the locate db with this command.

sudo /usr/libexec/locate.updatedb

How do I access previous promise results in a .then() chain?

Mutable contextual state

The trivial (but inelegant and rather errorprone) solution is to just use higher-scope variables (to which all callbacks in the chain have access) and write result values to them when you get them:

function getExample() {
    var resultA;
    return promiseA(…).then(function(_resultA) {
        resultA = _resultA;
        // some processing
        return promiseB(…);
    }).then(function(resultB) {
        // more processing
        return // something using both resultA and resultB
    });
}

Instead of many variables one might also use an (initially empty) object, on which the results are stored as dynamically created properties.

This solution has several drawbacks:

  • Mutable state is ugly, and global variables are evil.
  • This pattern doesn't work across function boundaries, modularising the functions is harder as their declarations must not leave the shared scope
  • The scope of the variables does not prevent to access them before they are initialized. This is especially likely for complex promise constructions (loops, branching, excptions) where race conditions might happen. Passing state explicitly, a declarative design that promises encourage, forces a cleaner coding style which can prevent this.
  • One must choose the scope for those shared variables correctly. It needs to be local to the executed function to prevent race conditions between multiple parallel invocations, as would be the case if, for example, state was stored on an instance.

The Bluebird library encourages the use of an object that is passed along, using their bind() method to assign a context object to a promise chain. It will be accessible from each callback function via the otherwise unusable this keyword. While object properties are more prone to undetected typos than variables, the pattern is quite clever:

function getExample() {
    return promiseA(…)
    .bind({}) // Bluebird only!
    .then(function(resultA) {
        this.resultA = resultA;
        // some processing
        return promiseB(…);
    }).then(function(resultB) {
        // more processing
        return // something using both this.resultA and resultB
    }).bind(); // don't forget to unbind the object if you don't want the
               // caller to access it
}

This approach can be easily simulated in promise libraries that do not support .bind (although in a somewhat more verbose way and cannot be used in an expression):

function getExample() {
    var ctx = {};
    return promiseA(…)
    .then(function(resultA) {
        this.resultA = resultA;
        // some processing
        return promiseB(…);
    }.bind(ctx)).then(function(resultB) {
        // more processing
        return // something using both this.resultA and resultB
    }.bind(ctx));
}

How do I set the selenium webdriver get timeout?

The timeouts() methods are not implemented in some drivers and are very unreliable in general.
I use a separate thread for the timeouts (passing the url to access as the thread name):

Thread t = new Thread(new Runnable() {
    public void run() {
        driver.get(Thread.currentThread().getName());
    }
}, url);
t.start();
try {
    t.join(YOUR_TIMEOUT_HERE_IN_MS);
} catch (InterruptedException e) { // ignore
}
if (t.isAlive()) { // Thread still alive, we need to abort
    logger.warning("Timeout on loading page " + url);
    t.interrupt();
}

This seems to work most of the time, however it might happen that the driver is really stuck and any subsequent call to driver will be blocked (I experience that with Chrome driver on Windows). Even something as innocuous as a driver.findElements() call could end up being blocked. Unfortunately I have no solutions for blocked drivers.

SQL Server query to find all current database names

This forum suggests also:

SELECT CATALOG_NAME AS DataBaseName
FROM INFORMATION_SCHEMA.SCHEMATA

How to put a List<class> into a JSONObject and then read that object?

Let us assume that the class is Data with two objects name and dob which are both strings.

Initially, check if the list is empty. Then, add the objects from the list to a JSONArray

JSONArray allDataArray = new JSONArray();
List<Data> sList = new ArrayList<String>();

    //if List not empty
    if (!(sList.size() ==0)) {

        //Loop index size()
        for(int index = 0; index < sList.size(); index++) {
            JSONObject eachData = new JSONObject();
            try {
                eachData.put("name", sList.get(index).getName());
                eachData.put("dob", sList.get(index).getDob());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            allDataArray.put(eachData);
        }
    } else {
        //Do something when sList is empty
    }

Finally, add the JSONArray to a JSONObject.

JSONObject root = new JSONObject();
    try {
        root.put("data", allDataArray);
    } catch (JSONException e) {
        e.printStackTrace();
    }

You can further get this data as a String too.

String jsonString = root.toString();

Unsupported operand type(s) for +: 'int' and 'str'

try,

str_list = " ".join([str(ele) for ele in numlist])

this statement will give you each element of your list in string format

print("The list now looks like [{0}]".format(str_list))

and,

change print(numlist.pop(2)+" has been removed") to

print("{0} has been removed".format(numlist.pop(2)))

as well.

SQL Sum Multiple rows into one

You're grouping with BillDate, but the bill dates are different for each account so your rows are not being grouped. If you think about it, that doesn't even make sense - they are different bills, and have different dates. The same goes for the Bill - you're attempting to sum bills for an account, why would you group by that?

If you leave BillDate and Bill off of the select and group by clauses you'll get the correct results.

SELECT AccountNumber, SUM(Bill)
FROM Table1
GROUP BY AccountNumber

Margin while printing html page

I'd personally suggest using a different unit of measurement than px. I don't think that pixels have much relevance in terms of print; ideally you'd use:

  • point (pt)
  • centimetre (cm)

I'm sure there are others, and one excellent article about print-css can be found here: Going to Print, by Eric Meyer.

Subtract one day from datetime

This should work.

select DATEADD(day, -1, convert(date, GETDATE()))

What does FETCH_HEAD in Git mean?

As mentioned in Jonathan's answer, FETCH_HEAD corresponds to the file .git/FETCH_HEAD. Typically, the file will look like this:

71f026561ddb57063681109aadd0de5bac26ada9                        branch 'some-branch' of <remote URL>
669980e32769626587c5f3c45334fb81e5f44c34        not-for-merge   branch 'some-other-branch' of <remote URL>
b858c89278ab1469c71340eef8cf38cc4ef03fed        not-for-merge   branch 'yet-some-other-branch' of <remote URL>

Note how all branches but one are marked not-for-merge. The odd one out is the branch that was checked out before the fetch. In summary: FETCH_HEAD essentially corresponds to the remote version of the branch that's currently checked out.

Android LinearLayout Gradient Background

It is also possible to have the third color (center). And different kinds of shapes.

For example in drawable/gradient.xml:

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#000000"
        android:centerColor="#5b5b5b"
        android:endColor="#000000"
        android:angle="0" />
</shape>

This gives you black - gray - black (left to right) which is my favorite dark background atm.

Remember to add gradient.xml as background in your layout xml:

android:background="@drawable/gradient"

It is also possible to rotate, with:

angle="0"

gives you a vertical line

and with

angle="90"

gives you a horizontal line

Possible angles are:

0, 90, 180, 270.

Also there are few different kind of shapes:

android:shape="rectangle"

Rounded shape:

android:shape="oval"

and problably a few more.

Hope it helps, cheers!

Label word wrapping

Refer to Automatically Wrap Text in Label. It describes how to create your own growing label.

Here is the full source taken from the above reference:

using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

public class GrowLabel : Label {
  private bool mGrowing;
  public GrowLabel() {
    this.AutoSize = false;
  }
  private void resizeLabel() {
    if (mGrowing) return;
    try {
      mGrowing = true;
      Size sz = new Size(this.Width, Int32.MaxValue);
      sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
      this.Height = sz.Height;
    }
    finally {
      mGrowing = false;
    }
  }
  protected override void OnTextChanged(EventArgs e) {
    base.OnTextChanged(e);
    resizeLabel();
  }
  protected override void OnFontChanged(EventArgs e) {
    base.OnFontChanged(e);
    resizeLabel();
  }
  protected override void OnSizeChanged(EventArgs e) {
    base.OnSizeChanged(e);
    resizeLabel();
  }
}

Basic Python client socket example

It looks like your client is trying to connect to a non-existent server. In a shell window, run:

$ nc -l 5000

before running your Python code. It will act as a server listening on port 5000 for you to connect to. Then you can play with typing into your Python window and seeing it appear in the other terminal and vice versa.

The application was unable to start correctly (0xc000007b)

Actually this error indicates to an invalid image format. However, why this is happening and what the error code usually means? Actually this could be appear when you are trying to run a program that is made for or intended to work with a 64 bit Windows operating system, but your computer is running on 32 bit Operating system.

Possible Reasons:

  • Microsoft Visual C++
  • Need to restart
  • DirectX
  • .NET Framework
  • Need to Re-Install
  • Need to Run the application as an administrator

Source: http://www.solveinweb.com/solved-the-application-was-unable-to-start-correctly-0xc000007b-click-ok-to-close-the-application/

How do you add CSS with Javascript?

Another option is to use JQuery to store the element's in-line style property, append to it, and to then update the element's style property with the new values. As follows:

function appendCSSToElement(element, CssProperties)
        {
            var existingCSS = $(element).attr("style");

             if(existingCSS == undefined) existingCSS = "";

            $.each(CssProperties, function(key,value)
            {
                existingCSS += " " + key + ": " + value + ";";
            });

            $(element).attr("style", existingCSS);

            return $(element);
        }

And then execute it with the new CSS attributes as an object.

appendCSSToElement("#ElementID", { "color": "white", "background-color": "green", "font-weight": "bold" });

This may not necessarily be the most efficient method (I'm open to suggestions on how to improve this. :) ), but it definitely works.

Calling Javascript from a html form

Remove javascript: from onclick=".., onsubmit=".. declarations

javascript: prefix is used only in href="" or similar attributes (not events related)

Java: get greatest common divisor

/*
import scanner and instantiate scanner class;
declare your method with two parameters
declare a third variable;
set condition;
swap the parameter values if condition is met;
set second conditon based on result of first condition;
divide and assign remainder to the third variable;
swap the result;
in the main method, allow for user input;
Call the method;

*/
public class gcf {
    public static void main (String[]args){//start of main method
        Scanner input = new Scanner (System.in);//allow for user input
        System.out.println("Please enter the first integer: ");//prompt
        int a = input.nextInt();//initial user input
        System.out.println("Please enter a second interger: ");//prompt
        int b = input.nextInt();//second user input


       Divide(a,b);//call method
    }
   public static void Divide(int a, int b) {//start of your method

    int temp;
    // making a greater than b
    if (b > a) {
         temp = a;
         a = b;
         b = temp;
    }

    while (b !=0) {
        // gcd of b and a%b
        temp = a%b;
        // always make a greater than b
        a =b;
        b =temp;

    }
    System.out.println(a);//print to console
  }
}

How do I call a JavaScript function on page load?

function yourfunction() { /* do stuff on page load */ }

window.onload = yourfunction;

Or with jQuery if you want:

$(function(){
   yourfunction();
});

If you want to call more than one function on page load, take a look at this article for more information:

How do I set up CLion to compile and run?

You can also use Microsoft Visual Studio compiler instead of Cygwin or MinGW in Windows environment as the compiler for CLion.

Just go to find Actions in Help and type "Registry" without " and enable CLion.enable.msvc Now configure toolchain with Microsoft Visual Studio Compiler. (You need to download it if not already downloaded)

follow this link for more details: https://www.jetbrains.com/help/clion/quick-tutorial-on-configuring-clion-on-windows.html

inline if statement java, why is not working

Your cases does not have a return value.

getButtons().get(i).setText("§");

In-line-if is Ternary operation all ternary operations must have return value. That variable is likely void and does not return anything and it is not returning to a variable. Example:

int i = 40;
String value = (i < 20) ? "it is too low" : "that is larger than 20";

for your case you just need an if statement.

if (compareChar(curChar, toChar("0"))) { getButtons().get(i).setText("§"); }

Also side note you should use curly braces it makes the code more readable and declares scope.

Insert multiple values using INSERT INTO (SQL Server 2005)

The syntax you are using is new to SQL Server 2008:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1000,N'test'),(1001,N'test2')

For SQL Server 2005, you will have to use multiple INSERT statements:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1000,N'test')

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1001,N'test2')

One other option is to use UNION ALL:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
SELECT 1000, N'test' UNION ALL
SELECT 1001, N'test2'

Could not find default endpoint element

I had the same Issue
I was using desktop app and using Global Weather Web service

I deleted the service reference and added the web reference and problem solved Thanks

javascript regex : only english letters allowed

The answer that accepts empty string:

/^[a-zA-Z]*$/.test('something')

the * means 0 or more occurrences of the preceding item.

How do I resolve a TesseractNotFoundError?

This occurs under windows (at least in tesseract version 3.05) when the current directory is on a different drive from where tesseract is installed.

Something in tesseract is expecting data files to be in \Program Files... (rather than C:\Program Files, say). So if you're not on the same drive letter as tesseract, it will fail. It would be great if we could work around it by temporarily changing drives (under windows only) to the tesseract installation drive before executing tesseract, and changing back after. Example in your case: You can copy yourmodule_python.py to "C/Program Files (x86)/Tesseract-OCR/" and RUN!

How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

In such a case I would recommand using the ternary operator:

child: condition ? Container() : Center()

and try to avoid code of the form:

if (condition) return A else return B

which is needlessly more verbose than the ternary operator.

But if more logic is needed you may also:

Use the Builder widget

The Builder widget is meant for allowing the use of a closure when a child widget is required:

A platonic widget that calls a closure to obtain its child widget.

It is convenient anytime you need logic to build a widget, it avoids the need to create a dedicated function.

You use the Builder widget as the child, you provide your logic in its builder method:

Center(
  child: Builder(
    builder: (context) {
      // any logic needed...
      final condition = _whateverLogicNeeded();
      
      return condition
          ? Container();
          : Center();
    }
  )
)

The Builder provides a convenient place to hold the creational logic. It is more straightforward than the immediate anonymous function proposed by atreeon.

Also I agree that the logic should be extracted from the UI code, but when it's really UI logic it is sometimes more legible to keep it there.

Core dump file analysis

You just need a binary (with debugging symbols included) that is identical to the one that generated the core dump file. Then you can run gdb path/to/the/binary path/to/the/core/dump/file to debug it.

When it starts up, you can use bt (for backtrace) to get a stack trace from the time of the crash. In the backtrace, each function invocation is given a number. You can use frame number (replacing number with the corresponding number in the stack trace) to select a particular stack frame.

You can then use list to see code around that function, and info locals to see the local variables. You can also use print name_of_variable (replacing "name_of_variable" with a variable name) to see its value.

Typing help within GDB will give you a prompt that will let you see additional commands.

PHP string concatenation

$personCount=1;
while ($personCount < 10) {
    $result=0;
    $result.= $personCount . "person ";
    $personCount++;
    echo $result;
}

How to display a gif fullscreen for a webpage background?

if it's background, use background-size: cover;

_x000D_
_x000D_
body{_x000D_
    background-image: url('http://i.stack.imgur.com/kx8MT.gif');_x000D_
    background-size: cover;_x000D_
    _x000D_
    _x000D_
    _x000D_
    height: 100vh;_x000D_
    padding:0;_x000D_
    margin:0;_x000D_
}
_x000D_
_x000D_
_x000D_

Why do Sublime Text 3 Themes not affect the sidebar?

setting color_scheme only sets the code pallet, setting theme sets the whole ST3 theme to the one you specify:

{
    "theme": "Nil.sublime-theme",
    "color_scheme": "Packages/Theme - Nil/Big Duo.tmTheme"
    ...
}

accessing a variable from another class

I had the same problem. In order to modify variables from different classes, I made them extend the class they were to modify. I also made the super class's variables static so they can be changed by anything that inherits them. I also made them protected for more flexibility.

Source: Bad experiences. Good lessons.

Remove Backslashes from Json Data in JavaScript

try this

var finalData = str.replace(/\\/g, '');

Convert string to title case with JavaScript

Here is my function that is taking care of accented characters (important for french !) and that can switch on/off the handling of lowers exceptions. Hope that helps.

String.prototype.titlecase = function(lang, withLowers = false) {
    var i, string, lowers, uppers;

    string = this.replace(/([^\s:\-'])([^\s:\-']*)/g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    }).replace(/Mc(.)/g, function(match, next) {
        return 'Mc' + next.toUpperCase();
    });

    if (withLowers) {
        if (lang == 'EN') {
            lowers = ['A', 'An', 'The', 'At', 'By', 'For', 'In', 'Of', 'On', 'To', 'Up', 'And', 'As', 'But', 'Or', 'Nor', 'Not'];
        }
        else {
            lowers = ['Un', 'Une', 'Le', 'La', 'Les', 'Du', 'De', 'Des', 'À', 'Au', 'Aux', 'Par', 'Pour', 'Dans', 'Sur', 'Et', 'Comme', 'Mais', 'Ou', 'Où', 'Ne', 'Ni', 'Pas'];
        }
        for (i = 0; i < lowers.length; i++) {
            string = string.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'), function(txt) {
                return txt.toLowerCase();
            });
        }
    }

    uppers = ['Id', 'R&d'];
    for (i = 0; i < uppers.length; i++) {
        string = string.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'), uppers[i].toUpperCase());
    }

    return string;
}

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

You can use reportValidity, however it has poor browser support yet. It works on Chrome, Opera and Firefox but not on IE nor Edge or Safari:

var myform = $("#my-form")[0];
if (!myform.checkValidity()) {
    if (myform.reportValidity) {
        myform.reportValidity();
    } else {
        //warn IE users somehow
    }
}

(checkValidity has better support, but does not work on IE<10 neither.)

How to redirect DNS to different ports

You can use SRV records:

_service._proto.name. TTL class SRV priority weight port target.

Service: the symbolic name of the desired service.

Proto: the transport protocol of the desired service; this is usually either TCP or UDP.

Name: the domain name for which this record is valid, ending in a dot.

TTL: standard DNS time to live field.

Class: standard DNS class field (this is always IN).

Priority: the priority of the target host, lower value means more preferred.

Weight: A relative weight for records with the same priority.

Port: the TCP or UDP port on which the service is to be found.

Target: the canonical hostname of the machine providing the service, ending in a dot.

Example:

_sip._tcp.example.com. 86400 IN SRV 0 5 5060 sipserver.example.com.

So what I think you're looking for is to add something like this to your DNS hosts file:

_sip._tcp.arboristal.com. 86400 IN SRV 10 40 25565 mc.arboristal.com.
_sip._tcp.arboristal.com. 86400 IN SRV 10 30 25566 tekkit.arboristal.com.
_sip._tcp.arboristal.com. 86400 IN SRV 10 30 25567 pvp.arboristal.com.

On a side note, I highly recommend you go with a hosting company rather than hosting the servers yourself. It's just asking for trouble with your home connection (DDoS and Bandwidth/Connection Speed), but it's up to you.

Inline for loop

your list comphresnion will, work but will return list of None because append return None:

demo:

>>> a=[]
>>> [ a.append(x) for x in range(10) ]
[None, None, None, None, None, None, None, None, None, None]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

better way to use it like this:

>>> a= [ x for x in range(10) ]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

How do I get a human-readable file size in bytes abbreviation using .NET?

int size = new FileInfo( filePath ).Length / 1024;
string humanKBSize = string.Format( "{0} KB", size );
string humanMBSize = string.Format( "{0} MB", size / 1024 );
string humanGBSize = string.Format( "{0} GB", size / 1024 / 1024 );

JPA: How to get entity based on field value other than ID?

It is not a "problem" as you stated it.

Hibernate has the built-in find(), but you have to build your own query in order to get a particular object. I recommend using Hibernate's Criteria :

Criteria criteria = session.createCriteria(YourClass.class);
YourObject yourObject = criteria.add(Restrictions.eq("yourField", yourFieldValue))
                             .uniqueResult();

This will create a criteria on your current class, adding the restriction that the column "yourField" is equal to the value yourFieldValue. uniqueResult() tells it to bring a unique result. If more objects match, you should retrive a list.

List<YourObject> list = criteria.add(Restrictions.eq("yourField", yourFieldValue)).list();

If you have any further questions, please feel free to ask. Hope this helps.

Oracle Partition - Error ORA14400 - inserted partition key does not map to any partition

For this issue need to add the partition for date column values, If last partition 20201231245959, then inserting the 20210110245959 values, this issue will occurs.

For that need to add the 2021 partition into that table

ALTER TABLE TABLE_NAME ADD PARTITION PARTITION_NAME VALUES LESS THAN (TO_DATE('2021-12-31 24:59:59', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')) NOCOMPRESS

Relative frequencies / proportions with dplyr

For the sake of completeness of this popular question, since version 1.0.0 of dplyr, parameter .groups controls the grouping structure of the summarise function after group_by summarise help.

With .groups = "drop_last", summarise drops the last level of grouping. This was the only result obtained before version 1.0.0.

library(dplyr)
library(scales)

original <- mtcars %>%
  group_by (am, gear) %>%
  summarise (n=n()) %>%
  mutate(rel.freq =  scales::percent(n/sum(n), accuracy = 0.1))
#> `summarise()` regrouping output by 'am' (override with `.groups` argument)

original
#> # A tibble: 4 x 4
#> # Groups:   am [2]
#>      am  gear     n rel.freq
#>   <dbl> <dbl> <int> <chr>   
#> 1     0     3    15 78.9%   
#> 2     0     4     4 21.1%   
#> 3     1     4     8 61.5%   
#> 4     1     5     5 38.5%

new_drop_last <- mtcars %>%
  group_by (am, gear) %>%
  summarise (n=n(), .groups = "drop_last") %>%
  mutate(rel.freq =  scales::percent(n/sum(n), accuracy = 0.1))

dplyr::all_equal(original, new_drop_last)
#> [1] TRUE

With .groups = "drop", all levels of grouping are dropped. The result is turned into an independent tibble with no trace of the previous group_by

# .groups = "drop"
new_drop <- mtcars %>%
  group_by (am, gear) %>%
  summarise (n=n(), .groups = "drop") %>%
  mutate(rel.freq =  scales::percent(n/sum(n), accuracy = 0.1))

new_drop
#> # A tibble: 4 x 4
#>      am  gear     n rel.freq
#>   <dbl> <dbl> <int> <chr>   
#> 1     0     3    15 46.9%   
#> 2     0     4     4 12.5%   
#> 3     1     4     8 25.0%   
#> 4     1     5     5 15.6%

If .groups = "keep", same grouping structure as .data (mtcars, in this case). summarise does not peel off any variable used in the group_by.

Finally, with .groups = "rowwise", each row is it's own group. It is equivalent to "keep" in this situation

# .groups = "keep"
new_keep <- mtcars %>%
  group_by (am, gear) %>%
  summarise (n=n(), .groups = "keep") %>%
  mutate(rel.freq =  scales::percent(n/sum(n), accuracy = 0.1))

new_keep
#> # A tibble: 4 x 4
#> # Groups:   am, gear [4]
#>      am  gear     n rel.freq
#>   <dbl> <dbl> <int> <chr>   
#> 1     0     3    15 100.0%  
#> 2     0     4     4 100.0%  
#> 3     1     4     8 100.0%  
#> 4     1     5     5 100.0%

# .groups = "rowwise"
new_rowwise <- mtcars %>%
  group_by (am, gear) %>%
  summarise (n=n(), .groups = "rowwise") %>%
  mutate(rel.freq =  scales::percent(n/sum(n), accuracy = 0.1))

dplyr::all_equal(new_keep, new_rowwise)
#> [1] TRUE

Another point that can be of interest is that sometimes, after applying group_by and summarise, a summary line can help.

# create a subtotal line to help readability
subtotal_am <- mtcars %>%
  group_by (am) %>% 
  summarise (n=n()) %>%
  mutate(gear = NA, rel.freq = 1)
#> `summarise()` ungrouping output (override with `.groups` argument)

mtcars %>% group_by (am, gear) %>%
  summarise (n=n()) %>% 
  mutate(rel.freq = n/sum(n)) %>%
  bind_rows(subtotal_am) %>%
  arrange(am, gear) %>%
  mutate(rel.freq =  scales::percent(rel.freq, accuracy = 0.1))
#> `summarise()` regrouping output by 'am' (override with `.groups` argument)
#> # A tibble: 6 x 4
#> # Groups:   am [2]
#>      am  gear     n rel.freq
#>   <dbl> <dbl> <int> <chr>   
#> 1     0     3    15 78.9%   
#> 2     0     4     4 21.1%   
#> 3     0    NA    19 100.0%  
#> 4     1     4     8 61.5%   
#> 5     1     5     5 38.5%   
#> 6     1    NA    13 100.0%

Created on 2020-11-09 by the reprex package (v0.3.0)

Hope you find this answer useful.

How to create our own Listener interface in android?

Create a new file:

MyListener.java:

public interface MyListener {
    // you can define any parameter as per your requirement
    public void callback(View view, String result);
}

In your activity, implement the interface:

MyActivity.java:

public class MyActivity extends Activity implements MyListener {
   @override        
   public void onCreate(){
        MyButton m = new MyButton(this);
   }

    // method is invoked when MyButton is clicked
    @override
    public void callback(View view, String result) {   
        // do your stuff here
    }
}

In your custom class, invoke the interface when needed:

MyButton.java:

public class MyButton {
    MyListener ml;

    // constructor
    MyButton(MyListener ml) {
        //Setting the listener
        this.ml = ml;
    }

    public void MyLogicToIntimateOthers() {
        //Invoke the interface
        ml.callback(this, "success");
    }
}

Order data frame rows according to vector with specific order

Here's a similar system for the situation where you have a variable you want to sort by, initially, but then you want to sort by a secondary variable according to the order that this secondary variable first appears in the initial sort.

In the function below, the initial sort variable is called order_by and the secondary variable is called order_along - as in "order by this variable along its initial order".

library(dplyr, warn.conflicts = FALSE)
df <- structure(
  list(
    msoa11hclnm = c(
      "Bewbush", "Tilgate", "Felpham",
      "Selsey", "Brunswick", "Ratton", "Ore", "Polegate", "Mile Oak",
      "Upperton", "Arundel", "Kemptown"
    ),
    lad20nm = c(
      "Crawley", "Crawley",
      "Arun", "Chichester", "Brighton and Hove", "Eastbourne", "Hastings",
      "Wealden", "Brighton and Hove", "Eastbourne", "Arun", "Brighton and Hove"
    ),
    shape_area = c(
      1328821, 3089180, 3540014, 9738033, 448888, 10152663, 5517102,
      7036428, 5656430, 2653589, 72832514, 826151
    )
  ),
  row.names = c(NA, -12L), class = "data.frame"
)

this does not give me what I need:

df %>% 
  dplyr::arrange(shape_area, lad20nm)
#>    msoa11hclnm           lad20nm shape_area
#> 1    Brunswick Brighton and Hove     448888
#> 2     Kemptown Brighton and Hove     826151
#> 3      Bewbush           Crawley    1328821
#> 4     Upperton        Eastbourne    2653589
#> 5      Tilgate           Crawley    3089180
#> 6      Felpham              Arun    3540014
#> 7          Ore          Hastings    5517102
#> 8     Mile Oak Brighton and Hove    5656430
#> 9     Polegate           Wealden    7036428
#> 10      Selsey        Chichester    9738033
#> 11      Ratton        Eastbourne   10152663
#> 12     Arundel              Arun   72832514

Here’s a function:

order_along <- function(df, order_along, order_by) {
  cols <- colnames(df)
  
  df <- df %>%
    dplyr::arrange({{ order_by }})
  
  df %>% 
    dplyr::select({{ order_along }}) %>% 
    dplyr::distinct() %>% 
    dplyr::full_join(df) %>% 
    dplyr::select(dplyr::all_of(cols))
  
}

order_along(df, lad20nm, shape_area)
#> Joining, by = "lad20nm"
#>    msoa11hclnm           lad20nm shape_area
#> 1    Brunswick Brighton and Hove     448888
#> 2     Kemptown Brighton and Hove     826151
#> 3     Mile Oak Brighton and Hove    5656430
#> 4      Bewbush           Crawley    1328821
#> 5      Tilgate           Crawley    3089180
#> 6     Upperton        Eastbourne    2653589
#> 7       Ratton        Eastbourne   10152663
#> 8      Felpham              Arun    3540014
#> 9      Arundel              Arun   72832514
#> 10         Ore          Hastings    5517102
#> 11    Polegate           Wealden    7036428
#> 12      Selsey        Chichester    9738033

Created on 2021-01-12 by the reprex package (v0.3.0)

How to bundle an Angular app for production

Angular 2 with Webpack (without CLI setup)

1- The tutorial by the Angular2 team

The Angular2 team published a tutorial for using Webpack

I created and placed the files from the tutorial in a small GitHub seed project. So you can quickly try the workflow.

Instructions:

  • npm install

  • npm start. For development. This will create a virtual "dist" folder that will be livereloaded at your localhost address.

  • npm run build. For production. "This will create a physical "dist" folder version than can be sent to a webserver. The dist folder is 7.8MB but only 234KB is actually required to load the page in a web browser.

2 - A Webkit starter kit

This Webpack Starter Kit offers some more testing features than the above tutorial and seem quite popular.

Changing the text on a label

self.labelText = 'change the value'

The above sentence makes labelText change the value, but not change depositLabel's text.

To change depositLabel's text, use one of following setences:

self.depositLabel['text'] = 'change the value'

OR

self.depositLabel.config(text='change the value')

What is the difference between an annotated and unannotated tag?

Push annotated tags, keep lightweight local

man git-tag says:

Annotated tags are meant for release while lightweight tags are meant for private or temporary object labels.

And certain behaviors do differentiate between them in ways that this recommendation is useful e.g.:

  • annotated tags can contain a message, creator, and date different than the commit they point to. So you could use them to describe a release without making a release commit.

    Lightweight tags don't have that extra information, and don't need it, since you are only going to use it yourself to develop.

  • git push --follow-tags will only push annotated tags
  • git describe without command line options only sees annotated tags

Internals differences

  • both lightweight and annotated tags are a file under .git/refs/tags that contains a SHA-1

  • for lightweight tags, the SHA-1 points directly to a commit:

    git tag light
    cat .git/refs/tags/light
    

    prints the same as the HEAD's SHA-1.

    So no wonder they cannot contain any other metadata.

  • annotated tags point to a tag object in the object database.

    git tag -as -m msg annot
    cat .git/refs/tags/annot
    

    contains the SHA of the annotated tag object:

    c1d7720e99f9dd1d1c8aee625fd6ce09b3a81fef
    

    and then we can get its content with:

    git cat-file -p c1d7720e99f9dd1d1c8aee625fd6ce09b3a81fef
    

    sample output:

    object 4284c41353e51a07e4ed4192ad2e9eaada9c059f
    type commit
    tag annot
    tagger Ciro Santilli <[email protected]> 1411478848 +0200
    
    msg
    -----BEGIN PGP SIGNATURE-----
    Version: GnuPG v1.4.11 (GNU/Linux)
    
    <YOUR PGP SIGNATURE>
    -----END PGP SIGNAT
    

    And this is how it contains extra metadata. As we can see from the output, the metadata fields are:

    A more detailed analysis of the format is present at: What is the format of a git tag object and how to calculate its SHA?

Bonuses

  • Determine if a tag is annotated:

    git cat-file -t tag
    

    Outputs

    • commit for lightweight, since there is no tag object, it points directly to the commit
    • tag for annotated, since there is a tag object in that case
  • List only lightweight tags: How can I list all lightweight tags?

Refresh DataGridView when updating data source

Alexander Abakumov's answer is the correct one. It solved every binding issue I had updating the underlying data and having the grid update.

Its easy to implement and modify any existing source code you have.

grdDetails.DataSource = new System.Windows.Forms.BindingSource { DataSource = OrderDetails };

What is Vim recording and how can it be disabled?

You start recording by q<letter> and you can end it by typing q again.

Recording is a really useful feature of Vim.

It records everything you type. You can then replay it simply by typing @<letter>. Record search, movement, replacement...

One of the best feature of Vim IMHO.

Create new project on Android, Error: Studio Unknown host 'services.gradle.org'

I also faced it and encorrected it like below successfully.

File > Settings > Build, Execution, Deployment > Gradle > Use local gradle distribution

Set the home path as : C:/Program Files/Android/Android Studio/gradle/gradle-version

You may need to upgrade your gradle version.

How to dynamic new Anonymous Class?

Anonymous types are just regular types that are implicitly declared. They have little to do with dynamic.

Now, if you were to use an ExpandoObject and reference it through a dynamic variable, you could add or remove fields on the fly.

edit

Sure you can: just cast it to IDictionary<string, object>. Then you can use the indexer.

You use the same casting technique to iterate over the fields:

dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;

foreach (var property in (IDictionary<string, object>)employee)
{
    Console.WriteLine(property.Key + ": " + property.Value);
}
// This code example produces the following output:
// Name: John Smith
// Age: 33

The above code and more can be found by clicking on that link.

CMD command to check connected USB devices

you can download USBview and get all the information you need. Along with the list of devices it will also show you the configuration of each device.

Is it possible to use pip to install a package from a private GitHub repository?

If you don't want to use SSH, you could add the username and password in the HTTPS URL.

The code below assumes that you have a file called "pass" in the working directory that contains your password.

export PASS=$(cat pass)
pip install git+https://<username>:[email protected]/echweb/echweb-utils.git

SQLException: No suitable driver found for jdbc:derby://localhost:1527

if the database is created and you have started the connection to the, then al you need is to add the driver jar. from the project window, right click on the libraries folder, goto c:programsfiles\sun\javadb\lib\derbyclient.jar. load the file and you should be able to run.

all the best

Docker container will automatically stop after "docker run -d"

Background

A Docker container runs a process (the "command" or "entrypoint") that keeps it alive. The container will continue to run as long as the command continues to run.

In your case, the command (/bin/bash, by default, on centos:latest) is exiting immediately (as bash does when it's not connected to a terminal and has nothing to run).

Normally, when you run a container in daemon mode (with -d), the container is running some sort of daemon process (like httpd). In this case, as long as the httpd daemon is running, the container will remain alive.

What you appear to be trying to do is to keep the container alive without a daemon process running inside the container. This is somewhat strange (because the container isn't doing anything useful until you interact with it, perhaps with docker exec), but there are certain cases where it might make sense to do something like this.

(Did you mean to get to a bash prompt inside the container? That's easy! docker run -it centos:latest)

Solution

A simple way to keep a container alive in daemon mode indefinitely is to run sleep infinity as the container's command. This does not rely doing strange things like allocating a TTY in daemon mode. Although it does rely on doing strange things like using sleep as your primary command.

$ docker run -d centos:latest sleep infinity
$ docker ps
CONTAINER ID  IMAGE         COMMAND          CREATED       STATUS       PORTS NAMES
d651c7a9e0ad  centos:latest "sleep infinity" 2 seconds ago Up 2 seconds       nervous_visvesvaraya

Alternative Solution

As indicated by cjsimon, the -t option allocates a "pseudo-tty". This tricks bash into continuing to run indefinitely because it thinks it is connected to an interactive TTY (even though you have no way to interact with that particular TTY if you don't pass -i). Anyway, this should do the trick too:

$ docker run -t -d centos:latest

Not 100% sure whether -t will produce other weird interactions; maybe leave a comment below if it does.

Java JSON serialization - best practice

Are you tied to this library? Google Gson is very popular. I have myself not used it with Generics but their front page says Gson considers support for Generics very important.

Change language of Visual Studio 2017 RC

You can CHANGE user interface LANGUAGE like this:

Open VS > VS Community > Preferences > Environment > Visual Style > User Interface language

Woala!!!

CSS: Center block, but align contents to the left

Reposting the working answer from the other question: How to horizontally center a floating element of a variable width?

Assuming the element which is floated and will be centered is a div with an id="content" ...

<body>
<div id="wrap">
   <div id="content">
   This will be centered
   </div>
</div>
</body>

And apply the following CSS

#wrap {
    float: left;
    position: relative;
    left: 50%;
}

#content {
    float: left;
    position: relative;
    left: -50%;
}

Here is a good reference regarding that http://dev.opera.com/articles/view/35-floats-and-clearing/#centeringfloats

If file exists then delete the file

fileExists() is a method of FileSystemObject, not a global scope function.

You also have an issue with the delete, DeleteFile() is also a method of FileSystemObject.

Furthermore, it seems you are moving the file and then attempting to deal with the overwrite issue, which is out of order. First you must detect the name collision, so you can choose the rename the file or delete the collision first. I am assuming for some reason you want to keep deleting the new files until you get to the last one, which seemed implied in your question.

So you could use the block:

if NOT fso.FileExists(newname) Then  

    file.move fso.buildpath(OUT_PATH, newname)           

else

    fso.DeleteFile newname
    file.move fso.buildpath(OUT_PATH, newname)  

end if 

Also be careful that your string comparison with the = sign is case sensitive. Use strCmp with vbText compare option for case insensitive string comparison.

Python: pandas merge multiple dataframes

Look at this pandas three-way joining multiple dataframes on columns

filenames = ['fn1', 'fn2', 'fn3', 'fn4',....]
dfs = [pd.read_csv(filename, index_col=index_col) for filename in filenames)]
dfs[0].join(dfs[1:])

Send Outlook Email Via Python?

This was one I tried using Win32:

import win32com.client as win32
import psutil
import os
import subprocess
import sys

# Drafting and sending email notification to senders. You can add other senders' email in the list
def send_notification():


    outlook = win32.Dispatch('outlook.application')
    olFormatHTML = 2
    olFormatPlain = 1
    olFormatRichText = 3
    olFormatUnspecified = 0
    olMailItem = 0x0

    newMail = outlook.CreateItem(olMailItem)
    newMail.Subject = sys.argv[1]
    #newMail.Subject = "check"
    newMail.BodyFormat = olFormatHTML    #or olFormatRichText or olFormatPlain
    #newMail.HTMLBody = "test"
    newMail.HTMLBody = sys.argv[2]
    newMail.To = "[email protected]"
    attachment1 = sys.argv[3]
    attachment2 = sys.argv[4]
    newMail.Attachments.Add(attachment1)
    newMail.Attachments.Add(attachment2)

    newMail.display()
    # or just use this instead of .display() if you want to send immediately
    newMail.Send()





# Open Outlook.exe. Path may vary according to system config
# Please check the path to .exe file and update below
def open_outlook():
    try:
        subprocess.call(['C:\Program Files\Microsoft Office\Office15\Outlook.exe'])
        os.system("C:\Program Files\Microsoft Office\Office15\Outlook.exe");
    except:
        print("Outlook didn't open successfully")     
#

# Checking if outlook is already opened. If not, open Outlook.exe and send email
for item in psutil.pids():
    p = psutil.Process(item)
    if p.name() == "OUTLOOK.EXE":
        flag = 1
        break
    else:
        flag = 0

if (flag == 1):
    send_notification()
else:
    open_outlook()
    send_notification()

View HTTP headers in Google Chrome?

You can find the headers option in the Network tab in Developer's console in Chrome:

  1. In Chrome press F12 to open Developer's console.
  2. Select the Network tab. This tab gives you the information about the requests fired from the browser.
  3. Select a request by clicking on the request name. There you can find the Header information for that request along with some other information like Preview, Response and Timing.

Also, in my version of Chrome (50.0.2661.102), it gives an extension named LIVE HTTP Headers which gives information about the request headers for all the HTTP requests.

update: added image

enter image description here

JBoss AS 7: How to clean up tmp?

As you know JBoss is a purely filesystem based installation. To install you simply unzip a file and thats it. Once you install a certain folder structure is created by default and as you run the JBoss instance for the first time, it creates additional folders for runtime operation. For comparison here is the structure of JBoss AS 7 before and after you start for the first time

Before

jboss-as-7
 |
 |---> standalone
 |      |----> lib
 |      |----> configuration
 |      |----> deployments
 |      
 |---> domain
 |....

After

jboss-as-7
     |
     |---> standalone
     |      |----> lib
     |      |----> configuration
     |      |----> deployments
     |      |----> tmp
     |      |----> data
     |      |----> log
     |      
     |---> domain
     |....

As you can see 3 new folders are created (log, data & tmp). These folders can all be deleted without effecting the application deployed in deployments folder unless your application generated Data that's stored in those folders. In development, its ok to delete all these 3 new folders assuming you don't have any need for the logs and data stored in "data" directory.

For production, ITS NOT RECOMMENDED to delete these folders as there maybe application generated data that stores certain state of the application. For ex, in the data folder, the appserver can save critical Tx rollback logs. So contact your JBoss Administrator if you need to delete those folders for any reason in production.

Good luck!

yum error "Cannot retrieve metalink for repository: epel. Please verify its path and try again" updating ContextBroker

I solved this issue editing both /etc/yum.repos.d/epel.repo and /etc/yum.repos.d/epel-testing.repo files, commenting all entries starting with mirrorlist=... and uncommenting all the entries starting with baseurl=....

How to scanf only integer?

  1. You take scanf().
  2. You throw it in the bin.
  3. You use fgets() to get an entire line.
  4. You use strtol() to parse the line as an integer, checking if it consumed the entire line.
char *end;
char buf[LINE_MAX];

do {
     if (!fgets(buf, sizeof buf, stdin))
        break;

     // remove \n
     buf[strlen(buf) - 1] = 0;

     int n = strtol(buf, &end, 10);
} while (end != buf + strlen(buf));

C++ float array initialization

No, it sets all members/elements that haven't been explicitly set to their default-initialisation value, which is zero for numeric types.

Send values from one form to another form

There are several solutions to this but this is the pattern I tend to use.

// Form 1
// inside the button click event
using(Form2 form2 = new Form2()) 
{
    if(form2.ShowDialog() == DialogResult.OK) 
    {
        someControlOnForm1.Text = form2.TheValue;
    }
}

And...

// Inside Form2
// Create a public property to serve the value
public string TheValue 
{
    get { return someTextBoxOnForm2.Text; }
}

When to use IMG vs. CSS background-image?

You can use IMG tags if you want the images to be fluid and scale to different screen sizes. For me these images are mostly part of the content. For most elements that are not part of the content, I use CSS sprites to keep the download size minimal unless I really want to animate icons etc.

Slide a layout up from bottom of screen

Try this below code, Its very short and simple.

transalate_anim.xml

<?xml version="1.0" encoding="utf-8"?><!-- Copyright (C) 2013 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="4000"
        android:fromXDelta="0"
        android:fromYDelta="0"
        android:repeatCount="infinite"
        android:toXDelta="0"
        android:toYDelta="-90%p" />

    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="4000"
        android:fromAlpha="0.0"
        android:repeatCount="infinite"
        android:toAlpha="1.0" />
</set>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.naveen.congratulations.MainActivity">


    <ImageView
        android:id="@+id/image_1"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginStart="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:srcCompat="@drawable/balloons" />
</android.support.constraint.ConstraintLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ImageView imageView1 = (ImageView) findViewById(R.id.image_1);
        imageView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startBottomToTopAnimation(imageView1);
            }
        });

    }

    private void startBottomToTopAnimation(View view) {
        view.startAnimation(AnimationUtils.loadAnimation(this, R.anim.translate_anim));
    }
}

bottom_up_navigation of image

About "*.d.ts" in TypeScript

Worked example for a specific case:

Let's say you have my-module that you're sharing via npm.

You install it with npm install my-module

You use it thus:

import * as lol from 'my-module';

const a = lol('abc', 'def');

The module's logic is all in index.js:

module.exports = function(firstString, secondString) {

  // your code

  return result
}

To add typings, create a file index.d.ts:

declare module 'my-module' {
  export default function anyName(arg1: string, arg2: string): MyResponse;
}

interface MyResponse {
  something: number;
  anything: number;
}

Adding a newline character within a cell (CSV)

I was concatenating the variable and adding multiple items in same row. so below code work for me. "\n" new line code is mandatory to add first and last of each line if you will add it on last only it will append last 1-2 character to new lines.

  $itemCode =  '';
foreach($returnData['repairdetail'] as $checkkey=>$repairDetailData){

    if($checkkey >0){
        $itemCode   .= "\n".trim(@$repairDetailData['ItemMaster']->Item_Code)."\n";
    }else{
        $itemCode   .= "\n".trim(@$repairDetailData['ItemMaster']->Item_Code)."\n";             
    }
    $repairDetaile[]= array(
        $itemCode,
    )
}
// pass all array to here 
foreach ($repairDetaile as $csvData) { 
    fputcsv($csv_file,$csvData,',','"');
}
fclose($csv_file);  

How to add \newpage in Rmarkdown in a smart way?

Simply \newpage or \pagebreak will work, e.g.

hello world
\newpage
```{r, echo=FALSE}
1+1
```
\pagebreak
```{r, echo=FALSE}
plot(1:10)
```

This solution assumes you are knitting PDF. For HTML, you can achieve a similar effect by adding a tag <P style="page-break-before: always">. Note that you likely won't see a page break in your browser (HTMLs don't have pages per se), but the printing layout will have it.

Generating random strings with T-SQL

I'm not expert in T-SQL, but the simpliest way I've already used it's like that:

select char((rand()*25 + 65))+char((rand()*25 + 65))

This generates two char (A-Z, in ascii 65-90).

How to put php inside JavaScript?

Let's see both the options:

1.) Use PHP inside Javascript

<script>
    <?php $temp = 'hello';?>
    console.log('<?php echo $temp; ?>');
</script>

Note: File name should be in .php only.

2.) Use Javascript variable inside PHP

<script>
  var res = "success";
</script>
<?php
   echo "<script>document.writeln(res);</script>";
?>

C++ equivalent of java's instanceof

Instanceof implementation without dynamic_cast

I think this question is still relevant today. Using the C++11 standard you are now able to implement a instanceof function without using dynamic_cast like this:

if (dynamic_cast<B*>(aPtr) != nullptr) {
  // aPtr is instance of B
} else {
  // aPtr is NOT instance of B
}

But you're still reliant on RTTI support. So here is my solution for this problem depending on some Macros and Metaprogramming Magic. The only drawback imho is that this approach does not work for multiple inheritance.

InstanceOfMacros.h

#include <set>
#include <tuple>
#include <typeindex>

#define _EMPTY_BASE_TYPE_DECL() using BaseTypes = std::tuple<>;
#define _BASE_TYPE_DECL(Class, BaseClass) \
  using BaseTypes = decltype(std::tuple_cat(std::tuple<BaseClass>(), Class::BaseTypes()));
#define _INSTANCE_OF_DECL_BODY(Class)                                 \
  static const std::set<std::type_index> baseTypeContainer;           \
  virtual bool instanceOfHelper(const std::type_index &_tidx) {       \
    if (std::type_index(typeid(ThisType)) == _tidx) return true;      \
    if (std::tuple_size<BaseTypes>::value == 0) return false;         \
    return baseTypeContainer.find(_tidx) != baseTypeContainer.end();  \
  }                                                                   \
  template <typename... T>                                            \
  static std::set<std::type_index> getTypeIndexes(std::tuple<T...>) { \
    return std::set<std::type_index>{std::type_index(typeid(T))...};  \
  }

#define INSTANCE_OF_SUB_DECL(Class, BaseClass) \
 protected:                                    \
  using ThisType = Class;                      \
  _BASE_TYPE_DECL(Class, BaseClass)            \
  _INSTANCE_OF_DECL_BODY(Class)

#define INSTANCE_OF_BASE_DECL(Class)                                                    \
 protected:                                                                             \
  using ThisType = Class;                                                               \
  _EMPTY_BASE_TYPE_DECL()                                                               \
  _INSTANCE_OF_DECL_BODY(Class)                                                         \
 public:                                                                                \
  template <typename Of>                                                                \
  typename std::enable_if<std::is_base_of<Class, Of>::value, bool>::type instanceOf() { \
    return instanceOfHelper(std::type_index(typeid(Of)));                               \
  }

#define INSTANCE_OF_IMPL(Class) \
  const std::set<std::type_index> Class::baseTypeContainer = Class::getTypeIndexes(Class::BaseTypes());

Demo

You can then use this stuff (with caution) as follows:

DemoClassHierarchy.hpp*

#include "InstanceOfMacros.h"

struct A {
  virtual ~A() {}
  INSTANCE_OF_BASE_DECL(A)
};
INSTANCE_OF_IMPL(A)

struct B : public A {
  virtual ~B() {}
  INSTANCE_OF_SUB_DECL(B, A)
};
INSTANCE_OF_IMPL(B)

struct C : public A {
  virtual ~C() {}
  INSTANCE_OF_SUB_DECL(C, A)
};
INSTANCE_OF_IMPL(C)

struct D : public C {
  virtual ~D() {}
  INSTANCE_OF_SUB_DECL(D, C)
};
INSTANCE_OF_IMPL(D)

The following code presents a small demo to verify rudimentary the correct behavior.

InstanceOfDemo.cpp

#include <iostream>
#include <memory>
#include "DemoClassHierarchy.hpp"

int main() {
  A *a2aPtr = new A;
  A *a2bPtr = new B;
  std::shared_ptr<A> a2cPtr(new C);
  C *c2dPtr = new D;
  std::unique_ptr<A> a2dPtr(new D);

  std::cout << "a2aPtr->instanceOf<A>(): expected=1, value=" << a2aPtr->instanceOf<A>() << std::endl;
  std::cout << "a2aPtr->instanceOf<B>(): expected=0, value=" << a2aPtr->instanceOf<B>() << std::endl;
  std::cout << "a2aPtr->instanceOf<C>(): expected=0, value=" << a2aPtr->instanceOf<C>() << std::endl;
  std::cout << "a2aPtr->instanceOf<D>(): expected=0, value=" << a2aPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "a2bPtr->instanceOf<A>(): expected=1, value=" << a2bPtr->instanceOf<A>() << std::endl;
  std::cout << "a2bPtr->instanceOf<B>(): expected=1, value=" << a2bPtr->instanceOf<B>() << std::endl;
  std::cout << "a2bPtr->instanceOf<C>(): expected=0, value=" << a2bPtr->instanceOf<C>() << std::endl;
  std::cout << "a2bPtr->instanceOf<D>(): expected=0, value=" << a2bPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "a2cPtr->instanceOf<A>(): expected=1, value=" << a2cPtr->instanceOf<A>() << std::endl;
  std::cout << "a2cPtr->instanceOf<B>(): expected=0, value=" << a2cPtr->instanceOf<B>() << std::endl;
  std::cout << "a2cPtr->instanceOf<C>(): expected=1, value=" << a2cPtr->instanceOf<C>() << std::endl;
  std::cout << "a2cPtr->instanceOf<D>(): expected=0, value=" << a2cPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "c2dPtr->instanceOf<A>(): expected=1, value=" << c2dPtr->instanceOf<A>() << std::endl;
  std::cout << "c2dPtr->instanceOf<B>(): expected=0, value=" << c2dPtr->instanceOf<B>() << std::endl;
  std::cout << "c2dPtr->instanceOf<C>(): expected=1, value=" << c2dPtr->instanceOf<C>() << std::endl;
  std::cout << "c2dPtr->instanceOf<D>(): expected=1, value=" << c2dPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "a2dPtr->instanceOf<A>(): expected=1, value=" << a2dPtr->instanceOf<A>() << std::endl;
  std::cout << "a2dPtr->instanceOf<B>(): expected=0, value=" << a2dPtr->instanceOf<B>() << std::endl;
  std::cout << "a2dPtr->instanceOf<C>(): expected=1, value=" << a2dPtr->instanceOf<C>() << std::endl;
  std::cout << "a2dPtr->instanceOf<D>(): expected=1, value=" << a2dPtr->instanceOf<D>() << std::endl;

  delete a2aPtr;
  delete a2bPtr;
  delete c2dPtr;

  return 0;
}

Output:

a2aPtr->instanceOf<A>(): expected=1, value=1
a2aPtr->instanceOf<B>(): expected=0, value=0
a2aPtr->instanceOf<C>(): expected=0, value=0
a2aPtr->instanceOf<D>(): expected=0, value=0

a2bPtr->instanceOf<A>(): expected=1, value=1
a2bPtr->instanceOf<B>(): expected=1, value=1
a2bPtr->instanceOf<C>(): expected=0, value=0
a2bPtr->instanceOf<D>(): expected=0, value=0

a2cPtr->instanceOf<A>(): expected=1, value=1
a2cPtr->instanceOf<B>(): expected=0, value=0
a2cPtr->instanceOf<C>(): expected=1, value=1
a2cPtr->instanceOf<D>(): expected=0, value=0

c2dPtr->instanceOf<A>(): expected=1, value=1
c2dPtr->instanceOf<B>(): expected=0, value=0
c2dPtr->instanceOf<C>(): expected=1, value=1
c2dPtr->instanceOf<D>(): expected=1, value=1

a2dPtr->instanceOf<A>(): expected=1, value=1
a2dPtr->instanceOf<B>(): expected=0, value=0
a2dPtr->instanceOf<C>(): expected=1, value=1
a2dPtr->instanceOf<D>(): expected=1, value=1

Performance

The most interesting question which now arises is, if this evil stuff is more efficient than the usage of dynamic_cast. Therefore I've written a very basic performance measurement app.

InstanceOfPerformance.cpp

#include <chrono>
#include <iostream>
#include <string>
#include "DemoClassHierarchy.hpp"

template <typename Base, typename Derived, typename Duration>
Duration instanceOfMeasurement(unsigned _loopCycles) {
  auto start = std::chrono::high_resolution_clock::now();
  volatile bool isInstanceOf = false;
  for (unsigned i = 0; i < _loopCycles; ++i) {
    Base *ptr = new Derived;
    isInstanceOf = ptr->template instanceOf<Derived>();
    delete ptr;
  }
  auto end = std::chrono::high_resolution_clock::now();
  return std::chrono::duration_cast<Duration>(end - start);
}

template <typename Base, typename Derived, typename Duration>
Duration dynamicCastMeasurement(unsigned _loopCycles) {
  auto start = std::chrono::high_resolution_clock::now();
  volatile bool isInstanceOf = false;
  for (unsigned i = 0; i < _loopCycles; ++i) {
    Base *ptr = new Derived;
    isInstanceOf = dynamic_cast<Derived *>(ptr) != nullptr;
    delete ptr;
  }
  auto end = std::chrono::high_resolution_clock::now();
  return std::chrono::duration_cast<Duration>(end - start);
}

int main() {
  unsigned testCycles = 10000000;
  std::string unit = " us";
  using DType = std::chrono::microseconds;

  std::cout << "InstanceOf performance(A->D)  : " << instanceOfMeasurement<A, D, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "InstanceOf performance(A->C)  : " << instanceOfMeasurement<A, C, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "InstanceOf performance(A->B)  : " << instanceOfMeasurement<A, B, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "InstanceOf performance(A->A)  : " << instanceOfMeasurement<A, A, DType>(testCycles).count() << unit
            << "\n"
            << std::endl;
  std::cout << "DynamicCast performance(A->D) : " << dynamicCastMeasurement<A, D, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "DynamicCast performance(A->C) : " << dynamicCastMeasurement<A, C, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "DynamicCast performance(A->B) : " << dynamicCastMeasurement<A, B, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "DynamicCast performance(A->A) : " << dynamicCastMeasurement<A, A, DType>(testCycles).count() << unit
            << "\n"
            << std::endl;
  return 0;
}

The results vary and are essentially based on the degree of compiler optimization. Compiling the performance measurement program using g++ -std=c++11 -O0 -o instanceof-performance InstanceOfPerformance.cpp the output on my local machine was:

InstanceOf performance(A->D)  : 699638 us
InstanceOf performance(A->C)  : 642157 us
InstanceOf performance(A->B)  : 671399 us
InstanceOf performance(A->A)  : 626193 us

DynamicCast performance(A->D) : 754937 us
DynamicCast performance(A->C) : 706766 us
DynamicCast performance(A->B) : 751353 us
DynamicCast performance(A->A) : 676853 us

Mhm, this result was very sobering, because the timings demonstrates that the new approach is not much faster compared to the dynamic_cast approach. It is even less efficient for the special test case which tests if a pointer of A is an instance ofA. BUT the tide turns by tuning our binary using compiler otpimization. The respective compiler command is g++ -std=c++11 -O3 -o instanceof-performance InstanceOfPerformance.cpp. The result on my local machine was amazing:

InstanceOf performance(A->D)  : 3035 us
InstanceOf performance(A->C)  : 5030 us
InstanceOf performance(A->B)  : 5250 us
InstanceOf performance(A->A)  : 3021 us

DynamicCast performance(A->D) : 666903 us
DynamicCast performance(A->C) : 698567 us
DynamicCast performance(A->B) : 727368 us
DynamicCast performance(A->A) : 3098 us

If you are not reliant on multiple inheritance, are no opponent of good old C macros, RTTI and template metaprogramming and are not too lazy to add some small instructions to the classes of your class hierarchy, then this approach can boost your application a little bit with respect to its performance, if you often end up with checking the instance of a pointer. But use it with caution. There is no warranty for the correctness of this approach.

Note: All demos were compiled using clang (Apple LLVM version 9.0.0 (clang-900.0.39.2)) under macOS Sierra on a MacBook Pro Mid 2012.

Edit: I've also tested the performance on a Linux machine using gcc (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609. On this platform the perfomance benefit was not so significant as on macOs with clang.

Output (without compiler optimization):

InstanceOf performance(A->D)  : 390768 us
InstanceOf performance(A->C)  : 333994 us
InstanceOf performance(A->B)  : 334596 us
InstanceOf performance(A->A)  : 300959 us

DynamicCast performance(A->D) : 331942 us
DynamicCast performance(A->C) : 303715 us
DynamicCast performance(A->B) : 400262 us
DynamicCast performance(A->A) : 324942 us

Output (with compiler optimization):

InstanceOf performance(A->D)  : 209501 us
InstanceOf performance(A->C)  : 208727 us
InstanceOf performance(A->B)  : 207815 us
InstanceOf performance(A->A)  : 197953 us

DynamicCast performance(A->D) : 259417 us
DynamicCast performance(A->C) : 256203 us
DynamicCast performance(A->B) : 261202 us
DynamicCast performance(A->A) : 193535 us

How to grey out a button?

You should create a XML file for the disabled button (drawable/btn_disable.xml)

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/grey" />
    <corners android:radius="6dp" />
</shape>

And create a selector for the button (drawable/btn_selector.xml)

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

    <item android:drawable="@drawable/btn_disable" android:state_enabled="false"/>
    <item android:drawable="@drawable/btn_default" android:state_enabled="true"/>
    <item android:drawable="@drawable/btn_default" android:state_pressed="false" />

</selector>

Add the selector to your button

<style name="srp_button" parent="@android:style/Widget.Button">
    <item name="android:background">@drawable/btn_selector</item>
</style>

How to check if a variable is an integer or a string?

Depending on your definition of shortly, you could use one of the following options:

How to find event listeners on a DOM node when debugging or from the JavaScript code?

It is possible to list all event listeners in JavaScript: It's not that hard; you just have to hack the prototype's method of the HTML elements (before adding the listeners).

function reportIn(e){
    var a = this.lastListenerInfo[this.lastListenerInfo.length-1];
    console.log(a)
}


HTMLAnchorElement.prototype.realAddEventListener = HTMLAnchorElement.prototype.addEventListener;

HTMLAnchorElement.prototype.addEventListener = function(a,b,c){
    this.realAddEventListener(a,reportIn,c); 
    this.realAddEventListener(a,b,c); 
    if(!this.lastListenerInfo){  this.lastListenerInfo = new Array()};
    this.lastListenerInfo.push({a : a, b : b , c : c});
};

Now every anchor element (a) will have a lastListenerInfo property wich contains all of its listeners. And it even works for removing listeners with anonymous functions.

web-api POST body object always null

I just ran into this and was frustrating. My setup: The header was set to Content-Type: application/JSON and was passing the info from the body with JSON format, and was reading [FromBody] on the controller.

Everything was set up fine and I expect it to work, but the problem was with the JSON sent over. Since it was a complex structure, one of my classes which was defined 'Abstract' was not getting initialized and hence the values weren't assigned to the model properly. I removed the abstract keyword and it just worked..!!!

One tip, the way I could figure this out was to send data in parts to my controller and check when it becomes null... since it was a complex model I was appending one model at a time to my request params. Hope it helps someone who runs into this stupid issue.

Printing Batch file results to a text file

You can add this piece of code to the top of your batch file:

@Echo off
SET LOGFILE=MyLogFile.log
call :Logit >> %LOGFILE% 
exit /b 0

:Logit
:: The rest of your code
:: ....

It basically redirects the output of the :Logit method to the LOGFILE. The exit command is to ensure the batch exits after executing :Logit.

Eclipse Java Missing required source folder: 'src'

Go to the Build Path dialog (right-click project > Build Path > Configure Build Path) and make sure you have the correct source folder listed, and make sure it exists.

The source folder is the one that holds your sources, usuglaly in the form: project/src/com/yourpackage/...

Trees in Twitter Bootstrap

Another great Treeview jquery plugin is http://www.jstree.com/

For an advance view you should check jquery-treetable
http://ludo.cubicphuse.nl/jquery-plugins/treeTable/doc/

No == operator found while comparing structs in C++

Because you did not write a comparison operator for your struct. The compiler does not generate it for you, so if you want comparison, you have to write it yourself.

How do I display the current value of an Android Preference in the Preference summary?

Here's my solution:

Build a preference type 'getter' method.

protected String getPreference(Preference x) {
    // http://stackoverflow.com/questions/3993982/how-to-check-type-of-variable-in-java
    if (x instanceof CheckBoxPreference)
        return "CheckBoxPreference";
    else if (x instanceof EditTextPreference)
        return "EditTextPreference";
    else if (x instanceof ListPreference)
        return "ListPreference";
    else if (x instanceof MultiSelectListPreference)
        return "MultiSelectListPreference";
    else if (x instanceof RingtonePreference)
        return "RingtonePreference";
    else if (x instanceof SwitchPreference)
        return "SwitchPreference";
    else if (x instanceof TwoStatePreference)
        return "TwoStatePreference";
    else if (x instanceof DialogPreference) // Needs to be after ListPreference
        return "DialogPreference";
    else
        return "undefined";
}

Build a 'setSummaryInit' method.

public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
        Log.i(TAG, "+ onSharedPreferenceChanged(prefs:" + prefs + ", key:" + key + ")");
        if( key != null ) {
            updatePreference(prefs, key);
            setSummary(key);
        } else {
            Log.e(TAG, "Preference without key!");
        }
        Log.i(TAG, "- onSharedPreferenceChanged()");
    }

    protected boolean setSummary() {
        return _setSummary(null);
    }
    
    protected boolean setSummary(String sKey) {
        return _setSummary(sKey);
    }
    
    private boolean _setSummary(String sKey) {
        if (sKey == null) Log.i(TAG, "Initializing");
        else Log.i(TAG, sKey);
        
        // Get Preferences
        SharedPreferences sharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(this);

        // Iterate through all Shared Preferences
        // http://stackoverflow.com/questions/9310479/how-to-iterate-through-all-keys-of-shared-preferences
        Map<String, ?> keys = sharedPrefs.getAll();
        for (Map.Entry<String, ?> entry : keys.entrySet()) {
            String key = entry.getKey();
            // Do work only if initializing (null) or updating specific preference key
            if ( (sKey == null) || (sKey.equals(key)) ) {
                String value = entry.getValue().toString();
                Preference pref = findPreference(key);
                String preference = getPreference(pref);
                Log.d("map values", key + " | " + value + " | " + preference);
                pref.setSummary(key + " | " + value + " | " + preference);
                if (sKey != null) return true;
            }
        }
        return false;
    }

    private void updatePreference(SharedPreferences prefs, String key) {
        Log.i(TAG, "+ updatePreference(prefs:" + prefs + ", key:" + key + ")");
        Preference pref = findPreference(key);
        String preferenceType = getPreference(pref);
        Log.i(TAG, "preferenceType = " + preferenceType);
        Log.i(TAG, "- updatePreference()");
    }

Initialize

Create public class that PreferenceActivity and implements OnSharedPreferenceChangeListener

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    PreferenceManager.setDefaultValues(this, R.xml.global_preferences,
    false);
    this.addPreferencesFromResource(R.xml.global_preferences);
    this.getPreferenceScreen().getSharedPreferences()
        .registerOnSharedPreferenceChangeListener(this);
}

protected void onResume() {
    super.onResume();
    setSummary();
}

Create intermediate folders if one doesn't exist

Use this code spinet for create intermediate folders if one doesn't exist while creating/editing file:

File outFile = new File("/dir1/dir2/dir3/test.file");
outFile.getParentFile().mkdirs();
outFile.createNewFile();

Align div right in Bootstrap 3

Bootstrap 4+ has made changes to the utility classes for this. From the documentation:

Added .float-{sm,md,lg,xl}-{left,right,none} classes for responsive floats and removed .pull-left and .pull-right since they’re redundant to .float-left and .float-right.

So use the .float-right (or a size equivalent such as .float-lg-right) instead of .pull-right for your right alignment if you're using a newer Bootstrap version.

Example to use shared_ptr?

The best way to add different objects into same container is to use make_shared, vector, and range based loop and you will have a nice, clean and "readable" code!

typedef std::shared_ptr<gate> Ptr   
vector<Ptr> myConatiner; 
auto andGate = std::make_shared<ANDgate>();
myConatiner.push_back(andGate );
auto orGate= std::make_shared<ORgate>();
myConatiner.push_back(orGate);

for (auto& element : myConatiner)
    element->run();

How to convert a String into an array of Strings containing one character each

If by array of String you mean array of char:

public class Test
{
    public static void main(String[] args)
    {
        String test = "aabbab ";
        char[] t = test.toCharArray();

        for(char c : t)
            System.out.println(c);    

        System.out.println("The end!");    
    }
}  

If not, the String.split() function could transform a String into an array of String

See those String.split examples

/* String to split. */
String str = "one-two-three";
String[] temp;

/* delimiter */
String delimiter = "-";
/* given string will be split by the argument delimiter provided. */
temp = str.split(delimiter);
/* print substrings */
for(int i =0; i < temp.length ; i++)
  System.out.println(temp[i]);

The input.split("(?!^)") proposed by Joachim in his answer is based on:

  • a '?!' zero-width negative lookahead (see Lookaround)
  • the caret '^' as an Anchor to match the start of the string the regex pattern is applied to

Any character which is not the first will be split. An empty string will not be split but return an empty array.

Scanner is skipping nextLine() after using next() or nextFoo()?

I guess I'm pretty late to the party..

As previously stated, calling input.nextLine() after getting your int value will solve your problem. The reason why your code didn't work was because there was nothing else to store from your input (where you inputted the int) into string1. I'll just shed a little more light to the entire topic.

Consider nextLine() as the odd one out among the nextFoo() methods in the Scanner class. Let's take a quick example.. Let's say we have two lines of code like the ones below:

int firstNumber = input.nextInt();
int secondNumber = input.nextInt();

If we input the value below (as a single line of input)

54 234

The value of our firstNumber and secondNumber variable become 54 and 234 respectively. The reason why this works this way is because a new line feed (i.e \n) IS NOT automatically generated when the nextInt() method takes in the values. It simply takes the "next int" and moves on. This is the same for the rest of the nextFoo() methods except nextLine().

nextLine() generates a new line feed immediately after taking a value; this is what @RohitJain means by saying the new line feed is "consumed".

Lastly, the next() method simply takes the nearest String without generating a new line; this makes this the preferential method for taking separate Strings within the same single line.

I hope this helps.. Merry coding!

Should a function have only one return statement?

My usual policy is to have only one return statement at the end of a function unless the complexity of the code is greatly reduced by adding more. In fact, I'm rather a fan of Eiffel, which enforces the only one return rule by having no return statement (there's just a auto-created 'result' variable to put your result in).

There certainly are cases where code can be made clearer with multiple returns than the obvious version without them would be. One could argue that more rework is needed if you have a function that is too complex to be understandable without multiple return statements, but sometimes it's good to be pragmatic about such things.

Open file dialog box in JavaScript

_x000D_
_x000D_
    $("#logo").css('opacity','0');_x000D_
    _x000D_
    $("#select_logo").click(function(e){_x000D_
       e.preventDefault();_x000D_
       $("#logo").trigger('click');_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<a href="#" id="select_logo">Select Logo</a> <input type="file" id="logo">
_x000D_
_x000D_
_x000D_

for IE add this:

$("#logo").css('filter','alpha(opacity = 0');

Check if a value exists in pandas dataframe index

Just for reference as it was something I was looking for, you can test for presence within the values or the index by appending the ".values" method, e.g.

g in df.<your selected field>.values
g in df.index.values

I find that adding the ".values" to get a simple list or ndarray out makes exist or "in" checks run more smoothly with the other python tools. Just thought I'd toss that out there for people.

if arguments is equal to this string, define a variable like this string

It seems that you are looking to parse commandline arguments into your bash script. I have searched for this recently myself. I came across the following which I think will assist you in parsing the arguments:

http://rsalveti.wordpress.com/2007/04/03/bash-parsing-arguments-with-getopts/

I added the snippet below as a tl;dr

#using : after a switch variable means it requires some input (ie, t: requires something after t to validate while h requires nothing.
while getopts “ht:r:p:v” OPTION
do
     case $OPTION in
         h)
             usage
             exit 1
             ;;
         t)
             TEST=$OPTARG
             ;;
         r)
             SERVER=$OPTARG
             ;;
         p)
             PASSWD=$OPTARG
             ;;
         v)
             VERBOSE=1
             ;;
         ?)
             usage
             exit
             ;;
     esac
done

if [[ -z $TEST ]] || [[ -z $SERVER ]] || [[ -z $PASSWD ]]
then
     usage
     exit 1
fi

./script.sh -t test -r server -p password -v

Enterprise app deployment doesn't work on iOS 7.1

The universal solution is to connect your device to Mac and to observe what's going on during installation. I got an error:

Could not load download manifest with underlying error: Error Domain=NSURLErrorDomain Code=-1202 "Cannot connect to the Store" UserInfo=0x146635d0 {NSLocalizedDescription=Cannot connect to the Store, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, NSLocalizedFailureReason=A secure connection could not be established. Please check your Date & Time settings., NSErrorFailingURLStringKey=https://myserver.com/app/manifest.plist, NSUnderlyingError=0x14678880 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “myserver.com” which could put your confidential information at risk.", NSURLErrorFailingURLPeerTrustErrorKey=, NSErrorFailingURLKey=https://myserver.com/app/manifest.plist}

There was even the suggestion in that error to check date settings. For some reason the date was 1 January 1970. Setting correct date solved the problem.

What's the difference between OpenID and OAuth?

The explanation of the difference between OpenID, OAuth, OpenID Connect:

OpenID is a protocol for authentication while OAuth is for authorization. Authentication is about making sure that the guy you are talking to is indeed who he claims to be. Authorization is about deciding what that guy should be allowed to do.

In OpenID, authentication is delegated: server A wants to authenticate user U, but U's credentials (e.g. U's name and password) are sent to another server, B, that A trusts (at least, trusts for authenticating users). Indeed, server B makes sure that U is indeed U, and then tells to A: "ok, that's the genuine U".

In OAuth, authorization is delegated: entity A obtains from entity B an "access right" which A can show to server S to be granted access; B can thus deliver temporary, specific access keys to A without giving them too much power. You can imagine an OAuth server as the key master in a big hotel; he gives to employees keys which open the doors of the rooms that they are supposed to enter, but each key is limited (it does not give access to all rooms); furthermore, the keys self-destruct after a few hours.

To some extent, authorization can be abused into some pseudo-authentication, on the basis that if entity A obtains from B an access key through OAuth, and shows it to server S, then server S may infer that B authenticated A before granting the access key. So some people use OAuth where they should be using OpenID. This schema may or may not be enlightening; but I think this pseudo-authentication is more confusing than anything. OpenID Connect does just that: it abuses OAuth into an authentication protocol. In the hotel analogy: if I encounter a purported employee and that person shows me that he has a key which opens my room, then I suppose that this is a true employee, on the basis that the key master would not have given him a key which opens my room if he was not.

(source)

How is OpenID Connect different than OpenID 2.0?

OpenID Connect performs many of the same tasks as OpenID 2.0, but does so in a way that is API-friendly, and usable by native and mobile applications. OpenID Connect defines optional mechanisms for robust signing and encryption. Whereas integration of OAuth 1.0a and OpenID 2.0 required an extension, in OpenID Connect, OAuth 2.0 capabilities are integrated with the protocol itself.

(source)

OpenID connect will give you an access token plus an id token. The id token is a JWT and contains information about the authenticated user. It is signed by the identity provider and can be read and verified without accessing the identity provider.

In addition, OpenID connect standardizes quite a couple things that oauth2 leaves up to choice. for instance scopes, endpoint discovery, and dynamic registration of clients.

This makes it easier to write code that lets the user choose between multiple identity providers.

(source)

Google's OAuth 2.0

Google's OAuth 2.0 APIs can be used for both authentication and authorization. This document describes our OAuth 2.0 implementation for authentication, which conforms to the OpenID Connect specification, and is OpenID Certified. The documentation found in Using OAuth 2.0 to Access Google APIs also applies to this service. If you want to explore this protocol interactively, we recommend the Google OAuth 2.0 Playground.

(source)

In bash, how to store a return value in a variable?

Simplest answer:

the return code from a function can be only a value in the range from 0 to 255 . To store this value in a variable you have to do like in this example:

#!/bin/bash

function returnfunction {
    # example value between 0-255 to be returned 
    return 23
}

# note that the value has to be stored immediately after the function call :
returnfunction
myreturnvalue=$?

echo "myreturnvalue is "$myreturnvalue

How to write std::string to file?

Assuming you're using a std::ofstream to write to file, the following snippet will write a std::string to file in human readable form:

std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;

Confused by python file mode "w+"

Actually, there's something wrong about all the other answers about r+ mode.

test.in file's content:

hello1
ok2
byebye3

And the py script's :

with open("test.in", 'r+')as f:
    f.readline()
    f.write("addition")

Execute it and the test.in's content will be changed to :

hello1
ok2
byebye3
addition

However, when we modify the script to :

with open("test.in", 'r+')as f:
    f.write("addition")

the test.in also do the respond:

additionk2
byebye3

So, the r+ mode will allow us to cover the content from the beginning if we did't do the read operation. And if we do some read operation, f.write()will just append to the file.

By the way, if we f.seek(0,0) before f.write(write_content), the write_content will cover them from the positon(0,0).

H2 in-memory database. Table not found

I have tried to add

jdbc:h2:mem:test;DB_CLOSE_DELAY=-1

However, that didn't helped. On the H2 site, I have found following, which indeed could help in some cases.

By default, closing the last connection to a database closes the database. For an in-memory database, this means the content is lost. To keep the database open, add ;DB_CLOSE_DELAY=-1 to the database URL. To keep the content of an in-memory database as long as the virtual machine is alive, use jdbc:h2:mem:test;DB_CLOSE_DELAY=-1.

However, my issue was that just the schema supposed to be different than default one. So insted of using

JDBC URL: jdbc:h2:mem:test

I had to use:

JDBC URL: jdbc:h2:mem:testdb

Then the tables were visible

Disabled form fields not submitting data

Use the CSS pointer-events:none on fields you want to "disable" (possibly together with a greyed background) which allows the POST action, like:

<input type="text" class="disable">

.disable{
pointer-events:none;
background:grey;
}

Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

How do I get and set Environment variables in C#?

Get and Set

Get

string getEnv = Environment.GetEnvironmentVariable("envVar");

Set

string setEnv = Environment.SetEnvironmentVariable("envvar", varEnv);

Generator expressions vs. list comprehensions

Sometimes you can get away with the tee function from itertools, it returns multiple iterators for the same generator that can be used independently.

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

Samsung Galaxy Phones has a feature Known as Secure Folder Removing App from That Solved The problem for me.

also adb uninstall packagename can Not remove App from Secure folder.

Check if table exists

    /**
 * Method that checks if all tables exist
 * If a table doesnt exist it creates the table
 */
public void checkTables() {
    try {
        startConn();// method that connects with mysql database
        String useDatabase = "USE " + getDatabase() + ";";
        stmt.executeUpdate(useDatabase);
        String[] tables = {"Patients", "Procedures", "Payments", "Procedurables"};//thats table names that I need to create if not exists
        DatabaseMetaData metadata = conn.getMetaData();

        for(int i=0; i< tables.length; i++) {
            ResultSet rs = metadata.getTables(null, null, tables[i], null);
            if(!rs.next()) {
                createTable(tables[i]);
                System.out.println("Table " + tables[i] + " created");
            }
        }
    } catch(SQLException e) {
        System.out.println("checkTables() " + e.getMessage());
    }
    closeConn();// Close connection with mysql database
}

How can I create an MSI setup?

Look for Windows Installer XML (WiX)

Differences between Ant and Maven

I'd say it depends upon the size of your project... Personnally, I would use Maven for simple projects that need straightforward compiling, packaging and deployment. As soon as you need to do some more complicated things (many dependencies, creating mapping files...), I would switch to Ant...

How can I remove the "No file chosen" tooltip from a file input in Chrome?

The default tooltip can be edited by using the title attribute

<input type='file' title="your text" />

But if you try to remove this tooltip

<input type='file' title=""/>

This won't work. Here is my little trick to work this, try title with a space. It will work.:)

<input type='file' title=" "/>

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

Check if table exists and if it doesn't exist, create it in SQL Server 2008

Let us create a sample database with a table by the below script:

CREATE DATABASE Test
GO
USE Test
GO
CREATE TABLE dbo.tblTest (Id INT, Name NVARCHAR(50))

Approach 1: Using INFORMATION_SCHEMA.TABLES view

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

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

The above query checks the existence of the tblTest table across all the schemas in the current database. Instead of this if you want to check the existence of the Table in a specified Schema and the Specified Database then we can write the above query as below:

IF EXISTS (SELECT * FROM Test.INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = N'dbo'  AND TABLE_NAME = N'tblTest')
BEGIN
  PRINT 'Table Exists'
END

Pros of this Approach: INFORMATION_SCHEMA views are portable across different RDBMS systems, so porting to different RDBMS doesn’t require any change.

Approach 2: Using OBJECT_ID() function

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

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

Specifying the Database Name and Schema Name parts for the Table Name is optional. But specifying Database Name and Schema Name provides an option to check the existence of the table in the specified database and within a specified schema, instead of checking in the current database across all the schemas. The below query shows that even though the current database is MASTER database, we can check the existence of the tblTest table in the dbo schema in the Test database.

USE MASTER
GO
IF OBJECT_ID(N'Test.dbo.tblTest', N'U') IS NOT NULL
BEGIN
  PRINT 'Table Exists'
END

Pros: Easy to remember. One other notable point to mention about OBJECT_ID() function is: it provides an option to check the existence of the Temporary Table which is created in the current connection context. All other Approaches checks the existence of the Temporary Table created across all the connections context instead of just the current connection context. Below query shows how to check the existence of a Temporary Table using OBJECT_ID() function:

CREATE TABLE #TempTable(ID INT)
GO
IF OBJECT_ID(N'TempDB.dbo.#TempTable', N'U') IS NOT NULL
BEGIN
  PRINT 'Table Exists'
END
GO

Approach 3: Using sys.Objects Catalog View

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

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

Approach 4: Using sys.Tables Catalog View

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

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

Sys.Tables catalog view inherits the rows from the Sys.Objects catalog view, Sys.objects catalog view is referred to as base view where as sys.Tables is referred to as derived view. Sys.Tables will return the rows only for the Table objects whereas Sys.Object view apart from returning the rows for table objects, it returns rows for the objects like: stored procedure, views etc.

Approach 5: Avoid Using sys.sysobjects System table

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

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

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

"make clean" results in "No rule to make target `clean'"

Check that the file is called GNUMakefile, makefile or Makefile.

If it is called anything else (and you don't want to rename it) then try:

make -f othermakefilename clean

What's the difference between display:inline-flex and display:flex?

Using two-value display syntax instead, for clarity

The display CSS property in fact sets two things at once: the outer display type, and the inner display type. The outer display type affects how the element (which acts as a container) is displayed in its context. The inner display type affects how the children of the element (or the children of the container) are laid out.

If you use the two-value display syntax, which is only supported in some browsers like Firefox, the difference between the two is much more obvious:

  • display: block is equivalent to display: block flow
  • display: inline is equivalent to display: inline flow
  • display: flex is equivalent to display: block flex
  • display: inline-flex is equivalent to display: inline flex
  • display: grid is equivalent to display: block grid
  • display: inline-grid is equivalent to display: inline grid

Outer display type: block or inline:

An element with the outer display type of block will take up the whole width available to it, like <div> does. An element with the outer display type of inline will only take up the width that it needs, with wrapping, like <span> does.

Inner display type: flow, flex or grid:

The inner display type flow is the default inner display type when flex or grid is not specified. It is the way of laying out children elements that we are used to in a <p> for instance. flex and grid are new ways of laying out children that each deserve their own post.

Conclusion:

The difference between display: flex and display: inline-flex is the outer display type, the first's outer display type is block, and the second's outer display type is inline. Both of them have the inner display type of flex.

References:

Calculating text width

I had trouble with solutions like @rune-kaagaard's for large amounts of text. I discovered this:

_x000D_
_x000D_
$.fn.textWidth = function() {_x000D_
 var width = 0;_x000D_
 var calc = '<span style="display: block; width: 100%; overflow-y: scroll; white-space: nowrap;" class="textwidth"><span>' + $(this).html() + '</span></span>';_x000D_
 $('body').append(calc);_x000D_
 var last = $('body').find('span.textwidth:last');_x000D_
 if (last) {_x000D_
   var lastcontent = last.find('span');_x000D_
   width = lastcontent.width();_x000D_
   last.remove();_x000D_
 }_x000D_
 return width;_x000D_
};
_x000D_
_x000D_
_x000D_

JSFiddle GitHub

How to change the name of an iOS app?

Its very easy to change in XCode 8, enter the app name in the "Display Name" field in Project Target -> General Identity section.

enter image description here

How do I fix the indentation of selected lines in Visual Studio

For the Mac users.

For selecting all of the code in the document => cmd+A

For formatting selected code => cmd+K, cmd+F

What is size_t in C?

size_t is an unsigned integer data type which can assign only 0 and greater than 0 integer values. It measure bytes of any object's size and returned by sizeof operator. const is the syntax representation of size_t, but without const you can run the programm.

const size_t number;

size_t regularly used for array indexing and loop counting. If the compiler is 32-bit it would work on unsigned int. If the compiler is 64-bit it would work on unsigned long long int also. There for maximum size of size_t depending on compiler type.

size_t already define on <stdio.h> header file, but It can also define by <stddef.h>, <stdlib.h>, <string.h>, <time.h>, <wchar.h> headers.

  • Example (with const)
#include <stdio.h>

int main()
{
    const size_t value = 200;
    size_t i;
    int arr[value];

    for (i = 0 ; i < value ; ++i)
    {
        arr[i] = i;
    }

    size_t size = sizeof(arr);
    printf("size = %zu\n", size);
}

Output -: size = 800


  • Example (without const)
#include <stdio.h>

int main()
{
    size_t value = 200;
    size_t i;
    int arr[value];

    for (i = 0 ; i < value ; ++i)
    {
        arr[i] = i;
    }

    size_t size = sizeof(arr);
    printf("size = %zu\n", size);
}

Output -: size = 800

Android textview usage as label and value

You should implement a Custom List View, such that you define a Layout once and draw it for every row in the list view.

Normalization in DOM parsing with java - how does it work?

In simple, Normalisation is Reduction of Redundancies.
Examples of Redundancies:
a) white spaces outside of the root/document tags(...<document></document>...)
b) white spaces within start tag (<...>) and end tag (</...>)
c) white spaces between attributes and their values (ie. spaces between key name and =")
d) superfluous namespace declarations
e) line breaks/white spaces in texts of attributes and tags
f) comments etc...

Can a WSDL indicate the SOAP version (1.1 or 1.2) of the web service?

Yes you can usually see what SOAP version is supported based on the WSDL.

Take a look at Demo web service WSDL. It has a reference to the soap12 namespace indicating it supports SOAP 1.2. If that was absent then you'd probably be safe assuming the service only supported SOAP 1.1.

HTML - how to make an entire DIV a hyperlink?

You just need to specify the cursor as a pointer, not a hand, as pointer is now the standard, so, here's the example page code:

<div onclick="location.href='portable-display-stands.html';" id="smallbox">The content of the div here</div>

and the example CSS:

#smallbox {
    cursor: pointer;
}

So the div is now a clickable element using 'onclick' and you've faked the hand cursor with the CSS...job done, works for me!

Something better than .NET Reflector?

I am not sure what you really want here. If you want to see the .NET framework source code, you may try Netmassdownloader. It's free.

If you want to see any assembly's code (not just .NET), you can use ReSharper. Although it's not free.

jQuery Ajax POST example with PHP

Handling Ajax errors and loader before submit and after submitting success shows an alert boot box with an example:

var formData = formData;

$.ajax({
    type: "POST",
    url: url,
    async: false,
    data: formData, // Only input
    processData: false,
    contentType: false,
    xhr: function ()
    {
        $("#load_consulting").show();
        var xhr = new window.XMLHttpRequest();

        // Upload progress
        xhr.upload.addEventListener("progress", function (evt) {
            if (evt.lengthComputable) {
                var percentComplete = (evt.loaded / evt.total) * 100;
                $('#addLoad .progress-bar').css('width', percentComplete + '%');
            }
        }, false);

        // Download progress
        xhr.addEventListener("progress", function (evt) {
            if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total;
            }
        }, false);
        return xhr;
    },
    beforeSend: function (xhr) {
        qyuraLoader.startLoader();
    },
    success: function (response, textStatus, jqXHR) {
        qyuraLoader.stopLoader();
        try {
            $("#load_consulting").hide();

            var data = $.parseJSON(response);
            if (data.status == 0)
            {
                if (data.isAlive)
                {
                    $('#addLoad .progress-bar').css('width', '00%');
                    console.log(data.errors);
                    $.each(data.errors, function (index, value) {
                        if (typeof data.custom == 'undefined') {
                            $('#err_' + index).html(value);
                        }
                        else
                        {
                            $('#err_' + index).addClass('error');

                            if (index == 'TopError')
                            {
                                $('#er_' + index).html(value);
                            }
                            else {
                                $('#er_TopError').append('<p>' + value + '</p>');
                            }
                        }
                    });
                    if (data.errors.TopError) {
                        $('#er_TopError').show();
                        $('#er_TopError').html(data.errors.TopError);
                        setTimeout(function () {
                            $('#er_TopError').hide(5000);
                            $('#er_TopError').html('');
                        }, 5000);
                    }
                }
                else
                {
                    $('#headLogin').html(data.loginMod);
                }
            } else {
                //document.getElementById("setData").reset();
                $('#myModal').modal('hide');
                $('#successTop').show();
                $('#successTop').html(data.msg);
                if (data.msg != '' && data.msg != "undefined") {

                    bootbox.alert({closeButton: false, message: data.msg, callback: function () {
                            if (data.url) {
                                window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
                            } else {
                                location.reload(true);
                            }
                        }});
                } else {
                    bootbox.alert({closeButton: false, message: "Success", callback: function () {
                        if (data.url) {
                            window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
                        } else {
                            location.reload(true);
                        }
                    }});
                }

            }
        }
        catch (e) {
            if (e) {
                $('#er_TopError').show();
                $('#er_TopError').html(e);
                setTimeout(function () {
                    $('#er_TopError').hide(5000);
                    $('#er_TopError').html('');
                }, 5000);
            }
        }
    }
});

Resolving tree conflict

What you can do to resolve your conflict is

svn resolve --accept working -R <path>

where <path> is where you have your conflict (can be the root of your repo).

Explanations:

  • resolve asks svn to resolve the conflict
  • accept working specifies to keep your working files
  • -R stands for recursive

Hope this helps.

EDIT:

To sum up what was said in the comments below:

  • <path> should be the directory in conflict (C:\DevBranch\ in the case of the OP)
  • it's likely that the origin of the conflict is
    • either the use of the svn switch command
    • or having checked the Switch working copy to new branch/tag option at branch creation
  • more information about conflicts can be found in the dedicated section of Tortoise's documentation.
  • to be able to run the command, you should have the CLI tools installed together with Tortoise:

Command line client tools

Objective-C for Windows

I have mixed feelings about the Cocotron project. I'm glad they are releasing source code and sharing but I don't feel that they are doing things the easiest way.

Examples.
Apple has released the source code to the objective-c runtime, which includes properties and garbage collection. The Cocotron project however has their own implementation of the objective-c runtime. Why bother to duplicate the effort? There is even a Visual Studio Project file that can be used to build an objc.dll file. Or if you're really lazy, you can just copy the DLL file from an installation of Safari on Windows.

They also did not bother to leverage CoreFoundation, which is also open sourced by Apple. I posted a question about this but did not receive an answer.

I think the current best solution is to take source code from multiple sources (Apple, CocoTron, GnuStep) and merge it together to what you need. You'll have to read a lot of source but it will be worth the end result.

How to create a new figure in MATLAB?

As has already been said: figure will create a new figure for your next plots. While calling figure you can also configure it. Example:

figHandle = figure('Name', 'Name of Figure', 'OuterPosition',[1, 1, scrsz(3), scrsz(4)]);

The example sets the name for the window and the outer size of it in relation to the used screen. Here figHandle is the handle to the resulting figure and can be used later to change appearance and content. Examples:

Dot notation:

figHandle.PaperOrientation = 'portrait';
figHandle.PaperUnits = 'centimeters';

Old Style:

set(figHandle, 'PaperOrientation', 'portrait', 'PaperUnits', 'centimeters');

Using the handle with dot notation or set, options for printing are configured here.

By keeping the handles for the figures with distinc names you can interact with multiple active figures. To set a existing figure as your active, call figure(figHandle). New plots will go there now.

How to convert a Java object (bean) to key-value pairs (and vice versa)?

One other possible way is here.

The BeanWrapper offers functionality to set and get property values (individually or in bulk), get property descriptors, and to query properties to determine if they are readable or writable.

Company c = new Company();
 BeanWrapper bwComp = BeanWrapperImpl(c);
 bwComp.setPropertyValue("name", "your Company");

What is the difference between persist() and merge() in JPA and Hibernate?

Persist should be called only on new entities, while merge is meant to reattach detached entities.

If you're using the assigned generator, using merge instead of persist can cause a redundant SQL statement.

Also, calling merge for managed entities is also a mistake since managed entities are automatically managed by Hibernate, and their state is synchronized with the database record by the dirty checking mechanism upon flushing the Persistence Context.

How can I show/hide component with JSF?

check this below code. this is for dropdown menu. In this if we select others then the text box will show otherwise text box will hide.

function show_txt(arg,arg1)
{
if(document.getElementById(arg).value=='other')
{
document.getElementById(arg1).style.display="block";
document.getElementById(arg).style.display="none";
}
else
{
document.getElementById(arg).style.display="block";
document.getElementById(arg1).style.display="none";
}
}
The HTML code here :

<select id="arg" onChange="show_txt('arg','arg1');">
<option>yes</option>
<option>No</option>
<option>Other</option>
</select>
<input type="text" id="arg1" style="display:none;">

or you can check this link click here

How can I convert an HTML table to CSV?

This method is not really a library OR a program, but for ad hoc conversions you can

  • put the HTML for a table in a text file called something.xls
  • open it with a spreadsheet
  • save it as CSV.

I know this works with Excel, and I believe I've done it with the OpenOffice spreadsheet.

But you probably would prefer a Perl or Ruby script...

Linux command: How to 'find' only text files?

If you are interested in finding any file type by their magic bytes using the awesome file utility combined with power of find, this can come in handy:

$ # Let's make some test files
$ mkdir ASCII-finder
$ cd ASCII-finder
$ dd if=/dev/urandom of=binary.file bs=1M count=1
1+0 records in
1+0 records out
1048576 bytes (1.0 MB, 1.0 MiB) copied, 0.009023 s, 116 MB/s
$ file binary.file
binary.file: data
$ echo 123 > text.txt
$ # Let the magic begin
$ find -type f -print0 | \
    xargs -0 -I @@ bash -c 'file "$@" | grep ASCII &>/dev/null && echo "file is ASCII: $@"' -- @@

Output:

file is ASCII: ./text.txt

Legend: $ is the interactive shell prompt where we enter our commands

You can modify the part after && to call some other script or do some other stuff inline as well, i.e. if that file contains given string, cat the entire file or look for a secondary string in it.

Explanation:

  • find items that are files
  • Make xargs feed each item as a line into one liner bash command/script
  • file checks type of file by magic byte, grep checks if ASCII exists, if so, then after && your next command executes.
  • find prints results null separated, this is good to escape filenames with spaces and meta-characters in it.
  • xargs , using -0 option, reads them null separated, -I @@ takes each record and uses as positional parameter/args to bash script.
  • -- for bash ensures whatever comes after it is an argument even if it starts with - like -c which could otherwise be interpreted as bash option

If you need to find types other than ASCII, simply replace grep ASCII with other type, like grep "PDF document, version 1.4"

Ignoring directories in Git repositories on Windows

I had some issues creating a file in Windows Explorer with a . at the beginning.

A workaround was to go into the commandshell and create a new file using "edit".

The 'Access-Control-Allow-Origin' header contains multiple values

The 'Access-Control-Allow-Origin' header contains multiple values

when i received this error i spent tons of hours searching solution for this but nothing works, finally i found solution to this problem which is very simple. when ''Access-Control-Allow-Origin' header added more than one time to your response this error occur, check your apache.conf or httpd.conf (Apache server), server side script, and remove unwanted entry header from these files.

Basic authentication with fetch?

You can also use btoa instead of base64.encode().

headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));

How do I create a constant in Python?

You can use Tuple for constant variable :

• A tuple is a collection which is ordered and unchangeable

my_tuple = (1, "Hello", 3.4)
print(my_tuple[0])

how to insert value into DataGridView Cell?

This is perfect code but it cannot add a new row:

dataGridView1.Rows[rowIndex].Cells[columnIndex].Value = value;

But this code can insert a new row:

var index = this.dataGridView1.Rows.Add();
this.dataGridView1.Rows[index].Cells[1].Value = "1";
this.dataGridView1.Rows[index].Cells[2].Value = "Baqar";

How to add images in select list?

not exactly an image, but i found the easiest solution was to just add some unicode code in, ? works great for me

define() vs. const

To add on NikiC's answer. const can be used within classes in the following manner:

class Foo {
    const BAR = 1;

    public function myMethod() {
        return self::BAR;
    }
}

You can not do this with define().

Total size of the contents of all the files in a directory

du is handy, but find is useful in case if you want to calculate the size of some files only (for example, using filter by extension). Also note that find themselves can print the size of each file in bytes. To calculate a total size we can connect dc command in the following manner:

find . -type f -printf "%s + " | dc -e0 -f- -ep

Here find generates sequence of commands for dc like 123 + 456 + 11 +. Although, the completed program should be like 0 123 + 456 + 11 + p (remember postfix notation).

So, to get the completed program we need to put 0 on the stack before executing the sequence from stdin, and print the top number after executing (the p command at the end). We achieve it via dc options:

  1. -e0 is just shortcut for -e '0' that puts 0 on the stack,
  2. -f- is for read and execute commands from stdin (that generated by find here),
  3. -ep is for print the result (-e 'p').

To print the size in MiB like 284.06 MiB we can use -e '2 k 1024 / 1024 / n [ MiB] p' in point 3 instead (most spaces are optional).

Could not load file or assembly System.Net.Http, Version=4.0.0.0 with ASP.NET (MVC 4) Web API OData Prerelease

i solve by way nuget. the first you install nuget. the second you use.
illustration follow:

third : Check to see if this is the latest version by looking at the "Version" property.

The finaly : you check project have latest version again.

How to close <img> tag properly?

It's helpful to have the closing tag if you will ever try to read it with an XHTML parser. Might be an edge case but I do it all the time. It does no harm having it, and means I know we can use an array of XML readers which won't keel over when they hit an unclosed tag.

If you are never going to try to parse the content, then ignore the closing.

Angular2 Material Dialog css, dialog size

On smaller screen's like laptop the dialog will shrink. To auto-fix, try the following option

http://answersicouldntfindanywhereelse.blogspot.com/2018/05/angular-material-full-size-dialog-on.html

Additional Reading https://material.angular.io/cdk/layout/overview

Thanks to the solution in answersicouldntfindanywhereelse (2nd para). it worked for me.

Following is needed

import { Breakpoints, BreakpointObserver } from '@angular/cdk/layout'

How do I determine whether my calculation of pi is accurate?

Undoubtedly, for your purposes (which I assume is just a programming exercise), the best thing is to check your results against any of the listings of the digits of pi on the web.

And how do we know that those values are correct? Well, I could say that there are computer-science-y ways to prove that an implementation of an algorithm is correct.

More pragmatically, if different people use different algorithms, and they all agree to (pick a number) a thousand (million, whatever) decimal places, that should give you a warm fuzzy feeling that they got it right.

Historically, William Shanks published pi to 707 decimal places in 1873. Poor guy, he made a mistake starting at the 528th decimal place.

Very interestingly, in 1995 an algorithm was published that had the property that would directly calculate the nth digit (base 16) of pi without having to calculate all the previous digits!

Finally, I hope your initial algorithm wasn't pi/4 = 1 - 1/3 + 1/5 - 1/7 + ... That may be the simplest to program, but it's also one of the slowest ways to do so. Check out the pi article on Wikipedia for faster approaches.

Media query to detect if device is touchscreen

The CSS solutions don't appear to be widely available as of mid-2013. Instead...

  1. Nicholas Zakas explains that Modernizr applies a no-touch CSS class when the browser doesn’t support touch.

  2. Or detect in JavaScript with a simple piece of code, allowing you to implement your own Modernizr-like solution:

    <script>
        document.documentElement.className += 
        (("ontouchstart" in document.documentElement) ? ' touch' : ' no-touch');
    </script>
    

    Then you can write your CSS as:

    .no-touch .myClass {
        ...
    }
    .touch .myClass {
        ...
    }
    

What is process.env.PORT in Node.js?

When hosting your application on another service (like Heroku, Nodejitsu, and AWS), your host may independently configure the process.env.PORT variable for you; after all, your script runs in their environment.

Amazon's Elastic Beanstalk does this. If you try to set a static port value like 3000 instead of process.env.PORT || 3000 where 3000 is your static setting, then your application will result in a 500 gateway error because Amazon is configuring the port for you.

This is a minimal Express application that will deploy on Amazon's Elastic Beanstalk:

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

// use port 3000 unless there exists a preconfigured port
var port = process.env.PORT || 3000;

app.listen(port);

Entity Framework throws exception - Invalid object name 'dbo.BaseCs'

Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.BaseCs'

This error means that EF is translating your LINQ into a sql statement that uses an object (most likely a table) named dbo.BaseCs, which does not exist in the database.

Check your database and verify whether that table exists, or that you should be using a different table name. Also, if you could post a link to the tutorial you are following, it would help to follow along with what you are doing.

C non-blocking keyboard input

On UNIX systems, you can use sigaction call to register a signal handler for SIGINT signal which represents the Control+C key sequence. The signal handler can set a flag which will be checked in the loop making it to break appropriately.

Is there a common Java utility to break a list into batches?

The following example demonstrates chunking of a List:

package de.thomasdarimont.labs;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SplitIntoChunks {

    public static void main(String[] args) {

        List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);

        List<List<Integer>> chunks = chunk(ints, 4);

        System.out.printf("Ints:   %s%n", ints);
        System.out.printf("Chunks: %s%n", chunks);
    }

    public static <T> List<List<T>> chunk(List<T> input, int chunkSize) {

        int inputSize = input.size();
        int chunkCount = (int) Math.ceil(inputSize / (double) chunkSize);

        Map<Integer, List<T>> map = new HashMap<>(chunkCount);
        List<List<T>> chunks = new ArrayList<>(chunkCount);

        for (int i = 0; i < inputSize; i++) {

            map.computeIfAbsent(i / chunkSize, (ignore) -> {

                List<T> chunk = new ArrayList<>();
                chunks.add(chunk);
                return chunk;

            }).add(input.get(i));
        }

        return chunks;
    }
}

Output:

Ints:   [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Chunks: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11]]

How to give environmental variable path for file appender in configuration file in log4j

This syntax is documented only in log4j 2.X so make sure you are using the correct version.

    <Appenders>
    <File name="file" fileName="${env:LOG_PATH}">
        <PatternLayout>
            <Pattern>%d %p %c{1.} [%t] %m %ex%n</Pattern>
        </PatternLayout>
    </File>
</Appenders>

http://logging.apache.org/log4j/2.x/manual/lookups.html#EnvironmentLookup

Convert string to JSON array

Here you get JSONObject so change this line:

JSONArray jsonArray = new JSONArray(readlocationFeed); 

with following:

JSONObject jsnobject = new JSONObject(readlocationFeed);

and after

JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject explrObject = jsonArray.getJSONObject(i);
}

Convert String to Integer in XSLT 1.0

XSLT 1.0 does not have an integer data type, only double. You can use number() to convert a string to a number.

How to install npm peer dependencies automatically?

The automatic install of peer dependencies was explicitly removed with npm 3, as it cause more problems than it tried to solve. You can read about it here for example:

So no, for the reasons given, you cannot install them automatically with npm 3 upwards.

NPM V7

NPM v7 has reintroduced the automatic peerDependencies installation. They had made some changes to fix old problems as version compatibility across multiple dependants. You can see the discussion here and the announcement here

Now in V7, as in versions before V3, you only need to do an npm i and all peerDependences should be automatically installed.

How to debug Ruby scripts

Debugging by raising exceptions is far easier than squinting through print log statements, and for most bugs, its generally much faster than opening up an irb debugger like pry or byebug. Those tools should not always be your first step.


Debugging Ruby/Rails Quickly:

1. Fast Method: Raise an Exception then and .inspect its result

The fastest way to debug Ruby (especially Rails) code is to raise an exception along the execution path of your code while calling .inspect on the method or object (e.g. foo):

raise foo.inspect

In the above code, raise triggers an Exception that halts execution of your code, and returns an error message that conveniently contains .inspect information about the object/method (i.e. foo) on the line that you're trying to debug.

This technique is useful for quickly examining an object or method (e.g. is it nil?) and for immediately confirming whether a line of code is even getting executed at all within a given context.

2. Fallback: Use a ruby IRB debugger like byebug or pry

Only after you have information about the state of your codes execution flow should you consider moving to a ruby gem irb debugger like pry or byebug where you can delve more deeply into the state of objects within your execution path.


General Beginner Advice

When you are trying to debug a problem, good advice is to always: Read The !@#$ing Error Message (RTFM)

That means reading error messages carefully and completely before acting so that you understand what it's trying to tell you. When you debug, ask the following mental questions, in this order, when reading an error message:

  1. What class does the error reference? (i.e. do I have the correct object class or is my object nil?)
  2. What method does the error reference? (i.e. is their a type in the method; can I call this method on this type/class of object?)
  3. Finally, using what I can infer from my last two questions, what lines of code should I investigate? (remember: the last line of code in the stack trace is not necessarily where the problem lies.)

In the stack trace pay particular attention to lines of code that come from your project (e.g. lines starting with app/... if you are using Rails). 99% of the time the problem is with your own code.


To illustrate why interpreting in this order is important...

E.g. a Ruby error message that confuses many beginners:

You execute code that at some point executes as such:

@foo = Foo.new

...

@foo.bar

and you get an error that states:

undefined method "bar" for Nil:nilClass

Beginners see this error and think the problem is that the method bar is undefined. It's not. In this error the real part that matters is:

for Nil:nilClass

for Nil:nilClass means that @foo is Nil! @foo is not a Foo instance variable! You have an object that is Nil. When you see this error, it's simply ruby trying to tell you that the method bar doesn't exist for objects of the class Nil. (well duh! since we are trying to use a method for an object of the class Foo not Nil).

Unfortunately, due to how this error is written (undefined method "bar" for Nil:nilClass) its easy to get tricked into thinking this error has to do with bar being undefined. When not read carefully this error causes beginners to mistakenly go digging into the details of the bar method on Foo, entirely missing the part of the error that hints that the object is of the wrong class (in this case: nil). It's a mistake that's easily avoided by reading error messages in their entirety.

Summary:

Always carefully read the entire error message before beginning any debugging. That means: Always check the class type of an object in an error message first, then its methods, before you begin sleuthing into any stacktrace or line of code where you think the error may be occurring. Those 5 seconds can save you 5 hours of frustration.

tl;dr: Don't squint at print logs: raise exceptions or use an irb debugger instead. Avoid rabbit holes by reading errors carefully before debugging.

Swift: Convert enum value to String?

Starting from Swift 3.0 you can

var str = String(describing: Audience.friends)

How to pass IEnumerable list to controller in MVC including checkbox state?

Use a list instead and replace your foreach loop with a for loop:

@model IList<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()

    @for (var i = 0; i < Model.Count; i++) 
    {
        <tr>
            <td>
                @Html.HiddenFor(x => x[i].IP)           
                @Html.CheckBoxFor(x => x[i].Checked)
            </td>
            <td>
                @Html.DisplayFor(x => x[i].IP)
            </td>
        </tr>
    }
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

Alternatively you could use an editor template:

@model IEnumerable<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()
    @Html.EditorForModel()   
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml which will automatically be rendered for each element of the collection:

@model BlockedIPViewModel
<tr>
    <td>
        @Html.HiddenFor(x => x.IP)
        @Html.CheckBoxFor(x => x.Checked)
    </td>
    <td>
        @Html.DisplayFor(x => x.IP)
    </td>
</tr>

The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article.

Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.

How to connect to MySQL Database?

You must to download MySQLConnection NET from here.

Then you need add MySql.Data.DLL to MSVisualStudio like this:

  1. Open menu project
  2. Add
  3. Reference
  4. Browse to C:\Program Files (x86)\MySQL\MySQL Connector Net 8.0.12\Assemblies\v4.5.2
  5. Add MySql.Data.dll

If you want to know more visit: enter link description here

To use in the code you must import the library:

using MySql.Data.MySqlClient;

An example with connectio to Mysql database (NO SSL MODE) by means of Click event:

using System;
using System.Windows;
using MySql.Data.MySqlClient;


namespace Deportes_WPF
{

public partial class Login : Window
{
    private MySqlConnection connection;
    private string server;
    private string database;
    private string user;
    private string password;
    private string port;
    private string connectionString;
    private string sslM;

    public Login()
    {
        InitializeComponent();

        server = "server_name";
        database = "database_name";
        user = "user_id";
        password = "password";
        port = "3306";
        sslM = "none";

        connectionString = String.Format("server={0};port={1};user id={2}; password={3}; database={4}; SslMode={5}", server, port, user, password, database, sslM);

        connection = new MySqlConnection(connectionString);
    }

    private void conexion()
    {
        try
        {
            connection.Open();

            MessageBox.Show("successful connection");

            connection.Close();
        }
        catch (MySqlException ex)
        {
            MessageBox.Show(ex.Message + connectionString);
        }
    }

    private void btn1_Click(object sender, RoutedEventArgs e)
    {
        conexion();
    }
  }

}

What is unexpected T_VARIABLE in PHP?

It could be some other line as well. PHP is not always that exact.

Probably you are just missing a semicolon on previous line.

How to reproduce this error, put this in a file called a.php:

<?php
  $a = 5
  $b = 7;        // Error happens here.
  print $b;
?>

Run it:

eric@dev ~ $ php a.php

PHP Parse error:  syntax error, unexpected T_VARIABLE in
/home/el/code/a.php on line 3

Explanation:

The PHP parser converts your program to a series of tokens. A T_VARIABLE is a Token of type VARIABLE. When the parser processes tokens, it tries to make sense of them, and throws errors if it receives a variable where none is allowed.

In the simple case above with variable $b, the parser tried to process this:

$a = 5 $b = 7;

The PHP parser looks at the $b after the 5 and says "that is unexpected".

PostgreSQL unnest() with element number

unnest2() as exercise

Older versions before pg v8.4 need a user-defined unnest(). We can adapt this old function to return elements with an index:

CREATE FUNCTION unnest2(anyarray)
  RETURNS setof record  AS
$BODY$
  SELECT $1[i], i
  FROM   generate_series(array_lower($1,1),
                         array_upper($1,1)) i;
$BODY$ LANGUAGE sql IMMUTABLE;

Google Maps JavaScript API RefererNotAllowedMapError

http://www.example.com/* has worked for me after days and days of trying.

Passing multiple values to a single PowerShell script parameter

One way to do it would be like this:

 param(
       [Parameter(Position=0)][String]$Vlan,
       [Parameter(ValueFromRemainingArguments=$true)][String[]]$Hosts
    ) ...

This would allow multiple hosts to be entered with spaces.

How to delete rows in tables that contain foreign keys to other tables

First, as a one-time data-scrubbing exercise, delete the orphaned rows e.g.

DELETE 
  FROM ReferencingTable 
 WHERE NOT EXISTS (
                   SELECT * 
                     FROM MainTable AS T1
                    WHERE T1.pk_col_1 = ReferencingTable.pk_col_1
                  );

Second, as a one-time schema-alteration exercise, add the ON DELETE CASCADE referential action to the foreign key on the referencing table e.g.

ALTER TABLE ReferencingTable DROP 
   CONSTRAINT fk__ReferencingTable__MainTable;

ALTER TABLE ReferencingTable ADD 
   CONSTRAINT fk__ReferencingTable__MainTable 
      FOREIGN KEY (pk_col_1)
      REFERENCES MainTable (pk_col_1)
      ON DELETE CASCADE;

Then, forevermore, rows in the referencing tables will automatically be deleted when their referenced row is deleted.

Dismissing a Presented View Controller

In addition to Michael Enriquez's answer, I can think of one other reason why this may be a good way to protect yourself from an undetermined state:

Say ViewControllerA presents ViewControllerB modally. But, since you may not have written the code for ViewControllerA you aren't aware of the lifecycle of ViewControllerA. It may dismiss 5 seconds (say) after presenting your view controller, ViewControllerB.

In this case, if you were simply using dismissViewController from ViewControllerB to dismiss itself, you would end up in an undefined state--perhaps not a crash or a black screen but an undefined state from your point of view.

If, instead, you were using the delegate pattern, you would be aware of the state of ViewControllerB and you can program for a case like the one I described.

run main class of Maven project

Try the maven-exec-plugin. From there:

mvn exec:java -Dexec.mainClass="com.example.Main"

This will run your class in the JVM. You can use -Dexec.args="arg0 arg1" to pass arguments.

If you're on Windows, apply quotes for exec.mainClass and exec.args:

mvn exec:java -D"exec.mainClass"="com.example.Main"

If you're doing this regularly, you can add the parameters into the pom.xml as well:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.2.1</version>
  <executions>
    <execution>
      <goals>
        <goal>java</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <mainClass>com.example.Main</mainClass>
    <arguments>
      <argument>foo</argument>
      <argument>bar</argument>
    </arguments>
  </configuration>
</plugin>

mvn command is not recognized as an internal or external command

I'm using Maven 3+ version. In my case everything was fine. But while adding the M2_HOME along with bin directory, I missed the '\' at the end. Previously it was like: %M2_HOME%\bin , which was throwing the mvn not recognizable error. After adding "\" at the end, mvn started working fine. I guess "\" acts as pointer to next folder. "%M2_HOME%\bin\" Should work, if you missed it.

Set colspan dynamically with jquery

I have adapted the script from Russ Cam (thank you, Russ Cam!) to my own needs: I needed to merge any columns that had the same value, not just empty cells.

This could be useful to someone else... Here is what I have come up with:

jQuery(document).ready(function() {

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

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

      if ((td.text() == strLookupText) || (td.text() == "")) {
        counter++;
        td.prev().attr('colSpan', '' + parseInt(counter + 1,10) + '').css({textAlign : 'center'});
        td.remove();
      }
      else {
        counter = 0;
      }

      // Sets the strLookupText variable to hold the current value. The next time in the loop the system will check the current value against the previous value.
      strLookupText = td.text();

    });

  });

});

Add number of days to a date

Keep in mind, the change of clock changes because of daylight saving time might give you some problems when only calculating the days.

Here's a little php function which takes care of that:

function add_days($date, $days) {
    $timeStamp = strtotime(date('Y-m-d',$date));
    $timeStamp+= 24 * 60 * 60 * $days;

    // ...clock change....
    if (date("I",$timeStamp) != date("I",$date)) {
        if (date("I",$date)=="1") { 
            // summer to winter, add an hour
            $timeStamp+= 60 * 60; 
        } else {
            // summer to winter, deduct an hour
            $timeStamp-= 60 * 60;           
        } // if
    } // if
    $cur_dat = mktime(0, 0, 0, 
                      date("n", $timeStamp), 
                      date("j", $timeStamp), 
                      date("Y", $timeStamp)
                     ); 
    return $cur_dat;
}

Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API

another way is to use certutil.exe save your username and password in a file e.g. in.txt as username:password

certutil -encode in.txt out.txt

Now you should be able to use auth value from out.txt

$headers = @{ Authorization = "Basic $((get-content out.txt)[1])" }
Invoke-WebRequest -Uri 'https://whatever' -Headers $Headers

Undefined or null for AngularJS

@STEVER's answer is satisfactory. However, I thought it may be useful to post a slightly different approach. I use a method called isValue which returns true for all values except null, undefined, NaN, and Infinity. Lumping in NaN with null and undefined is the real benefit of the function for me. Lumping Infinity in with null and undefined is more debatable, but frankly not that interesting for my code because I practically never use Infinity.

The following code is inspired by Y.Lang.isValue. Here is the source for Y.Lang.isValue.

/**
 * A convenience method for detecting a legitimate non-null value.
 * Returns false for null/undefined/NaN/Infinity, true for other values,
 * including 0/false/''
 * @method isValue
 * @static
 * @param o The item to test.
 * @return {boolean} true if it is not null/undefined/NaN || false.
 */
angular.isValue = function(val) {
  return !(val === null || !angular.isDefined(val) || (angular.isNumber(val) && !isFinite(val)));
};

Or as part of a factory

.factory('lang', function () {
  return {
    /**
     * A convenience method for detecting a legitimate non-null value.
     * Returns false for null/undefined/NaN/Infinity, true for other values,
     * including 0/false/''
     * @method isValue
     * @static
     * @param o The item to test.
     * @return {boolean} true if it is not null/undefined/NaN || false.
     */
    isValue: function(val) {
      return !(val === null || !angular.isDefined(val) || (angular.isNumber(val) && !isFinite(val)));
  };
})

curl: (35) SSL connect error

If updating cURL doesn't fix it, updating NSS should do the trick.

Getting value of selected item in list box as string

If you want to retrieve the display text of the item, use the GetItemText method:

string text = listBox1.GetItemText(listBox1.SelectedItem);

Python os.path.join on Windows

Consent with @georg-

I would say then why we need lame os.path.join- better to use str.join or unicode.join e.g.

sys.path.append('{0}'.join(os.path.dirname(__file__).split(os.path.sep)[0:-1]).format(os.path.sep))

Find rows that have the same value on a column in MySQL

Get the entire record as you want using the condition with inner select query.

SELECT *
FROM   member
WHERE  email IN (SELECT email
                 FROM   member
                 WHERE  login_id = [email protected]) 

How to go back to previous page if back button is pressed in WebView?

use this code to go back on page and when last page came then go out of activity

 @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent intent=new Intent(LiveImage.this,DashBoard.class);
        startActivity(intent);
    }

How to use the pass statement?

as the book said, I only ever use it as a temporary placeholder, ie,

# code that does something to to a variable, var
if var == 2000:
    pass
else:
    var += 1

and then later fill in the scenario where var == 2000

Where do I find the bashrc file on Mac?

On some system, instead of the .bashrc file, you can edit your profils' specific by editing:

sudo nano /etc/profile

What is the default Precision and Scale for a Number in Oracle?

Oracle stores numbers in the following way: 1 byte for power, 1 byte for the first significand digit (that is one before the separator), the rest for the other digits.

By digits here Oracle means centesimal digits (i. e. base 100)

SQL> INSERT INTO t_numtest VALUES (LPAD('9', 125, '9'))
  2  /

1 row inserted

SQL> INSERT INTO t_numtest VALUES (LPAD('7', 125, '7'))
  2  /

1 row inserted

SQL> INSERT INTO t_numtest VALUES (LPAD('9', 126, '9'))
  2  /

INSERT INTO t_numtest VALUES (LPAD('9', 126, '9'))

ORA-01426: numeric overflow

SQL> SELECT DUMP(num) FROM t_numtest;

DUMP(NUM)
--------------------------------------------------------------------------------
Typ=2 Len=2: 255,11
Typ=2 Len=21: 255,8,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,79

As we can see, the maximal number here is 7.(7) * 10^124, and he have 19 centesimal digits for precision, or 38 decimal digits.

How can I use UserDefaults in Swift?

I would say Anbu's answer perfectly fine but I had to add guard while fetching preferences to make my program doesn't fail

Here is the updated code snip in Swift 5

Storing data in UserDefaults

@IBAction func savePreferenceData(_ sender: Any) {
        print("Storing data..")
        UserDefaults.standard.set("RDC", forKey: "UserName") //String
        UserDefaults.standard.set("TestPass", forKey: "Passowrd")  //String
        UserDefaults.standard.set(21, forKey: "Age")  //Integer

    }

Fetching data from UserDefaults

    @IBAction func fetchPreferenceData(_ sender: Any) {
        print("Fetching data..")

        //added guard
        guard let uName = UserDefaults.standard.string(forKey: "UserName") else { return }
        print("User Name is :"+uName)
        print(UserDefaults.standard.integer(forKey: "Age"))
    }

Wildcards in a Windows hosts file

I could not find a prohibition in writing, but by convention, the Windows hosts file closely follows the UNIX hosts file, and you cannot put wildcard hostname references into that file.

If you read the man page, it says:

DESCRIPTION
     The hosts file contains information regarding the known hosts on the net-
     work.  For each host a single line should be present with the following
     information:

           Internet address
           Official host name
           Aliases

Although it does say,

     Host names may contain any printable character other than a field delim-
     iter, newline, or comment character.

that is not true from a practical level.

Basically, the code that looks at the /etc/hosts file does not support a wildcard entry.

The workaround is to create all the entries in advance, maybe use a script to put a couple hundred entries at once.

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

_x000D_
_x000D_
<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_
    </datalist>
_x000D_
_x000D_
_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

How to stop line breaking in vim

You may find set lbr useful; with set wrap on this will wrap but only cutting the line on whitespace and not in the middle of a word.

e.g.

without lbr the li
ne can be split on
a word

and

with lbr on the
line will be
split on 
whitespace only

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

you need to add jar file in your build path..

commons-dbcp-1.1-RC2.jar

or any version of that..!!!!

ADDED : also make sure you have commons-pool-1.1.jar too in your build path.

ADDED: sorry saw complete list of jar late... may be version clashes might be there.. better check out..!!! just an assumption.

How do you serialize a model instance in Django?

It sounds like what you're asking about involves serializing the data structure of a Django model instance for interoperability. The other posters are correct: if you wanted the serialized form to be used with a python application that can query the database via Django's api, then you would wan to serialize a queryset with one object. If, on the other hand, what you need is a way to re-inflate the model instance somewhere else without touching the database or without using Django, then you have a little bit of work to do.

Here's what I do:

First, I use demjson for the conversion. It happened to be what I found first, but it might not be the best. My implementation depends on one of its features, but there should be similar ways with other converters.

Second, implement a json_equivalent method on all models that you might need serialized. This is a magic method for demjson, but it's probably something you're going to want to think about no matter what implementation you choose. The idea is that you return an object that is directly convertible to json (i.e. an array or dictionary). If you really want to do this automatically:

def json_equivalent(self):
    dictionary = {}
    for field in self._meta.get_all_field_names()
        dictionary[field] = self.__getattribute__(field)
    return dictionary

This will not be helpful to you unless you have a completely flat data structure (no ForeignKeys, only numbers and strings in the database, etc.). Otherwise, you should seriously think about the right way to implement this method.

Third, call demjson.JSON.encode(instance) and you have what you want.

Compute mean and standard deviation by group for multiple variables in a data.frame

There are a few different ways to go about it. reshape2 is a helpful package. Personally, I like using data.table

Below is a step-by-step

If myDF is your data.frame:

library(data.table)
DT <- data.table(myDF)

DT

# this will get you your mean and SD's for each column
DT[, sapply(.SD, function(x) list(mean=mean(x), sd=sd(x)))]

# adding a `by` argument will give you the groupings
DT[, sapply(.SD, function(x) list(mean=mean(x), sd=sd(x))), by=ID]

# If you would like to round the values: 
DT[, sapply(.SD, function(x) list(mean=round(mean(x), 3), sd=round(sd(x), 3))), by=ID]

# If we want to add names to the columns 
wide <- setnames(DT[, sapply(.SD, function(x) list(mean=round(mean(x), 3), sd=round(sd(x), 3))), by=ID], c("ID", sapply(names(DT)[-1], paste0, c(".men", ".SD"))))

wide

   ID Obs.1.men Obs.1.SD Obs.2.men Obs.2.SD Obs.3.men Obs.3.SD
1:  1    35.333    8.021    36.333   10.214      33.0    9.644
2:  2    29.750    3.594    32.250    4.193      30.5    5.916
3:  3    41.500    4.950    43.500    4.950      39.0    4.243

Also, this may or may not be helpful

> DT[, sapply(.SD, summary), .SDcols=names(DT)[-1]]
        Obs.1 Obs.2 Obs.3
Min.    25.00 28.00 22.00
1st Qu. 29.00 31.00 27.00
Median  33.00 32.00 36.00
Mean    34.22 36.11 33.22
3rd Qu. 38.00 40.00 37.00
Max.    45.00 48.00 42.00

Select distinct rows from datatable in Linq

We can get the distinct similar to the example shown below

 //example
           var  distinctValues =  DetailedBreakDown_Table.AsEnumerable().Select(r => new
            {
                InvestmentVehicleID = r.Field<string>("InvestmentVehicleID"),
                Universe = r.Field<string>("Universe"),
                AsOfDate = _imqDate,
                Ticker = "",
                Cusip = "",
                PortfolioDate = r.Field<DateTime>("PortfolioDate")

            } ).Distinct();

How can I disable a button on a jQuery UI dialog?

This worked for me --

$("#dialog-confirm").html('Do you want to permanently delete this?');
$( "#dialog-confirm" ).dialog({
    resizable: false,
    title:'Confirm',
    modal: true,
    buttons: {
        Cancel: function() {
            $( this ).dialog( "close" );
        },
        OK:function(){
            $('#loading').show();
            $.ajax({
                    type:'post',
                    url:'ajax.php',
                    cache:false,
                    data:{action:'do_something'},
                    async:true,
                    success:function(data){
                        var resp = JSON.parse(data);
                        $("#loading").hide();
                        $("#dialog-confirm").html(resp.msg);
                        $( "#dialog-confirm" ).dialog({
                                resizable: false,
                                title:'Confirm',
                                modal: true,
                                buttons: {
                                    Close: function() {
                                        $( this ).dialog( "close" );
                                    }
                                }
                        });
                    }
                });
        }
    }
}); 

"The certificate chain was issued by an authority that is not trusted" when connecting DB in VM Role from Azure website

The same can be achieved from ssms client itself. Just open the ssms, insert the server name and then from options under heading connection properties make sure Trust server certificate is checked.

What's the name for hyphen-separated case?

I've always known it as kebab-case.

On a funny note, I've heard people call it a SCREAM-KEBAB when all the letters are capitalized.

Kebab Case Warning

I've always liked kebab-case as it seems the most readable when you need whitespace. However, some programs interpret the dash as a minus sign, and it can cause problems as what you think is a name turns into a subtraction operation.

first-second  // first minus second?
ten-2 // ten minus two?

Also, some frameworks parse dashes in kebab cased property. For example, GitHub Pages uses Jekyll, and Jekyll parses any dashes it finds in an md file. For example, a file named 2020-1-2-homepage.md on GitHub Pages gets put into a folder structured as \2020\1\2\homepage.html when the site is compiled.

Snake_case vs kebab-case

A safer alternative to kebab-case is snake_case, or SCREAMING_SNAKE_CASE, as underscores cause less confusion when compared to a minus sign.

How to install a Notepad++ plugin offline?

My frustration in being unable to get a plugin for Notepad++ to work came from not realizing that the DLL for the plugin had to be installed directly in the C:\Program Files (x86)\Notepad++\plugins directory, and NOT into a subfolder below that, named for the plugin.

I was misled because every OTHER plugin that comes with the clean installation of Notepad++ IS installed in its own subfolder under \plugins.

\plugins
   + DSpellCheck
   + MIME Tools
   + Converter (etc.)

I tried that with the plugin I was attempting to install (autosave), and just couldn't get it to work. But then thanks to an answer from Steve Chambers above, I tried putting the DLL directly into the \plugins folder and PRESTO! It Works.

Hope this helps save someone else similar frustrations!

NHibernate.MappingException: No persister for: XYZ

Make sure you have called the CreateCriteria(typeof(DomainObjectType)) method on Session for the domain object which you intent to fetch from DB.

Check if any type of files exist in a directory using BATCH script

For files in a directory, you can use things like:

if exist *.csv echo "csv file found"

or

if not exist *.csv goto nofile

Correct way to write loops for promise.

I'd make something like this:

var request = []
while(count<10){
   request.push(db.getUser(email).then(function(res) { return res; }));
   count++
};

Promise.all(request).then((dataAll)=>{
  for (var i = 0; i < dataAll.length; i++) {

      logger.log(dataAll[i]); 
  }  
});

in this way, dataAll is an ordered array of all element to log. And log operation will perform when all promises are done.