Programs & Examples On #Moviecliploader

Redirecting from HTTP to HTTPS with PHP

On my AWS beanstalk server, I don't see $_SERVER['HTTPS'] variable. I do see $_SERVER['HTTP_X_FORWARDED_PROTO'] which can be either 'http' or 'https' so if you're hosting on AWS, use this:

if ($_SERVER['HTTP_HOST'] != 'localhost' and $_SERVER['HTTP_X_FORWARDED_PROTO'] != "https") {
    $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $location);
    exit;
}

ESLint not working in VS Code?

Go to your settings.json file, add the following and, fix the eslint.nodepath. Tailor it to your own preferences.

 // PERSONAL
  "editor.codeActionsOnSaveTimeout": 2000,
  "editor.codeActionsOnSave": {
    "source.fixAll": true
  },
  "editor.fontSize": 16,
  "editor.formatOnSave": true,
  "explorer.confirmDragAndDrop": true,
  "editor.tabSize": 2,
  "eslint.codeAction.showDocumentation": {
    "enable": true
  },
  "eslint.nodePath": "C:\\{path}",
  "eslint.workingDirectories": ["./backend", "./frontend"],

Can I start the iPhone simulator without "Build and Run"?

This is an older question, but if you simply want to run the simulator from the Xcode 4.5 UI, you can do: Xcode > Open Developer Tool > iOS Simulator.

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

#use return convertView;

Code:

public View getView(final int position, View convertView, ViewGroup parent) {

    //convertView = null;

    if (convertView == null) {

        LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        convertView = mInflater.inflate(R.layout.list_item, null);     

        TextView tv = (TextView) convertView.findViewById(R.id.name);
        Button rm_btn = (Button) convertView.findViewById(R.id.rm_btn);

        Model m = modelList.get(position);
        tv.setText(m.getName());

        // click listener for remove button  ??????????
        rm_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modelList.remove(position);
                notifyDataSetChanged();
            }
        });
    }

    ///#use    return convertView;
    return convertView;
}

Android SDK manager won't open

http://quantumsupport.blogspot.com/2011/03/android-sdk-managerexe-wont-start.html

Create a new user account, either re-install or just start android.bat and it should work did for me

List attributes of an object

You can use dir(your_object) to get the attributes and getattr(your_object, your_object_attr) to get the values

usage :

for att in dir(your_object):
    print (att, getattr(your_object,att))

This is particularly useful if your object have no __dict__. If that is not the case you can try var(your_object) also

How do I detect what .NET Framework versions and service packs are installed?

For a 64-bit OS, the path would be:

HKEY_LOCAL_MACHINE\SOFTWARE\wow6432Node\Microsoft\NET Framework Setup\NDP\

Is there a jQuery unfocus method?

$('#textarea').blur()

Documentation at: http://api.jquery.com/blur/

minimum double value in C/C++

Floating point numbers (IEEE 754) are symmetrical, so if you can represent the greatest value (DBL_MAX or numeric_limits<double>::max()), just prepend a minus sign.

And then is the cool way:

double f;
(*((long long*)&f))= ~(1LL<<52);

VB.net: Date without time

Either use one of the standard date and time format strings which only specifies the date (e.g. "D" or "d"), or a custom date and time format string which only uses the date parts (e.g. "yyyy/MM/dd").

Minimum and maximum date

To augment T.J.'s answer, exceeding the min/max values generates an Invalid Date.

_x000D_
_x000D_
let maxDate = new Date(8640000000000000);_x000D_
let minDate = new Date(-8640000000000000);_x000D_
_x000D_
console.log(new Date(maxDate.getTime()).toString());_x000D_
console.log(new Date(maxDate.getTime() - 1).toString());_x000D_
console.log(new Date(maxDate.getTime() + 1).toString()); // Invalid Date_x000D_
_x000D_
console.log(new Date(minDate.getTime()).toString());_x000D_
console.log(new Date(minDate.getTime() + 1).toString());_x000D_
console.log(new Date(minDate.getTime() - 1).toString()); // Invalid Date
_x000D_
_x000D_
_x000D_

How to cast an Object to an int

For Example Object variable; hastaId

Object hastaId = session.getAttribute("hastaID");

For Example Cast an Object to an int,hastaID

int hastaID=Integer.parseInt(String.valueOf(hastaId));

Check if a key exists inside a json object

There's several ways to do it, depending on your intent.

thisSession.hasOwnProperty('merchant_id'); will tell you if thisSession has that key itself (i.e. not something it inherits from elsewhere)

"merchant_id" in thisSession will tell you if thisSession has the key at all, regardless of where it got it.

thisSession["merchant_id"] will return false if the key does not exist, or if its value evaluates to false for any reason (e.g. if it's a literal false or the integer 0 and so on).

Pandas rename column by position?

try this

df.rename(columns={ df.columns[1]: "your value" }, inplace = True)

android get all contacts

This is the Method to get contact list Name and Number

 private void getAllContacts() {
    ContentResolver contentResolver = getContentResolver();
    Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
    if (cursor.getCount() > 0) {
        while (cursor.moveToNext()) {

            int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
            if (hasPhoneNumber > 0) {
                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                Cursor phoneCursor = contentResolver.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id},
                        null);
                if (phoneCursor != null) {
                    if (phoneCursor.moveToNext()) {
                        String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

   //At here You can add phoneNUmber and Name to you listView ,ModelClass,Recyclerview
                        phoneCursor.close();
                    }


                }
            }
        }
    }
}

Why do I keep getting Delete 'cr' [prettier/prettier]?

In the root open the .editorconfig file and change:

end_of_line = lf

to

end_of_line = auto

This should fix it for new files.

How do you replace double quotes with a blank space in Java?

Use String#replace().

To replace them with spaces (as per your question title):

System.out.println("I don't like these \"double\" quotes".replace("\"", " "));

The above can also be done with characters:

System.out.println("I don't like these \"double\" quotes".replace('"', ' '));

To remove them (as per your example):

System.out.println("I don't like these \"double\" quotes".replace("\"", ""));

Simple check for SELECT query empty result

try:

SELECT * FROM service s WHERE s.service_id = ?;

IF @@ROWCOUNT=0
BEGIN
    PRINT 'no rows!'
END

Apache - MySQL Service detected with wrong path. / Ports already in use

about this specific issue:

12:35:23  [mysql]   Found Path: "C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqld" --defaults-file="C:\Program Files\MySQL\MySQL Server 5.5\my.ini" MySQL
12:35:23  [mysql]   Expected Path: c:\xampp\mysql\bin\mysqld.exe --defaults-file=c:\xampp\mysql\bin\my.ini mysql

notice that .exe is missing from 1st row at the end of mysqld.

To fix this, start regedit.exe and change HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\mysql ImagePath by adding the .exe extension.

Restart xampp control panel and this error should not show up.

Get and set position with jQuery .offset()

Here is an option. This is just for the x coordinates.

var div1Pos = $("#div1").offset();
var div1X = div1Pos.left;
$('#div2').css({left: div1X});

How can I add new item to the String array?

From arrays

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.

enter image description here

So in the case of a String array, once you create it with some length, you can't modify it, but you can add elements until you fill it.

String[] arr = new String[10]; // 10 is the length of the array.
arr[0] = "kk";
arr[1] = "pp";
...

So if your requirement is to add many objects, it's recommended that you use Lists like:

List<String> a = new ArrayList<String>();
a.add("kk");
a.add("pp"); 

How can I use Google's Roboto font on a website?

It's actually quite simple. Go to the font on Google's website, and add its link to the head of every page you want to include the font.

How to remove Firefox's dotted outline on BUTTONS as well as links?

Tested on Firefox 46 and Chrome 49 using this code.

input:focus, textarea:focus, button:focus {
    outline: none !important;
}

Before (white dots are visible )

input with white dots

After ( White dots are invisible ) enter image description here

If you want to apply only on few input fields, buttons etc. Use the more specific code.

input[type=text] {
  outline: none !important;
}

Happy Coding!!

Getting XML Node text value with Java DOM

I'd print out the result of an2.getNodeName() as well for debugging purposes. My guess is that your tree crawling code isn't crawling to the nodes that you think it is. That suspicion is enhanced by the lack of checking for node names in your code.

Other than that, the javadoc for Node defines "getNodeValue()" to return null for Nodes of type Element. Therefore, you really should be using getTextContent(). I'm not sure why that wouldn't give you the text that you want.

Perhaps iterate the children of your tag node and see what types are there?

Tried this code and it works for me:

String xml = "<add job=\"351\">\n" +
             "    <tag>foobar</tag>\n" +
             "    <tag>foobar2</tag>\n" +
             "</add>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
Document doc = db.parse(bis);
Node n = doc.getFirstChild();
NodeList nl = n.getChildNodes();
Node an,an2;

for (int i=0; i < nl.getLength(); i++) {
    an = nl.item(i);
    if(an.getNodeType()==Node.ELEMENT_NODE) {
        NodeList nl2 = an.getChildNodes();

        for(int i2=0; i2<nl2.getLength(); i2++) {
            an2 = nl2.item(i2);
            // DEBUG PRINTS
            System.out.println(an2.getNodeName() + ": type (" + an2.getNodeType() + "):");
            if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getTextContent());
            if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getNodeValue());
            System.out.println(an2.getTextContent());
            System.out.println(an2.getNodeValue());
        }
    }
}

Output was:

#text: type (3): foobar foobar
#text: type (3): foobar2 foobar2

Apply style to parent if it has child with css

It's not possible with CSS3. There is a proposed CSS4 selector, $, to do just that, which could look like this (Selecting the li element):

ul $li ul.sub { ... }

See the list of CSS4 Selectors here.

As an alternative, with jQuery, a one-liner you could make use of would be this:

$('ul li:has(ul.sub)').addClass('has_sub');

You could then go ahead and style the li.has_sub in your CSS.

Regex to get string between curly braces

If your string will always be of that format, a regex is overkill:

>>> var g='{getThis}';
>>> g.substring(1,g.length-1)
"getThis"

substring(1 means to start one character in (just past the first {) and ,g.length-1) means to take characters until (but not including) the character at the string length minus one. This works because the position is zero-based, i.e. g.length-1 is the last position.

For readers other than the original poster: If it has to be a regex, use /{([^}]*)}/ if you want to allow empty strings, or /{([^}]+)}/ if you want to only match when there is at least one character between the curly braces. Breakdown:

  • /: start the regex pattern
    • {: a literal curly brace
      • (: start capturing
        • [: start defining a class of characters to capture
          • ^}: "anything other than }"
        • ]: OK, that's our whole class definition
        • *: any number of characters matching that class we just defined
      • ): done capturing
    • }: a literal curly brace must immediately follow what we captured
  • /: end the regex pattern

Adding attribute in jQuery

$('#someid').attr('disabled', 'true');

Find out which remote branch a local branch is tracking

The local branches and their remotes.

git branch -vv 

All branches and tracking remotes.

git branch -a -vv

See where the local branches are explicitly configured for push and pull.

git remote show {remote_name}

How do I search for files in Visual Studio Code?

For windows. if Ctrl+p doesn't always work use Ctrl+shift+n instead.

How can I play sound in Java?

For playing sound in java, you can refer to the following code.

import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
import javax.swing.*;

// To play sound using Clip, the process need to be alive.
// Hence, we use a Swing application.
public class SoundClipTest extends JFrame {

   public SoundClipTest() {
      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      this.setTitle("Test Sound Clip");
      this.setSize(300, 200);
      this.setVisible(true);

      try {
         // Open an audio input stream.
         URL url = this.getClass().getClassLoader().getResource("gameover.wav");
         AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
         // Get a sound clip resource.
         Clip clip = AudioSystem.getClip();
         // Open audio clip and load samples from the audio input stream.
         clip.open(audioIn);
         clip.start();
      } catch (UnsupportedAudioFileException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      } catch (LineUnavailableException e) {
         e.printStackTrace();
      }
   }

   public static void main(String[] args) {
      new SoundClipTest();
   }
}

React eslint error missing in props validation

Issue: 'id1' is missing in props validation, eslintreact/prop-types

<div id={props.id1} >
    ...
</div>

Below solution worked, in a function component:

let { id1 } = props;

<div id={id1} >
    ...
</div>

Hope that helps.

How do I add comments to package.json for npm install?

You can always abuse the fact that duplicated keys are overwritten. This is what I just wrote:

"dependencies": {
  "grunt": "...",
  "grunt-cli": "...",

  "api-easy": "# Here is the pull request: https://github.com/...",
  "api-easy": "git://..."

  "grunt-vows": "...",
  "vows": "..."
}

However, it is not clear whether JSON allows duplicated keys (see Does JSON syntax allow duplicate keys in an object?. It seems to work with npm, so I take the risk.

The recommened hack is to use "//" keys (from the nodejs mailing list). When I tested it, it did not work with "dependencies" sections, though. Also, the example in the post uses multiple "//" keys, which implies that npm does not reject JSON files with duplicated keys. In other words, the hack above should always be fine.

Update: One annoying disadvantage of the duplicated key hack is that npm install --save silently eliminates all duplicates. Unfortunately, it is very easy to overlook it and your well-intentioned comments are gone.

The "//" hack is still the safest as it seems. However, multi-line comments will be removed by npm install --save, too.

VueJs get url query

Current route properties are present in this.$route, this.$router is the instance of router object which gives the configuration of the router. You can get the current route query using this.$route.query

What is the difference between char, nchar, varchar, and nvarchar in SQL Server?

  • nchar is fixed-length and can hold unicode characters. it uses two bytes storage per character.

  • varchar is of variable length and cannot hold unicode characters. it uses one byte storage per character.

Xcode - How to fix 'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X" error?

To add to this epic saga of a thread...

My view controller had an attribution above it: @objc(TheNameOfMyViewController)

This made all the Outlets crash with "not key value compliant" error for each Outlet. This was only an issue on IOS12 and below. It worked fine on iOS 13.

Removing that modifier fixed this problem. All the outlets are working fine now.

LINQ Group By into a Dictionary Object

For @atari2600, this is what the answer would look like using ToLookup in lambda syntax:

var x = listOfCustomObjects
    .GroupBy(o => o.PropertyName)
    .ToLookup(customObject => customObject);

Basically, it takes the IGrouping and materializes it for you into a dictionary of lists, with the values of PropertyName as the key.

MySQL select where column is not empty

select phone, phone2 from jewishyellow.users 
where phone like '813%' and phone2 is not null

E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation

I faced the same issue:

E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation

I resolved by using the following commands:

apt-get update
apt-get install gnupg

Error "package android.support.v7.app does not exist"

If you are using SDK 28 or higher, you need to migrate to AndroidX library.

With Android Studio 3.2 and higher, you can migrate an existing project to AndroidX by selecting Refactor > Migrate to AndroidX from the menu bar.

Error with multiple definitions of function

This problem happens because you are calling fun.cpp instead of fun.hpp. So c++ compiler finds func.cpp definition twice and throws this error.

Change line 3 of your main.cpp file, from #include "fun.cpp" to #include "fun.hpp" .

How to build query string with Javascript

querystring can help.

So, you can

const querystring = require('querystring')

url += '?' + querystring.stringify(parameters)

Why is the GETDATE() an invalid identifier

Use ORACLE equivalent of getdate() which is sysdate . Read about here. Getdate() belongs to SQL Server , will not work on Oracle.

Other option is current_date

How to escape comma and double quote at same time for CSV file?

"cell one","cell "" two","cell "" ,three"

Save this to csv file and see the results, so double quote is used to escape itself

Important Note

"cell one","cell "" two", "cell "" ,three"

will give you a different result because there is a space after the comma, and that will be treated as "

updating table rows in postgres using subquery

There are many ways to update the rows.

When it comes to UPDATE the rows using subqueries, you can use any of these approaches.

  1. Approach-1 [Using direct table reference]
UPDATE
  <table1>
SET
  customer=<table2>.customer,
  address=<table2>.address,
  partn=<table2>.partn
FROM
  <table2>
WHERE
  <table1>.address_id=<table2>.address_i;

Explanation: table1 is the table which we want to update, table2 is the table, from which we'll get the value to be replaced/updated. We are using FROM clause, to fetch the table2's data. WHERE clause will help to set the proper data mapping.

  1. Approach-2 [Using SubQueries]
UPDATE
  <table1>
SET
  customer=subquery.customer,
  address=subquery.address,
  partn=subquery.partn
FROM
  (
    SELECT
      address_id, customer, address, partn
    FROM  /* big hairy SQL */ ...
  ) AS subquery
WHERE
  dummy.address_id=subquery.address_id;

Explanation: Here we are using subquerie inside the FROM clause, and giving an alias to it. So that it will act like the table.

  1. Approach-3 [Using multiple Joined tables]
UPDATE
  <table1>
SET
  customer=<table2>.customer,
  address=<table2>.address,
  partn=<table2>.partn
FROM
  <table2> as t2
  JOIN <table3> as t3
  ON
    t2.id = t3.id
WHERE
  <table1>.address_id=<table2>.address_i;

Explanation: Sometimes we face the situation in that table join is so important to get proper data for the update. To do so, Postgres allows us to Join multiple tables inside the FROM clause.

  1. Approach-4 [Using WITH statement]

    • 4.1 [Using simple query]
WITH subquery AS (
    SELECT
      address_id,
      customer,
      address,
      partn
    FROM
      <table1>;
)
UPDATE <table-X>
SET customer = subquery.customer,
    address  = subquery.address,
    partn    = subquery.partn
FROM subquery
WHERE <table-X>.address_id = subquery.address_id;
  • 4.2 [Using query with complex JOIN]
WITH subquery AS (
    SELECT address_id, customer, address, partn
    FROM
      <table1> as t1
    JOIN
      <table2> as t2
    ON
      t1.id = t2.id;
    -- You can build as COMPLEX as this query as per your need.
)
UPDATE <table-X>
SET customer = subquery.customer,
    address  = subquery.address,
    partn    = subquery.partn
FROM subquery
WHERE <table-X>.address_id = subquery.address_id;

Explanation: From Postgres 9.1, this(WITH) concept has been introduces. Using that We can make any complex queries and generate desire result. Here we are using this approach to update the table.

I hope, this would be helpful.

When should I use a trailing slash in my URL?

Who says a file name needs an extension?? take a look on a *nix machine sometime...
I agree with your friend, no trailing slash.

What do I use for a max-heap implementation in Python?

To elaborate on https://stackoverflow.com/a/59311063/1328979, here is a fully documented, annotated and tested Python 3 implementation for the general case.

from __future__ import annotations  # To allow "MinHeap.push -> MinHeap:"
from typing import Generic, List, Optional, TypeVar
from heapq import heapify, heappop, heappush, heapreplace


T = TypeVar('T')


class MinHeap(Generic[T]):
    '''
    MinHeap provides a nicer API around heapq's functionality.
    As it is a minimum heap, the first element of the heap is always the
    smallest.
    >>> h = MinHeap([3, 1, 4, 2])
    >>> h[0]
    1
    >>> h.peek()
    1
    >>> h.push(5)  # N.B.: the array isn't always fully sorted.
    [1, 2, 4, 3, 5]
    >>> h.pop()
    1
    >>> h.pop()
    2
    >>> h.pop()
    3
    >>> h.push(3).push(2)
    [2, 3, 4, 5]
    >>> h.replace(1)
    2
    >>> h
    [1, 3, 4, 5]
    '''
    def __init__(self, array: Optional[List[T]] = None):
        if array is None:
            array = []
        heapify(array)
        self.h = array
    def push(self, x: T) -> MinHeap:
        heappush(self.h, x)
        return self  # To allow chaining operations.
    def peek(self) -> T:
        return self.h[0]
    def pop(self) -> T:
        return heappop(self.h)
    def replace(self, x: T) -> T:
        return heapreplace(self.h, x)
    def __getitem__(self, i) -> T:
        return self.h[i]
    def __len__(self) -> int:
        return len(self.h)
    def __str__(self) -> str:
        return str(self.h)
    def __repr__(self) -> str:
        return str(self.h)


class Reverse(Generic[T]):
    '''
    Wrap around the provided object, reversing the comparison operators.
    >>> 1 < 2
    True
    >>> Reverse(1) < Reverse(2)
    False
    >>> Reverse(2) < Reverse(1)
    True
    >>> Reverse(1) <= Reverse(2)
    False
    >>> Reverse(2) <= Reverse(1)
    True
    >>> Reverse(2) <= Reverse(2)
    True
    >>> Reverse(1) == Reverse(1)
    True
    >>> Reverse(2) > Reverse(1)
    False
    >>> Reverse(1) > Reverse(2)
    True
    >>> Reverse(2) >= Reverse(1)
    False
    >>> Reverse(1) >= Reverse(2)
    True
    >>> Reverse(1)
    1
    '''
    def __init__(self, x: T) -> None:
        self.x = x
    def __lt__(self, other: Reverse) -> bool:
        return other.x.__lt__(self.x)
    def __le__(self, other: Reverse) -> bool:
        return other.x.__le__(self.x)
    def __eq__(self, other) -> bool:
        return self.x == other.x
    def __ne__(self, other: Reverse) -> bool:
        return other.x.__ne__(self.x)
    def __ge__(self, other: Reverse) -> bool:
        return other.x.__ge__(self.x)
    def __gt__(self, other: Reverse) -> bool:
        return other.x.__gt__(self.x)
    def __str__(self):
        return str(self.x)
    def __repr__(self):
        return str(self.x)


class MaxHeap(MinHeap):
    '''
    MaxHeap provides an implement of a maximum-heap, as heapq does not provide
    it. As it is a maximum heap, the first element of the heap is always the
    largest. It achieves this by wrapping around elements with Reverse,
    which reverses the comparison operations used by heapq.
    >>> h = MaxHeap([3, 1, 4, 2])
    >>> h[0]
    4
    >>> h.peek()
    4
    >>> h.push(5)  # N.B.: the array isn't always fully sorted.
    [5, 4, 3, 1, 2]
    >>> h.pop()
    5
    >>> h.pop()
    4
    >>> h.pop()
    3
    >>> h.pop()
    2
    >>> h.push(3).push(2).push(4)
    [4, 3, 2, 1]
    >>> h.replace(1)
    4
    >>> h
    [3, 1, 2, 1]
    '''
    def __init__(self, array: Optional[List[T]] = None):
        if array is not None:
            array = [Reverse(x) for x in array]  # Wrap with Reverse.
        super().__init__(array)
    def push(self, x: T) -> MaxHeap:
        super().push(Reverse(x))
        return self
    def peek(self) -> T:
        return super().peek().x
    def pop(self) -> T:
        return super().pop().x
    def replace(self, x: T) -> T:
        return super().replace(Reverse(x)).x


if __name__ == '__main__':
    import doctest
    doctest.testmod()

https://gist.github.com/marccarre/577a55850998da02af3d4b7b98152cf4

How to wait 5 seconds with jQuery?

I ran across this question and I thought I'd provide an update on this topic. jQuery (v1.5+) includes a Deferred model, which (despite not adhering to the Promises/A spec until jQuery 3) is generally regarded as being a clearer way to approach many asynchronous problems. Implementing a $.wait() method using this approach is particularly readable I believe:

$.wait = function(ms) {
    var defer = $.Deferred();
    setTimeout(function() { defer.resolve(); }, ms);
    return defer;
};

And here's how you can use it:

$.wait(5000).then(disco);

However if, after pausing, you only wish to perform actions on a single jQuery selection, then you should be using jQuery's native .delay() which I believe also uses Deferred's under the hood:

$(".my-element").delay(5000).fadeIn();

iPhone Navigation Bar Title text color

This is one of those things that are missing. Your best bet is to create your own custom Navigation Bar, add a text box, and manipulate the color that way.

What does this square bracket and parenthesis bracket notation mean [first1,last1)?

The concept of interval notation comes up in both Mathematics and Computer Science. The Mathematical notation [, ], (, ) denotes the domain (or range) of an interval.

  • The brackets [ and ] means:

    1. The number is included,
    2. This side of the interval is closed,
  • The parenthesis ( and ) means:

    1. The number is excluded,
    2. This side of the interval is open.

An interval with mixed states is called "half-open".

For example, the range of consecutive integers from 1 .. 10 (inclusive) would be notated as such:

  • [1,10]

Notice how the word inclusive was used. If we want to exclude the end point but "cover" the same range we need to move the end-point:

  • [1,11)

For both left and right edges of the interval there are actually 4 permutations:

(1,10) =   2,3,4,5,6,7,8,9       Set has  8 elements
(1,10] =   2,3,4,5,6,7,8,9,10    Set has  9 elements
[1,10) = 1,2,3,4,5,6,7,8,9       Set has  9 elements
[1,10] = 1,2,3,4,5,6,7,8,9,10    Set has 10 elements

How does this relate to Mathematics and Computer Science?

Array indexes tend to use a different offset depending on which field are you in:

  • Mathematics tends to be one-based.
  • Certain programming languages tends to be zero-based, such as C, C++, Javascript, Python, while other languages such as Mathematica, Fortran, Pascal are one-based.

These differences can lead to subtle fence post errors, aka, off-by-one bugs when implementing Mathematical algorithms such as for-loops.

Integers

If we have a set or array, say of the first few primes [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ], Mathematicians would refer to the first element as the 1st absolute element. i.e. Using subscript notation to denote the index:

  • a1 = 2
  • a2 = 3
  • :
  • a10 = 29

Some programming languages, in contradistinction, would refer to the first element as the zero'th relative element.

  • a[0] = 2
  • a[1] = 3
  • :
  • a[9] = 29

Since the array indexes are in the range [0,N-1] then for clarity purposes it would be "nice" to keep the same numerical value for the range 0 .. N instead of adding textual noise such as a -1 bias.

For example, in C or JavaScript, to iterate over an array of N elements a programmer would write the common idiom of i = 0, i < N with the interval [0,N) instead of the slightly more verbose [0,N-1]:

_x000D_
_x000D_
function main() {_x000D_
    var output = "";_x000D_
    var a = [ 2, 3, 5, 7,  11, 13, 17, 19, 23, 29 ];_x000D_
    for( var i = 0; i < 10; i++ ) // [0,10)_x000D_
       output += "[" + i + "]: " + a[i] + "\n";_x000D_
_x000D_
    if (typeof window === 'undefined') // Node command line_x000D_
        console.log( output )_x000D_
    else_x000D_
        document.getElementById('output1').innerHTML = output;_x000D_
}
_x000D_
 <html>_x000D_
     <body onload="main();">_x000D_
         <pre id="output1"></pre>_x000D_
     </body>_x000D_
 </html>
_x000D_
_x000D_
_x000D_

Mathematicians, since they start counting at 1, would instead use the i = 1, i <= N nomenclature but now we need to correct the array offset in a zero-based language.

e.g.

_x000D_
_x000D_
function main() {_x000D_
    var output = "";_x000D_
    var a = [ 2, 3, 5, 7,  11, 13, 17, 19, 23, 29 ];_x000D_
    for( var i = 1; i <= 10; i++ ) // [1,10]_x000D_
       output += "[" + i + "]: " + a[i-1] + "\n";_x000D_
_x000D_
    if (typeof window === 'undefined') // Node command line_x000D_
        console.log( output )_x000D_
    else_x000D_
        document.getElementById( "output2" ).innerHTML = output;_x000D_
}
_x000D_
<html>_x000D_
    <body onload="main()";>_x000D_
        <pre id="output2"></pre>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Aside:

In programming languages that are 0-based you might need a kludge of a dummy zero'th element to use a Mathematical 1-based algorithm. e.g. Python Index Start

Floating-Point

Interval notation is also important for floating-point numbers to avoid subtle bugs.

When dealing with floating-point numbers especially in Computer Graphics (color conversion, computational geometry, animation easing/blending, etc.) often times normalized numbers are used. That is, numbers between 0.0 and 1.0.

It is important to know the edge cases if the endpoints are inclusive or exclusive:

  • (0,1) = 1e-M .. 0.999...
  • (0,1] = 1e-M .. 1.0
  • [0,1) = 0.0 .. 0.999...
  • [0,1] = 0.0 .. 1.0

Where M is some machine epsilon. This is why you might sometimes see const float EPSILON = 1e-# idiom in C code (such as 1e-6) for a 32-bit floating point number. This SO question Does EPSILON guarantee anything? has some preliminary details. For a more comprehensive answer see FLT_EPSILON and David Goldberg's What Every Computer Scientist Should Know About Floating-Point Arithmetic

Some implementations of a random number generator, random() may produce values in the range 0.0 .. 0.999... instead of the more convenient 0.0 .. 1.0. Proper comments in the code will document this as [0.0,1.0) or [0.0,1.0] so there is no ambiguity as to the usage.

Example:

  • You want to generate random() colors. You convert three floating-point values to unsigned 8-bit values to generate a 24-bit pixel with red, green, and blue channels respectively. Depending on the interval output by random() you may end up with near-white (254,254,254) or white (255,255,255).
     +--------+-----+
     |random()|Byte |
     |--------|-----|
     |0.999...| 254 | <-- error introduced
     |1.0     | 255 |
     +--------+-----+

For more details about floating-point precision and robustness with intervals see Christer Ericson's Real-Time Collision Detection, Chapter 11 Numerical Robustness, Section 11.3 Robust Floating-Point Usage.

Is there a way to follow redirects with command line cURL?

I had a similar problem. I am posting my solution here because I believe it might help one of the commenters.

For me, the obstacle was that the page required a login and then gave me a new URL through javascript. Here is what I had to do:

curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <URL>

Note that j_username and j_password is the name of the fields for my website's login form. You will have to open the source of the webpage to see what the 'name' of the username field and the 'name' of the password field is in your case. After that I go an html file with java script in which the new URL was embedded. After parsing this out just resubmit with the new URL:

curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <NEWURL>

How can I get column names from a table in SQL Server?

This SO question is missing the following approach :

-- List down all columns of table 'Logging'
select * from sys.all_columns where object_id = OBJECT_ID('Logging')

How to change my Git username in terminal?

Firstly you need to change credentials from your local machine

  1. remove generic credentials if there is any

Generic credentials

  1. configure new user and email (you can make it globally if you want)
git config [--global] user.name "Your Name"
git config [--global] user.email "[email protected]"
  1. now upload or update your repo it will ask your username and password to get access to github

Difference in days between two dates in Java?

It depends on what you define as the difference. To compare two dates at midnight you can do.

long day1 = ...; // in milliseconds.
long day2 = ...; // in milliseconds.
long days = (day2 - day1) / 86400000;

Observable.of is not a function

RxJS 6

When upgrading to version 6 of the RxJS library and not using the rxjs-compat package the following code

import 'rxjs/add/observable/of';   
  // ...
  return Observable.of(res);

has to be changed into

import { of } from 'rxjs';
  // ...
  return of(res);

How to get an enum value from a string value in Java?

I was looking for an answer to find the "blah" name and not its value (not the text). base on @Manu (@Mano)answer I find this code useful:

public enum Blah {
A("text1"),
B("text2"),
C("text3"),
D("text4");

private String text;

Blah(String text) {
this.text = text;
}

public String getText() {
  return this.text;
}

public static Blah valueOfCode(String blahCode) throws IllegalArgumentException {
    Blah blah = Arrays.stream(Blah.values())
            .filter(val -> val.name().equals(blahCode))
            .findFirst()
            .orElseThrow(() -> new IllegalArgumentException("Unable to resolve blah : " + blahCode));

    return blah;
}

}

Is there a way to make mv create the directory to be moved to if it doesn't exist?

i accomplished this with the install command on linux:

root@logstash:# myfile=bash_history.log.2021-02-04.gz ; install -v -p -D $myfile /tmp/a/b/$myfile

bash_history.log.2021-02-04.gz -> /tmp/a/b/bash_history.log.2021-02-04.gz

the only downside being the file permissions are changed:

root@logstash:# ls -lh /tmp/a/b/

-rwxr-xr-x 1 root root 914 Fev  4 09:11 bash_history.log.2021-02-04.gz

if you dont mind resetting the permission, you can use:

-g, --group=GROUP   set group ownership, instead of process' current group
-m, --mode=MODE     set permission mode (as in chmod), instead of rwxr-xr-x
-o, --owner=OWNER   set ownership (super-user only)

Is CSS Turing complete?

As per this article, it's not. The article also argues that it's not a good idea to make it one.

To quote from one of the comments:

So, I do not believe that CSS is turing complete. There is no capability to define a function in CSS. In order for a system to be turing-complete it has to be possible to write an interpreter: a function that interprets expressions that denote programs to execute. CSS has no variables that are directly accessible to the user; so you cannot even model the structure that represents the program to be interpreted in CSS.

How to select rows from a DataFrame based on column values

More flexibility using .query with Pandas >= 0.25.0:

August 2019 updated answer

Since Pandas >= 0.25.0 we can use the query method to filter dataframes with Pandas methods and even column names which have spaces. Normally the spaces in column names would give an error, but now we can solve that using a backtick (`) - see GitHub:

# Example dataframe
df = pd.DataFrame({'Sender email':['[email protected]', "[email protected]", "[email protected]"]})

     Sender email
0  [email protected]
1  [email protected]
2    [email protected]

Using .query with method str.endswith:

df.query('`Sender email`.str.endswith("@shop.com")')

Output

     Sender email
1  [email protected]
2    [email protected]

Also we can use local variables by prefixing it with an @ in our query:

domain = 'shop.com'
df.query('`Sender email`.str.endswith(@domain)')

Output

     Sender email
1  [email protected]
2    [email protected]

Flatten List in LINQ

With query syntax:

var values =
from inner in outer
from value in inner
select value;

What should be the sizeof(int) on a 64-bit machine?

Doesn't have to be; "64-bit machine" can mean many things, but typically means that the CPU has registers that big. The sizeof a type is determined by the compiler, which doesn't have to have anything to do with the actual hardware (though it typically does); in fact, different compilers on the same machine can have different values for these.

Start ssh-agent on login

I solved it by adding this to the /etc/profile - system wide (or to user local .profile, or _.bash_profile_):

# SSH-AGENT 
#!/usr/bin/env bash
SERVICE='ssh-agent'
WHOAMI=`who am i |awk '{print $1}'`

if pgrep -u $WHOAMI $SERVICE >/dev/null
then
    echo $SERVICE running.
else
    echo $SERVICE not running.
    echo starting
    ssh-agent > ~/.ssh/agent_env
fi
. ~/.ssh/agent_env

This starts a new ssh-agent if not running for the current user, or re-sets the ssh-agent env parameter if running.

MySQL Creating tables with Foreign Keys giving errno: 150

(Side notes too big for a Comment)

There is no need for an AUTO_INCREMENT id in a mapping table; get rid of it.

Change the PRIMARY KEY to (role_id, role_group_id) (in either order). This will make accesses faster.

Since you probably want to map both directions, also add an INDEX with those two columns in the opposite order. (There is no need to make it UNIQUE.)

More tips: http://mysql.rjweb.org/doc.php/index_cookbook_mysql#speeding_up_wp_postmeta

Show spinner GIF during an $http request in AngularJS?

Simple way without interceptors or jQuery

This is a simple way to show a spinner that does not require a third-party library, intercepters, or jQuery.

In the controller, set and reset a flag.

function starting() {
    //ADD SPINNER
    vm.starting = true;
    $http.get(url)
      .then(function onSuccess(response) {
        vm.data = response.data;
    }).catch(function onReject(errorResponse) {
        console.log(errorResponse.status);
    }).finally(function() {
        //REMOVE SPINNER
        vm.starting = false;
    });
};

In the HTML, use the flag:

<div ng-show="vm.starting">
    <img ng-src="spinnerURL" />
</div>

<div ng-hide="vm.starting">
    <p>{{vm.data}}</p>
</div>

The vm.starting flag is set true when the XHR starts and cleared when the XHR completes.

Can't find SDK folder inside Android studio path, and SDK manager not opening

If your are using android studio go to file >> project structure on the left pane press on SDK location . you will find the path where your sdk is located

Is there a label/goto in Python?

Python offers you the ability to do some of the things you could do with a goto using first class functions. For example:

void somefunc(int a)
{
    if (a == 1)
        goto label1;
    if (a == 2)
        goto label2;

    label1:
        ...
    label2:
        ...
}

Could be done in python like this:

def func1():
    ...

def func2():
    ...

funcmap = {1 : func1, 2 : func2}

def somefunc(a):
    funcmap[a]()  #Ugly!  But it works.

Granted, that isn't the best way to substitute for goto. But without knowing exactly what you're trying to do with the goto, it's hard to give specific advice.

@ascobol:

Your best bet is to either enclose it in a function or use an exception. For the function:

def loopfunc():
    while 1:
        while 1:
            if condition:
                return

For the exception:

try:
    while 1:
        while 1:
            raise BreakoutException #Not a real exception, invent your own
except BreakoutException:
    pass

Using exceptions to do stuff like this may feel a bit awkward if you come from another programming language. But I would argue that if you dislike using exceptions, Python isn't the language for you. :-)

Simulate a button click in Jest

Using Jest, you can do it like this:

test('it calls start logout on button click', () => {
    const mockLogout = jest.fn();
    const wrapper = shallow(<Component startLogout={mockLogout}/>);
    wrapper.find('button').at(0).simulate('click');
    expect(mockLogout).toHaveBeenCalled();
});

Combining CSS Pseudo-elements, ":after" the ":last-child"

I do like this for list items in <menu> elements. Consider the following markup:

<menu>
  <li><a href="/member/profile">Profile</a></li>
  <li><a href="/member/options">Options</a></li>
  <li><a href="/member/logout">Logout</a></li>
</menu>

I style it with the following CSS:

menu > li {
  display: inline;
}

menu > li::after {
  content: ' | ';
}

menu > li:last-child::after {
  content: '';
}

This will display:

Profile | Options | Logout

And this is possible because of what Martin Atkins explained on his comment

Note that in CSS 2 you would use :after, not ::after. If you use CSS 3, use ::after (two semi-columns) because ::after is a pseudo-element (a single semi-column is for pseudo-classes).

Count the number of all words in a string

Try this function from stringi package

   require(stringi)
   > s <- c("Lorem ipsum dolor sit amet, consectetur adipisicing elit.",
    +        "nibh augue, suscipit a, scelerisque sed, lacinia in, mi.",
    +        "Cras vel lorem. Etiam pellentesque aliquet tellus.",
    +        "")
    > stri_stats_latex(s)
        CharsWord CharsCmdEnvir    CharsWhite         Words          Cmds        Envirs 
              133             0            30            24             0             0 

Java Convert GMT/UTC to Local time doesn't work as expected

Joda-Time


UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.

See my other Answer using the industry-leading java.time classes.


Normally we consider it bad form on StackOverflow.com to answer a specific question by suggesting an alternate technology. But in the case of the date, time, and calendar classes bundled with Java 7 and earlier, those classes are so notoriously bad in both design and execution that I am compelled to suggest using a 3rd-party library instead: Joda-Time.

Joda-Time works by creating immutable objects. So rather than alter the time zone of a DateTime object, we simply instantiate a new DateTime with a different time zone assigned.

Your central concern of using both local and UTC time is so very simple in Joda-Time, taking just 3 lines of code.

    org.joda.time.DateTime now = new org.joda.time.DateTime();
    System.out.println( "Local time in ISO 8601 format: " + now + " in zone: " + now.getZone() );
    System.out.println( "UTC (Zulu) time zone: " + now.toDateTime( org.joda.time.DateTimeZone.UTC ) );

Output when run on the west coast of North America might be:

Local time in ISO 8601 format: 2013-10-15T02:45:30.801-07:00

UTC (Zulu) time zone: 2013-10-15T09:45:30.801Z

Here is a class with several examples and further comments. Using Joda-Time 2.5.

/**
 * Created by Basil Bourque on 2013-10-15.
 * © Basil Bourque 2013
 * This source code may be used freely forever by anyone taking full responsibility for doing so.
 */
public class TimeExample {
    public static void main(String[] args) {
        // Joda-Time - The popular alternative to Sun/Oracle's notoriously bad date, time, and calendar classes bundled with Java 8 and earlier.
        // http://www.joda.org/joda-time/

        // Joda-Time will become outmoded by the JSR 310 Date and Time API introduced in Java 8.
        // JSR 310 was inspired by Joda-Time but is not directly based on it.
        // http://jcp.org/en/jsr/detail?id=310

        // By default, Joda-Time produces strings in the standard ISO 8601 format.
        // https://en.wikipedia.org/wiki/ISO_8601
        // You may output to strings in other formats.

        // Capture one moment in time, to be used in all the examples to follow.
        org.joda.time.DateTime now = new org.joda.time.DateTime();

        System.out.println( "Local time in ISO 8601 format: " + now + " in zone: " + now.getZone() );
        System.out.println( "UTC (Zulu) time zone: " + now.toDateTime( org.joda.time.DateTimeZone.UTC ) );

        // You may specify a time zone in either of two ways:
        // • Using identifiers bundled with Joda-Time
        // • Using identifiers bundled with Java via its TimeZone class

        // ----|  Joda-Time Zones  |---------------------------------

        // Time zone identifiers defined by Joda-Time…
        System.out.println( "Time zones defined in Joda-Time : " + java.util.Arrays.toString( org.joda.time.DateTimeZone.getAvailableIDs().toArray() ) );

        // Specify a time zone using DateTimeZone objects from Joda-Time.
        // http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTimeZone.html
        org.joda.time.DateTimeZone parisDateTimeZone = org.joda.time.DateTimeZone.forID( "Europe/Paris" );
        System.out.println( "Paris France (Joda-Time zone): " + now.toDateTime( parisDateTimeZone ) );

        // ----|  Java Zones  |---------------------------------

        // Time zone identifiers defined by Java…
        System.out.println( "Time zones defined within Java : " + java.util.Arrays.toString( java.util.TimeZone.getAvailableIDs() ) );

        // Specify a time zone using TimeZone objects built into Java.
        // http://docs.oracle.com/javase/8/docs/api/java/util/TimeZone.html
        java.util.TimeZone parisTimeZone = java.util.TimeZone.getTimeZone( "Europe/Paris" );
        System.out.println( "Paris France (Java zone): " + now.toDateTime(org.joda.time.DateTimeZone.forTimeZone( parisTimeZone ) ) );

    }
}

Why won't my PHP app send a 404 error?

if (strstr($_SERVER['REQUEST_URI'],'index.php')){
    header('HTTP/1.0 404 Not Found');
    echo "<h1>404 Not Found</h1>";
    echo "The page that you have requested could not be found.";
    exit();
}

If you look at the last two echo lines, that's where you'll see the content. You can customize it however you want.

how to run the command mvn eclipse:eclipse

The m2e plugin uses it's own distribution of Maven, packaged with the plugin.

In order to use Maven from command line, you need to have it installed as a standalone application. Here is an instruction explaining how to do it in Windows

Once Maven is properly installed (i.e. be sure that MAVEN_HOME, JAVA_HOME and PATH variables are set correctly): you must run mvn eclipse:eclipse from the directory containing the pom.xml.

MySQL remove all whitespaces from the entire column

Using below query you can remove leading and trailing whitespace in a MySQL.

UPDATE `table_name`
SET `col_name` = TRIM(`col_name`);

How to join a slice of strings into a single string?

Use a slice, not an arrray. Just create it using

reg := []string {"a","b","c"}

An alternative would have been to convert your array to a slice when joining :

fmt.Println(strings.Join(reg[:],","))

Read the Go blog about the differences between slices and arrays.

Converting from Integer, to BigInteger

The method you want is BigInteger#valueOf(long val).

E.g.,

BigInteger bi = BigInteger.valueOf(myInteger.intValue());

Making a String first is unnecessary and undesired.

How do I set the default schema for a user in MySQL

There is no default database for user. There is default database for current session.

You can get it using DATABASE() function -

SELECT DATABASE();

And you can set it using USE statement -

USE database1;

You should set it manually - USE db_name, or in the connection string.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". in a Maven Project

I am assuming you are using Eclipse as your developing environment.

Eclipse Juno, Indigo and Kepler when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards.

Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the m2e support site.

The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i believe describes the same problem you are facing.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

Simulating ENTER keypress in bash script

Here is sample usage using expect:

#!/usr/bin/expect
set timeout 360
spawn my_command # Replace with your command.
expect "Do you want to continue?" { send "\r" }

Check: man expect for further information.

How to set a primary key in MongoDB?

One way of achieving this behaviour is by setting the value to _id (which is reserved for a primary key in MongoDB) field based on the custom fields you want to treat as primary key.
i.e. If I want employee_id as the primary key then at the time of creating document in MongoDB; assign _id value same as that of employee_id.

stopPropagation vs. stopImmediatePropagation

1)event.stopPropagation(): =>It is used to stop executions of its corresponding parent handler only.

2) event.stopImmediatePropagation(): => It is used to stop the execution of its corresponding parent handler and also handler or function attached to itself except the current handler. => It also stops all the handler attached to the current element of entire DOM.

Here is the example: Jsfiddle!

Thanks, -Sahil

Sound effects in JavaScript / HTML5

It's not possible to do multi-shot playing with a single <audio> element. You need to use multiple elements for this.

How do I spool to a CSV formatted file using SQLPLUS?

You should be aware that values of fields could contain commas and quotation characters, so some of the suggested answers would not work, as the CSV output file would not be correct. To replace quotation characters in a field, and replace it with the double quotation character, you can use the REPLACE function that oracle provides, to change a single quote to double quote.

set echo off
set heading off
set feedback off
set linesize 1024   -- or some other value, big enough
set pagesize 50000
set verify off
set trimspool on

spool output.csv
select trim(
       '"'   || replace(col1, '"', '""') || 
       '","' || replace(col2, '"', '""') ||
       '","' || replace(coln, '"', '""') || '"' ) -- etc. for all the columns
from   yourtable
/
spool off

Or, if you want the single quote character for the fields:

set echo off
set heading off
set feedback off
set linesize 1024   -- or some other value, big enough
set pagesize 50000
set verify off
set trimspool on

spool output.csv
select trim(
'"'   || replace(col1, '''', '''''') || 
'","' || replace(col2, '''', '''''') ||
'","' || replace(coln, '''', '''''') || '"' ) -- etc. for all the columns
from   yourtable
/
spool off

Failed to load ApplicationContext (with annotation)

In my case, I had to do the following while running with Junit5

@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class

Here abc.class was the class that was being tested

Handling null values in Freemarker

I think it works the other way

<#if object.attribute??>
   Do whatever you want....
</#if>

If object.attribute is NOT NULL, then the content will be printed.

Excel: Use a cell value as a parameter for a SQL query

The SQL is somewhat like the syntax of MS SQL.

SELECT * FROM [table$] WHERE *;

It is important that the table name is ended with a $ sign and the whole thing is put into brackets. As conditions you can use any value, but so far Excel didn't allow me to use what I call "SQL Apostrophes" (´), so a column title in one word is recommended.

If you have users listed in a table called "Users", and the id is in a column titled "id" and the name in a column titled "Name", your query will look like this:

SELECT Name FROM [Users$] WHERE id = 1;

Hope this helps.

Using atan2 to find angle between two vectors

angle(vector.b,vector.a)=pi/2*((1+sgn(xa))*(1-sgn(ya^2))-(1+sgn(xb))*(1-sgn(yb^2)))

+pi/4*((2+sgn(xa))*sgn(ya)-(2+sgn(xb))*sgn(yb))

+sgn(xa*ya)*atan((abs(xa)-abs(ya))/(abs(xa)+abs(ya)))

-sgn(xb*yb)*atan((abs(xb)-abs(yb))/(abs(xb)+abs(yb)))

xb,yb and xa,ya are the coordinates of the two vectors

How to get the date 7 days earlier date from current date in Java

You can use this to continue using the type Date and a more legible code, if you preffer:

import org.apache.commons.lang.time.DateUtils;
...
Date yourDate = DateUtils.addDays(new Date(), *days here*);

Using GroupBy, Count and Sum in LINQ Lambda Expressions

var boxSummary = from b in boxes
                 group b by b.Owner into g
                 let nrBoxes = g.Count()
                 let totalWeight = g.Sum(w => w.Weight)
                 let totalVolume = g.Sum(v => v.Volume)
                 select new { Owner = g.Key, Boxes = nrBoxes,
                              TotalWeight = totalWeight,
                              TotalVolume = totalVolume }

How to remove index.php from URLs?

Mainly If you are using Linux Based system Like 'Ubuntu' and this is only suggested for localhost user not for the server.

Follow all the steps mentioned in the previous answers. +

Check in Apache configuration for it. (AllowOverride All) If AllowOverride value is none then change it to All and restart apache again.

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

Let me know if this step help anyone. As it can save you time if you find it earlier.

enter image description here

I am adding the exact lines from my htaccess file in localhost. for your reference

Around line number 110

<IfModule mod_rewrite.c>

############################################
## enable rewrites

Options +FollowSymLinks
RewriteEngine on

############################################
## you can put here your magento root folder
## path relative to web root

#RewriteBase /

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

Images are for some user who understand easily from image the from the text:

enter image description here

Design Android EditText to show error message as described by google

TextInputLayout til = (TextInputLayout)editText.getParent();
til.setErrorEnabled(true);
til.setError("some error..");

Eclipse reports rendering library more recent than ADT plug-in

Please try once uninstalling from Help-->Installation details

and try again installing using http://dl-ssl.google.com/android/eclipse/

Android: ProgressDialog.show() crashes with getApplicationContext

For using dialogs inside activities, do it this way:

private Context mContext;
private AlertDialog.Builder mBuilder;

@Override
protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     mContext = this;

     //using mContext here refering to activity context
     mBuilder = new AlertDialog.Builder(mContext);
     //...
     //rest of the code
     //...
}

For using dialogs inside fragments, do it this way:

private Context mContext;
private AlertDialog.Builder mBuilder;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      View mRootView = inflater.inflate(R.layout.fragment_layout, container, false);
      mContext = getActivity();

      //using mContext here refering to fragment's hosting activity context
      mBuilder = new AlertDialog.Builder(mContext);
      //...
      //rest of the code
      //...
      return mRootView;
}

That's it ^_^

Cannot delete or update a parent row: a foreign key constraint fails

When you create database or create tables

You should add that line at top script create database or table

SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=1;

Now you want to delete records from table? then you write as

SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=1;
DELETE FROM `jobs` WHERE `job_id` =1 LIMIT 1

Good luck!

Get product id and product type in magento?

you can get all product information from following code

$product_id=6//Suppose
$_product=Mage::getModel('catalog/product')->load($product_id);


    $product_data["id"]=$_product->getId();
    $product_data["name"]=$_product->getName();
    $product_data["short_description"]=$_product->getShortDescription();
    $product_data["description"]=$_product->getDescription();
    $product_data["price"]=$_product->getPrice();
    $product_data["special price"]=$_product->getFinalPrice();
    $product_data["image"]=$_product->getThumbnailUrl();
    $product_data["model"]=$_product->getSku();
    $product_data["color"]=$_product->getAttributeText('color'); //get cusom attribute value


    $storeId = Mage::app()->getStore()->getId();
    $summaryData = Mage::getModel('review/review_summary')->setStoreId($storeId)  ->load($_product->getId());
    $product_data["rating"]=($summaryData['rating_summary']*5)/100;

    $product_data["shipping"]=Mage::getStoreConfig('carriers/flatrate/price');

    if($_product->isSalable() ==1)
        $product_data["in_stock"]=1;
    else
        $product_data["in_stock"]=0;


    echo "<pre>";
    print_r($product_data);
    //echo "</pre>";

npm check and update package if needed

To really update just one package install NCU and then run it just for that package. This will bump to the real latest.

npm install -g npm-check-updates

ncu -f your-intended-package-name -u

How to enable assembly bind failure logging (Fusion) in .NET

Set the following registry value:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion!EnableLog] (DWORD) to 1

To disable, set to 0 or delete the value.

[edit ]:Save the following text to a file, e.g FusionEnableLog.reg, in Windows Registry Editor Format:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion]
"EnableLog"=dword:00000001

Then run the file from windows explorer and ignore the warning about possible damage.

Border length smaller than div width?

This will help:

http://www.w3schools.com/tags/att_hr_width.asp

<hr width="50%">

This creates a horizontal line with a width of 50%, you would need to create/modify the class if you would like to edit the style.

How to sort an object array by date property?

You could use sortBy in underscore js.

http://underscorejs.org/#sortBy

Sample:

var log = [{date: '2016-01-16T05:23:38+00:00', other: 'sample'}, 
           {date: '2016-01-13T05:23:38+00:00',other: 'sample'}, 
           {date: '2016-01-15T11:23:38+00:00', other: 'sample'}];

console.log(_.sortBy(log, 'date'));

Grouped bar plot in ggplot

First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level

Then you need to create a data frame out of it, melt it and plot it:

Names=c("Food","Music","People")     # create list of names
data=data.frame(cbind(freq),Names)   # combine them into a data frame
data=data[,c(5,3,1,2,4)]             # sort columns

# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')

# plot everything
ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")

Is this what you're after?

enter image description here

To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:

> head(df)
  ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1  1    A  1980   450   338   154    36    13     9
2  2    A  2000   288   407   212    54    16    23
3  3    A  2020   196   434   246    68    19    36
4  4    B  1980   111   326   441    90    21    11
5  5    B  2000    63   298   443   133    42    21
6  6    B  2020    36   257   462   162    55    30

Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape and plotted.

For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw)) to get this:

> data
   Names Very.Bad Bad Good Very.Good
1   Food        7   6    5         2
2  Music        5   5    7         3
3 People        6   3    7         4

Just imagine you have Very.Bad, Bad, Good and so on instead of X1PCE, X2PCE, X3PCE. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw)).

How to fetch the row count for all tables in a SQL SERVER database

SQL Server 2005 or later gives quite a nice report showing table sizes - including row counts etc. It's in Standard Reports - and it is Disc Usage by Table.

Programmatically, there's a nice solution at: http://www.sqlservercentral.com/articles/T-SQL/67624/

Get RETURN value from stored procedure in SQL

This should work for you. Infact the one which you are thinking will also work:-

 .......
 DECLARE @returnvalue INT

 EXEC @returnvalue = SP_One
 .....

Googlemaps API Key for Localhost

You can follow this tutorial on how to use Google Maps for testing on localhost.

Check these related SO threads:

Hope this helps!

How to enable zoom controls and pinch zoom in a WebView?

Use these:

webview.getSettings().setBuiltInZoomControls(true);
webview.getSettings().setDisplayZoomControls(false);

How to check if variable is array?... or something array-like

Functions

<?php

/**
 * Is Array?
 * @param mixed $x
 * @return bool
 */
function isArray($x) : bool {
  return !isAssociative($x);
}

/**
 * Is Associative Array?
 * @param mixed $x
 * @return bool
 */
function isAssociative($x) : bool {
  if (!is_array($array)) {
    return false;
  }
  $i = count($array);
  while ($i > 0) {
    if (!isset($array[--$i])) {
      return true;
    }
  }
  return false;
}

Example

<?php

$arr = [ 'foo', 'bar' ];
$obj = [ 'foo' => 'bar' ];

var_dump(isAssociative($arr));
# bool(false)

var_dump(isAssociative($obj));
# bool(true)

var_dump(isArray($obj));
# bool(false)

var_dump(isArray($arr));
# bool(true)

Simple jQuery, PHP and JSONP example?

More Suggestion

JavaScript:

$.ajax({
        url: "http://FullUrl",
        dataType: 'jsonp',
        success: function (data) {

            //Data from the server in the in the variable "data"
            //In the form of an array

        }

});

PHP CallBack:

<?php

$array = array(
     '0' => array('fullName' => 'Meni Samet', 'fullAdress' => 'New York, NY'),
     '1' => array('fullName' => 'Test 2', 'fullAdress' => 'Paris'),
);

if(isset ($_GET['callback']))
{
    header("Content-Type: application/json");

    echo $_GET['callback']."(".json_encode($array).")";

}
?>

How to set up a squid Proxy with basic username and password authentication?

Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)

Basic squid conf

/etc/squid3/squid.conf instead of the super bloated default config file

auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

# Choose the port you want. Below we set it to default 3128.
http_port 3128

Please note the basic_ncsa_auth program instead of the old ncsa_auth

squid 2.x

For squid 2.x you need to edit /etc/squid/squid.conf file and place:

auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Setting up a user

sudo htpasswd -c /etc/squid3/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid3 restart

squid 2.x

sudo htpasswd -c /etc/squid/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid restart

htdigest vs htpasswd

For the many people that asked me: the 2 tools produce different file formats:

  • htdigest stores the password in plain text.
  • htpasswd stores the password hashed (various hashing algos are available)

Despite this difference in format basic_ncsa_auth will still be able to parse a password file generated with htdigest. Hence you can alternatively use:

sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like

Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.

On Ubuntu 14.04 htdigest and htpasswd are both available in the [apache2-utils][1] package.

MacOS

Similar as above applies, but file paths are different.

Install squid

brew install squid

Start squid service

brew services start squid

Squid config file is stored at /usr/local/etc/squid.conf.

Comment or remove following line:

http_access allow localnet

Then similar to linux config (but with updated paths) add this:

auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Note that path to basic_ncsa_auth may be different since it depends on installed version when using brew, you can verify this with ls /usr/local/Cellar/squid/. Also note that you should add the above just bellow the following section:

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

Now generate yourself a user:password basic auth credential (note: htpasswd and htdigest are also both available on MacOS)

htpasswd -c /usr/local/etc/squid_passwords username_you_like

Restart the squid service

brew services restart squid

php var_dump() vs print_r()

We can pass multiple parameters with var_dump like:

var_dump("array1",$array1,"array2",$array2);

Algorithm for Determining Tic Tac Toe Game Over

If you have boarder field 5*5 for examle, I used next method of checking:

public static boolean checkWin(char symb) {
  int SIZE = 5;

        for (int i = 0; i < SIZE-1; i++) {
            for (int j = 0; j <SIZE-1 ; j++) {
                //vertical checking
            if (map[0][j] == symb && map[1][j] == symb && map[2][j] == symb && map[3][j] == symb && map[4][j] == symb) return true;      // j=0
            }
            //horisontal checking
            if(map[i][0] == symb && map[i][1] == symb && map[i][2] == symb && map[i][3] == symb && map[i][4] == symb) return true;  // i=0
        }
        //diagonal checking (5*5)
        if (map[0][0] == symb && map[1][1] == symb && map[2][2] == symb && map[3][3] == symb && map[4][4] == symb) return true;
        if (map[4][0] == symb && map[3][1] == symb && map[2][2] == symb && map[1][3] == symb && map[0][4] == symb) return true;

        return false; 
        }

I think, it's more clear, but probably is not the most optimal way.

Is it possible to use JavaScript to change the meta-tags of the page?

$(document).ready(function() {
  $('meta[property="og:title"]').remove();
  $('meta[property="og:description"]').remove();
  $('meta[property="og:url"]').remove();
  $("head").append('<meta property="og:title" content="blubb1">');
  $("head").append('<meta property="og:description" content="blubb2">');
  $("head").append('<meta property="og:url" content="blubb3">');
});

Listing all the folders subfolders and files in a directory using php

It will use to make menu bar in directory format

$pathLen = 0;

function prePad($level)
{
  $ss = "";

  for ($ii = 0;  $ii < $level;  $ii++)
  {
      $ss = $ss . "|&nbsp;&nbsp;";
    }

    return $ss;
  }

  function myScanDir($dir, $level, $rootLen)
  {
    global $pathLen;

    if ($handle = opendir($dir)) {

      $allFiles = array();

      while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
          if (is_dir($dir . "/" . $entry))
          {
            $allFiles[] = "D: " . $dir . "/" . $entry;
          }
          else
          {
            $allFiles[] = "F: " . $dir . "/" . $entry;
          }
        }
      }
      closedir($handle);

      natsort($allFiles);

      foreach($allFiles as $value)
      {
        $displayName = substr($value, $rootLen + 4);
        $fileName    = substr($value, 3);
        $linkName    = str_replace(" ", " ", substr($value, $pathLen + 3));


        if (is_dir($fileName))
         {
               echo "<li ><a class='dropdown'><span>" . $displayName . "                    </span></a><ul>";

          myScanDir($fileName, $level + 1, strlen($fileName));
            echo "</ul></li>";
  } 
        else {
      $newstring = substr($displayName, -3);  
      if($newstring == "PDF" || $newstring == "pdf" )

          echo "<li ><a href=\"" . $linkName . "\" style=\"text-decoration:none;\">" . $displayName . "</a></li>";

        }
  $t;
        if($level != 0)
        {
          if($level < $t)
          {
        $r = int($t) - int($level);
        for($i=0;$i<$r;$i++)
        {
            echo "</ul></li>";
        }
          } 
        }
              $t = $level;
      }
          }

        }
        ?>

                                        <li style="color: #ffffff">

                                                <?php                                                   
   //  ListFolder('D:\PDF');
     $root = 'D:\PDF';
   $pathLen = strlen($root);

    myScanDir($root, 0, strlen($root)); 
     ?>


                                        </li>

Delete all but the most recent X files in bash

If the filenames don't have spaces, this will work:

ls -C1 -t| awk 'NR>5'|xargs rm

If the filenames do have spaces, something like

ls -C1 -t | awk 'NR>5' | sed -e "s/^/rm '/" -e "s/$/'/" | sh

Basic logic:

  • get a listing of the files in time order, one column
  • get all but the first 5 (n=5 for this example)
  • first version: send those to rm
  • second version: gen a script that will remove them properly

How can I use console logging in Internet Explorer?

Simple IE7 and below shim that preserves Line Numbering for other browsers:

/* console shim*/
(function () {
    var f = function () {};
    if (!window.console) {
        window.console = {
            log:f, info:f, warn:f, debug:f, error:f
        };
    }
}());

How to Correctly handle Weak Self in Swift Blocks with Arguments

**EDITED for Swift 4.2:

As @Koen commented, swift 4.2 allows:

guard let self = self else {
   return // Could not get a strong reference for self :`(
}

// Now self is a strong reference
self.doSomething()

P.S.: Since I am having some up-votes, I would like to recommend the reading about escaping closures.

EDITED: As @tim-vermeulen has commented, Chris Lattner said on Fri Jan 22 19:51:29 CST 2016, this trick should not be used on self, so please don't use it. Check the non escaping closures info and the capture list answer from @gbk.**

For those who use [weak self] in capture list, note that self could be nil, so the first thing I do is check that with a guard statement

guard let `self` = self else {
   return
}
self.doSomething()

If you are wondering what the quote marks are around self is a pro trick to use self inside the closure without needing to change the name to this, weakSelf or whatever.

Can I pass parameters in computed properties in Vue.Js

You can also pass arguments to getters by returning a function. This is particularly useful when you want to query an array in the store:

getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

Note that getters accessed via methods will run each time you call them, and the result is not cached.

That is called Method-Style Access and it is documented on the Vue.js docs.

How to convert a hex string to hex number

Use format string

intNum = 123
print "0x%x"%(intNum)

or hex function.

intNum = 123
print hex(intNum)

How to populate a dropdownlist with json data in jquery?

//javascript
//teams.Table does not exist

function OnSuccessJSON(data, status) {
    var teams = eval('(' + data.d + ')');
    var listItems = "";
    for (var i = 0; i < teams.length; i++) {
      listItems += "<option value='" + teams[i][0]+ "'>" + teams[i][1] + "</option>";
    }
    $("#<%=ddlTeams.ClientID%>").html(listItems);
} 

How do I make an editable DIV look like a text field?

In WebKit, you can do: -webkit-appearance: textarea;

Android - Using Custom Font

After trying most of the solutions described in this thread, I accidentally found Calligraphy (https://github.com/chrisjenx/Calligraphy) - a library by Christopher Jenkins that lets you easily add custom fonts to your app. The advantages of his lib comparing to approaches suggested here are:

  1. you don't have to introduce your own overriden TextView component, you use the built-in TextView
  2. you can easily include the library using gradle
  3. The library doesn't limit your choice of fonts; you just add your preferred ones to the assets dir
  4. you not only get custom text views — all the other text-based Android compontents will also be displayed using your custom font.

No assembly found containing an OwinStartupAttribute Error

I was missing the attribute:

[assembly: OwinStartupAttribute(typeof(projectname.Startup))]

Which specifies the startup class. More details: https://docs.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-startup-class-detection

Error 1053 the service did not respond to the start or control request in a timely fashion

this error can be caused due to various reasons. to identify the reason add try/ catch when service is run.

        try
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] 
                { 
                    new Service1() 
                };
                <span class="skimlinks-unlinked">ServiceBase.Run(ServicesToRun</span>);
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("Application", ex.ToString(), <span class="skimlinks-unlinked">EventLogEntryType.Error</span>);
            }

Is there a download function in jsFiddle?

Ok I found out:

You have to put /show a after the URL you're working on:
http://jsfiddle.net/<your_fiddle_id>/show/
It is the site that shows the results.

And then when you save it as a file. It is all in one HTML-file.

For example:
http://jsfiddle.net/Ua8Cv/show/
for the site http://jsfiddle.net/Ua8Cv

How to add a footer in ListView?

Create a footer view layout consisting of text that you want to set as footer and then try

View footerView = ((LayoutInflater) ActivityContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_layout, null, false);
ListView.addFooterView(footerView);

Layout for footer could be something like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="7dip"
    android:paddingBottom="7dip"
    android:orientation="horizontal"
    android:gravity="center">

    <LinearLayout 
        android:id="@+id/footer_layout" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center"
        android:layout_gravity="center">

    <TextView 
        android:text="@string/footer_text_1" 
        android:id="@+id/footer_1" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:textSize="14dip" 
        android:textStyle="bold" 
        android:layout_marginRight="5dip" />
    </LinearLayout>
</LinearLayout> 

The activity class could be:

public class MyListActivty extends ListActivity {
    private Context context = null;
    private ListView list = null;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        list = (ListView)findViewById(android.R.id.list);

        //code to set adapter to populate list
        View footerView =  ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_layout, null, false);
        list.addFooterView(footerView);
    }
}

In Objective-C, how do I test the object type?

You can make use of the following code incase you want to check the types of primitive data types.

// Returns 0 if the object type is equal to double
strcmp([myNumber objCType], @encode(double)) 

Reset the Value of a Select Box

I presume you only want to reset a single element. Resetting an entire form is simple: call its reset method.

The easiest way to "reset" a select element is to set its selectedIndex property to the default value. If you know that no option is the default selected option, just set the select elemen'ts selectedIndex property to an appropriate value:

function resetSelectElement(selectElement) {
    selecElement.selectedIndex = 0;  // first option is selected, or
                                     // -1 for no option selected
}

However, since one option may have the selected attribtue or otherwise be set to the default selected option, you may need to do:

function resetSelectElement(selectElement) {
    var options = selectElement.options;

    // Look for a default selected option
    for (var i=0, iLen=options.length; i<iLen; i++) {

        if (options[i].defaultSelected) {
            selectElement.selectedIndex = i;
            return;
        }
    }

    // If no option is the default, select first or none as appropriate
    selectElement.selectedIndex = 0; // or -1 for no option selected
}

And beware of setting attributes rather than properties, they have different effects in different browsers.

Should ol/ul be inside <p> or outside?

<p>tetxetextex</p>
<ol><li>first element</li></ol>
<p>other textetxeettx</p>

Because both <p> and <ol> are element rendered as block.

Console output in a Qt GUI app?

No way to output a message to console when using QT += gui.

fprintf(stderr, ...) also can't print output.

Use QMessageBox instead to show the message.

Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone

If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".

enter image description here

Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".

How do I view events fired on an element in Chrome DevTools?

For jQuery (at least version 1.11.2) the following procedure worked for me.

  1. Right click on the element and open 'Chrome Developer Tools'
  2. Type $._data(($0), 'events'); in the 'Console'
  3. Expand the attached objects and double click the handler: value.
  4. This shows the source code of the attached function, search for part of that using the 'Search' tab.

And it's time to stop re-inventing the wheel and start using vanilla JS events ... :)

how-to-find-jquery-click-handler-function

Read values into a shell variable from a pipe

if you want to read in lots of data and work on each line separately you could use something like this:

cat myFile | while read x ; do echo $x ; done

if you want to split the lines up into multiple words you can use multiple variables in place of x like this:

cat myFile | while read x y ; do echo $y $x ; done

alternatively:

while read x y ; do echo $y $x ; done < myFile

But as soon as you start to want to do anything really clever with this sort of thing you're better going for some scripting language like perl where you could try something like this:

perl -ane 'print "$F[0]\n"' < myFile

There's a fairly steep learning curve with perl (or I guess any of these languages) but you'll find it a lot easier in the long run if you want to do anything but the simplest of scripts. I'd recommend the Perl Cookbook and, of course, The Perl Programming Language by Larry Wall et al.

Multiline string literal in C#

The problem with using string literal I find is that it can make your code look a bit "weird" because in order to not get spaces in the string itself, it has to be completely left aligned:

    var someString = @"The
quick
brown
fox...";

Yuck.

So the solution I like to use, which keeps everything nicely aligned with the rest of your code is:

var someString = String.Join(
    Environment.NewLine,
    "The",
    "quick",
    "brown",
    "fox...");

And of course, if you just want to logically split up lines of an SQL statement like you are and don't actually need a new line, you can always just substitute Environment.NewLine for " ".

Include in SELECT a column that isn't actually in the database

You may want to use:

SELECT Name, 'Unpaid' AS Status FROM table;

The SELECT clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:

SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ] 
<select_list> 

Where the expression can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.

ORA-00054: resource busy and acquire with NOWAIT specified

When you killed the session, the session hangs around for a while in "KILLED" status while Oracle cleans up after it.

If you absolutely must, you can kill the OS process as well (look up v$process.spid), which would release any locks it was holding on to.

See this for more detailed info.

What are the First and Second Level caches in (N)Hibernate?

by default, NHibernate uses first level caching which is Session Object based. but if you are running in a multi-server environment, then the first level cache may not very scalable along with some performance issues. it is happens because of the fact that it has to make very frequent trips to the database as the data is distributed over multiple servers. in other words NHibernate provides a basic, not-so-sophisticated in-process L1 cache out of box. However, it doesn’t provide features that a caching solution must have to have a notable impact on the application performance.

so the questions of all these problem is the use of a L2 cache which is associated with the session factory objects. it reduces the time consuming trips to the database so ultimately increases the app response time.

Eclipse IDE for Java - Full Dark Theme

Windows 10 users

If you want to get a custom window title color on Windows 10, in short going from this

eclipse - white window title

to this (or any other custom color for the window of your Eclipse IDE)

eclipse - full black

follow the next steps.

Go to C:\Windows\Resources\Themes\. Duplicate the folder aero and the file aero.theme. If you can't duplicate the folder and the file then right click on both, Properties, Security, Modify, add your user to Permissions, and set authorizations to modify, read and write.

Rename the folder C:\Windows\Resources\Themes\aero - copy and the file C:\Windows\Resources\Themes\aero - copy.theme to C:\Windows\Resources\Themes\custom and C:\Windows\Resources\Themes\custom.theme (you can pick the name you want).

themes folder

Rename C:\Windows\Resources\Themes\custom\aero.msstyles to C:\Windows\Resources\Themes\custom.msstyles.

custom theme folder

Rename C:\Windows\Resources\Themes\custom\%your_locale%\aero.msstyles.mui (%your_locale% is fr-FR in my case) to C:\Windows\Resources\Themes\custom\%your_locale%\custom.msstyles.mui.

custom theme - locale folder

Edit custom.theme with Notepad and change the PATH variable of VisualStyles to your custom.msstyles.

changing theme path

Set your custom theme (yet unchanged) by double-clicking on custom.theme. Then right-click on start menu button, go to Parameters -> Customize appearance -> Themes and select the second one. Go to the menu Colors, select dark mode for every applications. Choose custom color for accent color and put it full black.

start menu - parameters

choosing custom theme

changin custom theme

custom accent color

custom accent color set to black

Apply your favorite dark theme (here DevStyle - Darkest dark - Deep black) to Eclipse and voilà, you have a full dark theme for Eclipse on Windows 10!

eclipse - full black

From ND to 1D arrays

For list of array with different size use following:

import numpy as np

# ND array list with different size
a = [[1],[2,3,4,5],[6,7,8]]

# stack them
b = np.hstack(a)

print(b)

Output:

[1 2 3 4 5 6 7 8]

Group by multiple field names in java 8

Here look at the code:

You can simply create a Function and let it do the work for you, kind of functional Style!

Function<Person, List<Object>> compositeKey = personRecord ->
    Arrays.<Object>asList(personRecord.getName(), personRecord.getAge());

Now you can use it as a map:

Map<Object, List<Person>> map =
people.collect(Collectors.groupingBy(compositeKey, Collectors.toList()));

Cheers!

Grant Select on all Tables Owned By Specific User

Well, it's not a single statement, but it's about as close as you can get with oracle:

BEGIN
   FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP
      EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser';
   END LOOP;
END; 

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

I'm not sure I understand your intent perfectly, but perhaps the following would be close to what you want:

select n1.name, n1.author_id, count_1, total_count
  from (select id, name, author_id, count(1) as count_1
          from names
          group by id, name, author_id) n1
inner join (select id, author_id, count(1) as total_count
              from names
              group by id, author_id) n2
  on (n2.id = n1.id and n2.author_id = n1.author_id)

Unfortunately this adds the requirement of grouping the first subquery by id as well as name and author_id, which I don't think was wanted. I'm not sure how to work around that, though, as you need to have id available to join in the second subquery. Perhaps someone else will come up with a better solution.

Share and enjoy.

View HTTP headers in Google Chrome?

I'm not sure about your exact version, but Chrome has a tab "Network" with several items and when I click on them I can see the headers on the right in a tab.

Press F12 on windows or ??I on a mac to bring up the Chrome developer tools.

Chrome developer tools headers tab

Is there a typescript List<> and/or Map<> class/library?

It's very easy to write that yourself, and that way you have more control over things.. As the other answers say, TypeScript is not aimed at adding runtime types or functionality.

Map:

class Map<T> {
    private items: { [key: string]: T };

    constructor() {
        this.items = {};
    }

    add(key: string, value: T): void {
        this.items[key] = value;
    }

    has(key: string): boolean {
        return key in this.items;
    }

    get(key: string): T {
        return this.items[key];
    }
}

List:

class List<T> {
    private items: Array<T>;

    constructor() {
        this.items = [];
    }

    size(): number {
        return this.items.length;
    }

    add(value: T): void {
        this.items.push(value);
    }

    get(index: number): T {
        return this.items[index];
    }
}

I haven't tested (or even tried to compile) this code, but it should give you a starting point.. you can of course then change what ever you want and add the functionality that YOU need...

As for your "special needs" from the List, I see no reason why to implement a linked list, since the javascript array lets you add and remove items.
Here's a modified version of the List to handle the get prev/next from the element itself:

class ListItem<T> {
    private list: List<T>;
    private index: number;

    public value: T;

    constructor(list: List<T>, value: T, index: number) {
        this.list = list;
        this.index = index;
        this.value = value;
    }

    prev(): ListItem<T> {
        return this.list.get(this.index - 1);
    }

    next(): ListItem<T> {
        return this.list.get(this.index + 1);   
    }
}

class List<T> {
    private items: Array<ListItem<T>>;

    constructor() {
        this.items = [];
    }

    size(): number {
        return this.items.length;
    }

    add(value: T): void {
        this.items.push(new ListItem<T>(this, value, this.size()));
    }

    get(index: number): ListItem<T> {
        return this.items[index];
    }
}

Here too you're looking at untested code..

Hope this helps.


Edit - as this answer still gets some attention

Javascript has a native Map object so there's no need to create your own:

let map = new Map();
map.set("key1", "value1");
console.log(map.get("key1")); // value1

How do I find out what all symbols are exported from a shared object?

The cross-platform way (not only cross-platform itself, but also working, at the very least, with both *.so and *.dll) is using reverse-engineering framework radare2. E.g.:

$ rabin2 -s glew32.dll | head -n 5 
[Symbols]
vaddr=0x62afda8d paddr=0x0005ba8d ord=000 fwd=NONE sz=0 bind=GLOBAL type=FUNC name=glew32.dll___GLEW_3DFX_multisample
vaddr=0x62afda8e paddr=0x0005ba8e ord=001 fwd=NONE sz=0 bind=GLOBAL type=FUNC name=glew32.dll___GLEW_3DFX_tbuffer
vaddr=0x62afda8f paddr=0x0005ba8f ord=002 fwd=NONE sz=0 bind=GLOBAL type=FUNC name=glew32.dll___GLEW_3DFX_texture_compression_FXT1
vaddr=0x62afdab8 paddr=0x0005bab8 ord=003 fwd=NONE sz=0 bind=GLOBAL type=FUNC name=glew32.dll___GLEW_AMD_blend_minmax_factor

As a bonus, rabin2 recognizes C++ name mangling, for example (and also with .so file):

$ rabin2 -s /usr/lib/libabw-0.1.so.1.0.1 | head -n 5
[Symbols]
vaddr=0x00027590 paddr=0x00027590 ord=124 fwd=NONE sz=430 bind=GLOBAL type=FUNC name=libabw::AbiDocument::isFileFormatSupported
vaddr=0x0000a730 paddr=0x0000a730 ord=125 fwd=NONE sz=58 bind=UNKNOWN type=FUNC name=boost::exception::~exception
vaddr=0x00232680 paddr=0x00032680 ord=126 fwd=NONE sz=16 bind=UNKNOWN type=OBJECT name=typeinfoforboost::exception_detail::clone_base
vaddr=0x00027740 paddr=0x00027740 ord=127 fwd=NONE sz=235 bind=GLOBAL type=FUNC name=libabw::AbiDocument::parse

Works with object files too:

$ g++ test.cpp -c -o a.o
$ rabin2 -s a.o | head -n 5
Warning: Cannot initialize program headers
Warning: Cannot initialize dynamic strings
Warning: Cannot initialize dynamic section
[Symbols]
vaddr=0x08000149 paddr=0x00000149 ord=006 fwd=NONE sz=1 bind=LOCAL type=OBJECT name=std::piecewise_construct
vaddr=0x08000149 paddr=0x00000149 ord=007 fwd=NONE sz=1 bind=LOCAL type=OBJECT name=std::__ioinit
vaddr=0x080000eb paddr=0x000000eb ord=017 fwd=NONE sz=73 bind=LOCAL type=FUNC name=__static_initialization_and_destruction_0
vaddr=0x08000134 paddr=0x00000134 ord=018 fwd=NONE sz=21 bind=LOCAL type=FUNC name=_GLOBAL__sub_I__Z4funcP6Animal

Close Bootstrap Modal

   function Delete(){
       var id = $("#dgetid").val();
       debugger
       $.ajax({
           type: "POST",
           url: "Add_NewProduct.aspx/DeleteData",
           data: "{id:'" + id + "'}",
           datatype: "json",
           contentType: "application/json; charset=utf-8",
           success: function (result) {
               if (result.d == 1) {
                   bindData();
                   setTimeout(function(){ $('#DeleteModal').modal('hide');},1000);
               }
           }
       });
   };

How to move from one fragment to another fragment on click of an ImageView in Android?

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_profile, container, false);
    notification = (ImageView)v.findViewById(R.id.notification);

    notification.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FragmentTransaction fr = getFragmentManager().beginTransaction();
            fr.replace(R.id.container,new NotificationFragment());
            fr.commit();
        }
    });

    return v;
}

Is there an onSelect event or equivalent for HTML <select>?

Here's my solution, completely different to any else on here. It uses the mouse position to figure out if an option was clicked as oppose to clicking on the select box to open the dropdown. It makes use of the event.screenY position as this is the only reliable cross browser variable. A hover event has to be attached first so it can figure out the controls position relative to the screen before the click event.

var select = $("select");

var screenDif = 0;
select.bind("hover", function (e) {
    screenDif = e.screenY - e.clientY;
});
select.bind("click", function (e) {
    var element = $(e.target);
    var eventHorizon = screenDif + element.offset().top + element.height() - $(window).scrollTop();
    if (e.screenY > eventHorizon)
        alert("option clicked");
});

Here is my jsFiddle http://jsfiddle.net/sU7EV/4/

ORA-00932: inconsistent datatypes: expected - got CLOB

The problem may lie in selected null values ??in combination with a CLOB-type column.

select valueVarchar c1 ,
       valueClob c2 ,
       valueVarchar c3 ,
       valueVvarchar c4
of Table_1
union
select valueVarchar c1 ,
       valueClob c2 ,
       valueVarchar c3 ,
       null c4
of table_2

I reworked the cursor. The first cursor is composed of four non-null columns. The second cursor selects three non-null columns. The null values ??were injected into the cursorForLoop .

Use grep to report back only line numbers

You're going to want the second field after the colon, not the first.

grep -n "text to find" file.txt | cut -f2 -d:

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

I had this issue myself, regarding the error message that is received trying to populate a foreign key field. I ended up on this page in hopes of finding the answer. The checked answer on this page is indeed the correct one, unfortunately I feel that the answer is a bit incomplete for people not as familiar with SQL. I am fairly apt at writing code but SQL queries are new to me as well as building database tables.

Despite the checked answer being correct:

Mike M wrote-

"The way a FK works is it cannot have a value in that column that is not also in the primary key column of the referenced table."

What is missing from this answer is simply;

You must build the table containing the Primary Key first.

Another way to say it is;

You must Insert Data into the parent table, containing the Primary Key, before attempting to insert data into the child table containing the Foreign Key.

In short, many of the tutorials seem to be glazing over this fact so that if you were to try on your own and didn't realize there was an order of operations, then you would get this error. Naturally after adding the primary key data, your foreign key data in the child table must conform to the primary key field in the parent table, otherwise, you will still get this error.

If anyone read down this far. I hope this helped make the checked answer more clear. I know there are some of you who may feel that this sort of thing is pretty straight-forward and that opening a book would have answered this question before it was posted, but the truth is that not everyone learns in the same way.

Does a `+` in a URL scheme/host/path represent a space?

  • Percent encoding in the path section of a URL is expected to be decoded, but
  • any + characters in the path component is expected to be treated literally.

To be explicit: + is only a special character in the query component.

https://tools.ietf.org/html/rfc3986

jQuery UI DatePicker to show year only

I had the same problem and, after a day of research, I came up with this solution: http://jsfiddle.net/konstantc/4jkef3a1/

_x000D_
_x000D_
// *** (month and year only) ***_x000D_
$(function() { _x000D_
  $('#datepicker1').datepicker( {_x000D_
    yearRange: "c-100:c",_x000D_
    changeMonth: true,_x000D_
    changeYear: true,_x000D_
    showButtonPanel: true,_x000D_
    closeText:'Select',_x000D_
    currentText: 'This year',_x000D_
    onClose: function(dateText, inst) {_x000D_
      var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();_x000D_
      var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();_x000D_
      $(this).val($.datepicker.formatDate('MM yy (M y) (mm/y)', new Date(year, month, 1)));_x000D_
    }_x000D_
  }).focus(function () {_x000D_
    $(".ui-datepicker-calendar").hide();_x000D_
    $(".ui-datepicker-current").hide();_x000D_
    $("#ui-datepicker-div").position({_x000D_
      my: "left top",_x000D_
      at: "left bottom",_x000D_
      of: $(this)_x000D_
    });_x000D_
  }).attr("readonly", false);_x000D_
});_x000D_
// --------------------------------_x000D_
_x000D_
_x000D_
_x000D_
// *** (year only) ***_x000D_
$(function() { _x000D_
  $('#datepicker2').datepicker( {_x000D_
    yearRange: "c-100:c",_x000D_
    changeMonth: false,_x000D_
    changeYear: true,_x000D_
    showButtonPanel: true,_x000D_
    closeText:'Select',_x000D_
    currentText: 'This year',_x000D_
    onClose: function(dateText, inst) {_x000D_
      var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();_x000D_
      $(this).val($.datepicker.formatDate('yy', new Date(year, 1, 1)));_x000D_
    }_x000D_
  }).focus(function () {_x000D_
    $(".ui-datepicker-month").hide();_x000D_
    $(".ui-datepicker-calendar").hide();_x000D_
    $(".ui-datepicker-current").hide();_x000D_
    $(".ui-datepicker-prev").hide();_x000D_
    $(".ui-datepicker-next").hide();_x000D_
    $("#ui-datepicker-div").position({_x000D_
      my: "left top",_x000D_
      at: "left bottom",_x000D_
      of: $(this)_x000D_
    });_x000D_
  }).attr("readonly", false);_x000D_
});_x000D_
// --------------------------------_x000D_
_x000D_
_x000D_
_x000D_
// *** (year only, no controls) ***_x000D_
$(function() { _x000D_
  $('#datepicker3').datepicker( {_x000D_
    dateFormat: "yy",_x000D_
    yearRange: "c-100:c",_x000D_
    changeMonth: false,_x000D_
    changeYear: true,_x000D_
    showButtonPanel: false,_x000D_
    closeText:'Select',_x000D_
    currentText: 'This year',_x000D_
    onClose: function(dateText, inst) {_x000D_
      var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();_x000D_
      $(this).val($.datepicker.formatDate('yy', new Date(year, 1, 1)));_x000D_
    },_x000D_
    onChangeMonthYear : function () {_x000D_
      $(this).datepicker( "hide" );_x000D_
    }_x000D_
  }).focus(function () {_x000D_
    $(".ui-datepicker-month").hide();_x000D_
    $(".ui-datepicker-calendar").hide();_x000D_
    $(".ui-datepicker-current").hide();_x000D_
    $(".ui-datepicker-prev").hide();_x000D_
    $(".ui-datepicker-next").hide();_x000D_
    $("#ui-datepicker-div").position({_x000D_
      my: "left top",_x000D_
      at: "left bottom",_x000D_
      of: $(this)_x000D_
    });_x000D_
  }).attr("readonly", false);_x000D_
});_x000D_
// --------------------------------
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />_x000D_
_x000D_
<div class="container">_x000D_
_x000D_
  <h2 class="font-weight-light text-lg-left mt-4 mb-0"><b>jQuery UI Datepicker</b> custom select</h2>_x000D_
_x000D_
  <hr class="mt-2 mb-3">_x000D_
  <div class="row text-lg-left">_x000D_
    <div class="col-12">_x000D_
_x000D_
      <form>_x000D_
_x000D_
        <div class="form-label-group">_x000D_
        <label for="datepicker1">(month and year only : <code>id="datepicker1"</code> )</label>_x000D_
          <input type="text" class="form-control" id="datepicker1" _x000D_
                 placeholder="(month and year only)" />_x000D_
        </div>_x000D_
_x000D_
        <hr />_x000D_
_x000D_
        <div class="form-label-group">_x000D_
        <label for="datepicker2">(year only : <code>input id="datepicker2"</code> )</label>_x000D_
          <input type="text" class="form-control" id="datepicker2" _x000D_
                 placeholder="(year only)" />_x000D_
        </div>_x000D_
_x000D_
        <hr />_x000D_
_x000D_
        <div class="form-label-group">_x000D_
        <label for="datepicker3">(year only, no controls : <code>input id="datepicker3"</code> )</label>_x000D_
          <input type="text" class="form-control" id="datepicker3" _x000D_
                 placeholder="(year only, no controls)" />_x000D_
        </div>_x000D_
_x000D_
      </form>_x000D_
_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

I know this question is pretty old but I thought that my solution can be of use to others that encounter this problem. Hope it helps.

Hadoop: «ERROR : JAVA_HOME is not set»

You can add in your .bashrc file:

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")

and it will dynamically change when you update your packages.

How to convert NSNumber to NSString

In Swift 3.0

let number:NSNumber = 25
let strValue = String(describing: number as NSNumber)
print("As String => \(strValue)")

We can get the number value in String.

How to crop an image using PIL?

There is a crop() method:

w, h = yourImage.size
yourImage.crop((0, 30, w, h-30)).save(...)

How do I make a relative reference to another workbook in Excel?

The only solutions that I've seen to organize the external files into sub-folders has required the use of VBA to resolve a full path to the external file in the formulas. Here is a link to a site with several examples others have used:

http://www.teachexcel.com/excel-help/excel-how-to.php?i=415651

Alternatively, if you can place all of the files in the same folder instead of dividing them into sub-folders, then Excel will resolve the external references without requiring the use of VBA even if you move the files to a network location. Your formulas then become simply ='[ComponentsC.xlsx]Sheet1'!A1 with no folder names to traverse.

How to concatenate strings in windows batch file for loop?

A very simple example:

SET a=Hello
SET b=World
SET c=%a% %b%!
echo %c%

The result should be:

Hello World!

How to implement the Java comparable interface?

Emp class needs to implement Comaparable interface so we need to Override its compateTo method.

import java.util.ArrayList;
import java.util.Collections;


class Emp implements Comparable< Emp >{

    int empid;
    String name;

    Emp(int empid,String name){
         this.empid = empid;  
         this.name = name;

    }


    @Override
    public String toString(){
        return empid+" "+name;
    }

    @Override
    public int compareTo(Emp o) {

     if(this.empid==o.empid){
       return 0; 
     } 
     else if(this.empid < o.empid){
     return 1;
     }
     else{
       return -1;
     }
    }
}

public class JavaApplication1 {


    public static void main(String[] args) {

    ArrayList<Emp> a= new ArrayList<Emp>();

    a.add(new Emp(10,"Mahadev"));
      a.add(new Emp(50,"Ashish"));
      a.add(new Emp(40,"Amit"));
      Collections.sort(a);
      for(Emp id:a){
      System.out.println(id);
      }
    }

}

How do I test if a string is empty in Objective-C?

Another option is to check if it is equal to @"" with isEqualToString: like so:

if ([myString isEqualToString:@""]) {
    NSLog(@"myString IS empty!");
} else {
    NSLog(@"myString IS NOT empty, it is: %@", myString);
}

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

Suppose you have data in A1:A10 and B1:B10 and you want to highlight which values in A1:A10 do not appear in B1:B10.

Try as follows:

  1. Format > Conditional Formating...
  2. Select 'Formula Is' from drop down menu
  3. Enter the following formula:

    =ISERROR(MATCH(A1,$B$1:$B$10,0))

  4. Now select the format you want to highlight the values in col A that do not appear in col B

This will highlight any value in Col A that does not appear in Col B.

Error when trying to access XAMPP from a network

This answer is for XAMPP on Ubuntu.

The manual for installation and download is on (site official)

http://www.apachefriends.org/it/xampp-linux.html

After to start XAMPP simply call this command:

sudo /opt/lampp/lampp start

You should now see something like this on your screen:

Starting XAMPP 1.8.1...
LAMPP: Starting Apache...
LAMPP: Starting MySQL...
LAMPP started.

If you have this

Starting XAMPP for Linux 1.8.1...                                                             
XAMPP: Another web server daemon is already running.                                          
XAMPP: Another MySQL daemon is already running.                                               
XAMPP: Starting ProFTPD...                                                                    
XAMPP for Linux started

. The solution is

sudo /etc/init.d/apache2 stop
sudo /etc/init.d/mysql stop

And the restast with sudo //opt/lampp/lampp restart

You to fix most of the security weaknesses simply call the following command:

/opt/lampp/lampp security

After the change this file

sudo kate //opt/lampp/etc/extra/httpd-xampp.conf

Find and replace on

    #
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
    Order deny,allow
    Deny from all
    Allow from ::1 127.0.0.0/8 
    Allow from all
    #\
    #   fc00::/7 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 \
    #   fe80::/10 169.254.0.0/16

    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

Java Class.cast() vs. cast operator

Personally, I've used this before to build a JSON to POJO converter. In the case that the JSONObject processed with the function contains an array or nested JSONObjects (implying that the data here isn't of a primitive type or String), I attempt to invoke the setter method using class.cast() in this fashion:

public static Object convertResponse(Class<?> clazz, JSONObject readResultObject) {
    ...
    for(Method m : clazz.getMethods()) {
        if(!m.isAnnotationPresent(convertResultIgnore.class) && 
            m.getName().toLowerCase().startsWith("set")) {
        ...
        m.invoke(returnObject,  m.getParameters()[0].getClass().cast(convertResponse(m.getParameters()[0].getType(), readResultObject.getJSONObject(key))));
    }
    ...
}

Not sure if this is extremely helpful, but as said here before, reflection is one of the very few legitimate use case of class.cast() I can think of, at least you have another example now.

No Title Bar Android Theme

To Hide the Action Bar add the below code in Values/Styles

<style name="CustomActivityThemeNoActionBar" parent="@android:style/Theme.Holo.Light">
    <item name="android:windowActionBar">false</item>
    <item name="android:windowNoTitle">true</item>
</style>

Then in your AndroidManifest.xml file add the below code in the required activity

<activity
        android:name="com.newbelievers.android.NBMenu"
        android:label="@string/title_activity_nbmenu"
        android:theme="@style/CustomActivityThemeNoActionBar">
</activity>

How do I deal with corrupted Git object files?

Recovering from Repository Corruption is the official answer.

The really short answer is: find uncorrupted objects and copy them.

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

Solution for the issue: deprecated gradle features were used in this build making it incompatible with gradle 6.0. android studio This provided solution worked for me.

First change the classpath in dependencies of build.gradle of your project From: classpath 'com.android.tools.build:gradle:3.3.1' To: classpath 'com.android.tools.build:gradle:3.6.1'

Then make changes in the gradle-wrapper.properties file this file exists in the Project's gradle>wrapper folder From: distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip To: distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip

Then Sync your gradle.

How to remove the underline for anchors(links)?

Don't forget to either include stylesheets using the link tag

http://www.w3schools.com/TAGS/tag_link.asp

Or enclose CSS within a style tag on your webpage.

<style>
  a { text-decoration:none; }
  p { text-decoration:underline; }
</style>

I wouldn't recommend using the underline on anything apart from links, underline is generally accepted as something that is clickable. If it isn't clickable don't underline it.

CSS basics can be picked up at w3schools

jQuery: Get the cursor position of text in input without browser specific code?

A warning about the Jquery Caret plugin.

It will conflict with the Masked Input plugin (or vice versa). Fortunately the Masked Input plugin includes a caret() function of its own, which you can use very similarly to the Caret plugin for your basic needs - $(element).caret().begin or .end

Origin <origin> is not allowed by Access-Control-Allow-Origin

In case anyone searching for the solution , if you are using express here is the quick solution .

const express = require('express')
const cors = require('cors')
const app = express()

1) install cors using npm npm install cors --save

2) import it [require ] const cors = require('cors')

3) use it as middleware app.use(cors())

for details insatll and usage of cors . That is it, hopefully it works.

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

Here's a pure CSS solution, similar to DarkBee's answer, but without the need for an extra .wrapper div:

.dimmed {
  position: relative;
}

.dimmed:after {
  content: " ";
  z-index: 10;
  display: block;
  position: absolute;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
}

I'm using rgba here, but of course you can use other transparency methods if you like.

Should methods in a Java interface be declared with or without a public access modifier?

I always write what I would use if there was no interface and I was writing a direct implementation, i.e., I would use public.

Set cursor position on contentEditable <div>

This solution works in all major browsers:

saveSelection() is attached to the onmouseup and onkeyup events of the div and saves the selection to the variable savedRange.

restoreSelection() is attached to the onfocus event of the div and reselects the selection saved in savedRange.

This works perfectly unless you want the selection to be restored when the user clicks the div aswell (which is a bit unintuitative as normally you expect the cursor to go where you click but code included for completeness)

To achieve this the onclick and onmousedown events are canceled by the function cancelEvent() which is a cross browser function to cancel the event. The cancelEvent() function also runs the restoreSelection() function because as the click event is cancelled the div doesn't receive focus and therefore nothing is selected at all unless this functions is run.

The variable isInFocus stores whether it is in focus and is changed to "false" onblur and "true" onfocus. This allows click events to be cancelled only if the div is not in focus (otherwise you would not be able to change the selection at all).

If you wish to the selection to be change when the div is focused by a click, and not restore the selection onclick (and only when focus is given to the element programtically using document.getElementById("area").focus(); or similar then simply remove the onclick and onmousedown events. The onblur event and the onDivBlur() and cancelEvent() functions can also safely be removed in these circumstances.

This code should work if dropped directly into the body of an html page if you want to test it quickly:

<div id="area" style="width:300px;height:300px;" onblur="onDivBlur();" onmousedown="return cancelEvent(event);" onclick="return cancelEvent(event);" contentEditable="true" onmouseup="saveSelection();" onkeyup="saveSelection();" onfocus="restoreSelection();"></div>
<script type="text/javascript">
var savedRange,isInFocus;
function saveSelection()
{
    if(window.getSelection)//non IE Browsers
    {
        savedRange = window.getSelection().getRangeAt(0);
    }
    else if(document.selection)//IE
    { 
        savedRange = document.selection.createRange();  
    } 
}

function restoreSelection()
{
    isInFocus = true;
    document.getElementById("area").focus();
    if (savedRange != null) {
        if (window.getSelection)//non IE and there is already a selection
        {
            var s = window.getSelection();
            if (s.rangeCount > 0) 
                s.removeAllRanges();
            s.addRange(savedRange);
        }
        else if (document.createRange)//non IE and no selection
        {
            window.getSelection().addRange(savedRange);
        }
        else if (document.selection)//IE
        {
            savedRange.select();
        }
    }
}
//this part onwards is only needed if you want to restore selection onclick
var isInFocus = false;
function onDivBlur()
{
    isInFocus = false;
}

function cancelEvent(e)
{
    if (isInFocus == false && savedRange != null) {
        if (e && e.preventDefault) {
            //alert("FF");
            e.stopPropagation(); // DOM style (return false doesn't always work in FF)
            e.preventDefault();
        }
        else {
            window.event.cancelBubble = true;//IE stopPropagation
        }
        restoreSelection();
        return false; // false = IE style
    }
}
</script>

how to send a post request with a web browser

with a form, just set method to "post"

<form action="blah.php" method="post">
  <input type="text" name="data" value="mydata" />
  <input type="submit" />
</form>

How to check if a given directory exists in Ruby

All the other answers are correct, however, you might have problems if you're trying to check directory in a user's home directory. Make sure you expand the relative path before checking:

File.exists? '~/exists'
=> false
File.directory? '~/exists'
=> false
File.exists? File.expand_path('~/exists')
=> true

Index of element in NumPy array

If you are interested in the indexes, the best choice is np.argsort(a)

a = np.random.randint(0, 100, 10)
sorted_idx = np.argsort(a)

Detecting Enter keypress on VB.NET

I had the same problem and I could not make this answer work on Framework 2.0 so I dug deeper.

You would have to first handle the PreviewKeyDown on the textbox so when ENTER came along you would set IsInputKey so that it could be handled by or forwarded to the keyDown event on the textbox. Like this:

Private Sub txtFiltro_PreviewKeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles txtFiltro.PreviewKeyDown
    Select Case e.KeyCode
        Case Keys.Enter
            e.IsInputKey = True
    End Select
 End Sub

and then you would handle the event keydown on the textbox. One of the answer was on the right track but missed setting the e.IsInputKey.

Private Sub txtFiltro_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtFiltro.KeyDown
    If e.KeyCode = Keys.Enter Then
        e.handled = True
        Textbox1.Focus()
    End If
End Sub

How to exclude subdirectories in the destination while using /mir /xd switch in robocopy

The argument order seems to matter... to exclude subdirectories, I used

robocopy \\source\folder C:\destinationfolder /XD * /MIR

...and that works for me (Windows 10 copy from Windows Server 2016)

Android: how to make an activity return results to the activity which calls it?

Your error is in resultCode = Activity.RESULT_CANCELED, you should instance like resultCode == Activity.RESULT_CANCELED ==

Column/Vertical selection with Keyboard in SublimeText 3

Alright, here's the best solution I've found that meets all the requirements:

  1. Download the Sublime-Text-Advanced-CSV Sublime plugin and install.
  2. Specify a delimiter for your column (default is ","), via the "CSV: Set Delimiter" command.
  3. Hit "ctrl + , s" (or select from Command Palette) and your column will be selected.

No need for mouse interaction whatsoever.

Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction

If you really need to do it in separate transaction you need to use REQUIRES_NEW and live with the performance overhead. Watch out for dead locks.

I'd rather do it the other way:

  • Validate data on Java side.
  • Run everyting in one transaction.
  • If anything goes wrong on DB side -> it's a major error of DB or validation design. Rollback everything and throw critical top level error.
  • Write good unit tests.

python: order a list of numbers without built-in sort, min, max function

Here's a more readable example of an in-place Insertion sort algorithm.

a = [3, 1, 5, 2, 4]

for i in a[1:]:
    j = a.index(i)
    while j > 0 and a[j-1] > a[j]:
        a[j], a[j-1] = a[j-1], a[j]
        j = j - 1

C# Threading - How to start and stop a thread

This is how I do it...

public class ThreadA {
    public ThreadA(object[] args) {
        ...
    }
    public void Run() {
        while (true) {
            Thread.sleep(1000); // wait 1 second for something to happen.
            doStuff();
            if(conditionToExitReceived) // what im waiting for...
                break;
        }
        //perform cleanup if there is any...
    }
}

Then to run this in its own thread... ( I do it this way because I also want to send args to the thread)

private void FireThread(){
    Thread thread = new Thread(new ThreadStart(this.startThread));
    thread.start();
}
private void (startThread){
    new ThreadA(args).Run();
}

The thread is created by calling "FireThread()"

The newly created thread will run until its condition to stop is met, then it dies...

You can signal the "main" with delegates, to tell it when the thread has died.. so you can then start the second one...

Best to read through : This MSDN Article

What character represents a new line in a text area

Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n will work.

If you use anything else you will cause issues with cut and paste on Windows platforms.

The line breaks will be canonicalised by windows browsers when the form is submitted, but if you send the form down to the browser with \n linebreaks, you will find that the text will not copy and paste correctly between for example notepad and the textarea.

Interestingly, in spite of the Unix line end convention being \n, the standard in most text-based network protocols including HTTP, SMTP, POP3, IMAP, and so on is still \r\n. Yes, it may not make a lot of sense, but that's history and evolving standards for you!

How to install MySQLi on MacOS

MySQLi is part of PHP. There should be a php-mysqli type package available, or you can take the PHP source and recompile that mysqli enabled. You may already have it installed, but it's done as a module and is disabled. Check your php.ini for extension=mysqli.so or similar. it may be commented out, or the .so file is present in your extensions directory but not linked to PHP via that extension= directive.

How does autowiring work in Spring?

The whole concept of inversion of control means you are free from a chore to instantiate objects manually and provide all necessary dependencies. When you annotate class with appropriate annotation (e.g. @Service) Spring will automatically instantiate object for you. If you are not familiar with annotations you can also use XML file instead. However, it's not a bad idea to instantiate classes manually (with the new keyword) in unit tests when you don't want to load the whole spring context.

Read CSV file column by column

I sugges to use the Apache Commons CSV https://commons.apache.org/proper/commons-csv/

Here is one example:

    Path currentRelativePath = Paths.get("");
    String currentPath = currentRelativePath.toAbsolutePath().toString();
    String csvFile = currentPath + "/pathInYourProject/test.csv";

    Reader in;
    Iterable<CSVRecord> records = null;
    try
    {
        in = new FileReader(csvFile);
        records = CSVFormat.EXCEL.withHeader().parse(in); // header will be ignored
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

    for (CSVRecord record : records) {
        String line = "";
        for ( int i=0; i < record.size(); i++)
        {
            if ( line == "" )
                line = line.concat(record.get(i));
            else
                line = line.concat("," + record.get(i));
        }
        System.out.println("read line: " + line);
    }

It automaticly recognize , and " but not ; (maybe it can be configured...).

My example file is:

col1,col2,col3
val1,"val2",val3
"val4",val5
val6;val7;"val8"

And output is:

read line: val1,val2,val3
read line: val4,val5
read line: val6;val7;"val8"

Last line is considered like one value.

SQL Server Jobs with SSIS packages - Failed to decrypt protected XML node "DTS:Password" with error 0x8009000B

Little late to the game but i found a way to fix this for me that i had not seen anywhere else. Select your connection from Connection Managers. On the right you should see properties. Check to see if there are any expressions there if not add one. In your package explorer add a variable called connection to sql or whatever. Set the variable as a string and set the value as your connection string and include the User Id and password. Back to the connection manager properties and expression. From the drop down select ConnectionString and set the second box as the name of your variable. It should look like this

enter image description here

I could not for the life of me find another solution but this worked!

How to compare each item in a list with the rest, only once?

I think using enumerate on the outer loop and using the index to slice the list on the inner loop is pretty Pythonic:

for index, this in enumerate(mylist):
    for that in mylist[index+1:]:
        compare(this, that)

java.math.BigInteger cannot be cast to java.lang.Long

Try to convert the BigInteger to a long like this

Long longNumber= bigIntegerNumber.longValue();

Permission is only granted to system app

Have same error from time to time (when I set install location to "prefer external" in manifest). Just clean and rebuild project. Works for me.

Token based authentication in Web API without any user interface

I think there is some confusion about the difference between MVC and Web Api. In short, for MVC you can use a login form and create a session using cookies. For Web Api there is no session. That's why you want to use the token.

You do not need a login form. The Token endpoint is all you need. Like Win described you'll send the credentials to the token endpoint where it is handled.

Here's some client side C# code to get a token:

    //using System;
    //using System.Collections.Generic;
    //using System.Net;
    //using System.Net.Http;
    //string token = GetToken("https://localhost:<port>/", userName, password);

    static string GetToken(string url, string userName, string password) {
        var pairs = new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>( "grant_type", "password" ), 
                        new KeyValuePair<string, string>( "username", userName ), 
                        new KeyValuePair<string, string> ( "Password", password )
                    };
        var content = new FormUrlEncodedContent(pairs);
        ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
        using (var client = new HttpClient()) {
            var response = client.PostAsync(url + "Token", content).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }

In order to use the token add it to the header of the request:

    //using System;
    //using System.Collections.Generic;
    //using System.Net;
    //using System.Net.Http;
    //var result = CallApi("https://localhost:<port>/something", token);

    static string CallApi(string url, string token) {
        ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
        using (var client = new HttpClient()) {
            if (!string.IsNullOrWhiteSpace(token)) {
                var t = JsonConvert.DeserializeObject<Token>(token);

                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + t.access_token);
            }
            var response = client.GetAsync(url).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }

Where Token is:

//using Newtonsoft.Json;

class Token
{
    public string access_token { get; set; }
    public string token_type { get; set; }
    public int expires_in { get; set; }
    public string userName { get; set; }
    [JsonProperty(".issued")]
    public string issued { get; set; }
    [JsonProperty(".expires")]
    public string expires { get; set; }
}

Now for the server side:

In Startup.Auth.cs

        var oAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider("self"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            // https
            AllowInsecureHttp = false
        };
        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(oAuthOptions);

And in ApplicationOAuthProvider.cs the code that actually grants or denies access:

//using Microsoft.AspNet.Identity.Owin;
//using Microsoft.Owin.Security;
//using Microsoft.Owin.Security.OAuth;
//using System;
//using System.Collections.Generic;
//using System.Security.Claims;
//using System.Threading.Tasks;

public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
    private readonly string _publicClientId;

    public ApplicationOAuthProvider(string publicClientId)
    {
        if (publicClientId == null)
            throw new ArgumentNullException("publicClientId");

        _publicClientId = publicClientId;
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        var user = await userManager.FindAsync(context.UserName, context.Password);
        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager);
        var propertyDictionary = new Dictionary<string, string> { { "userName", user.UserName } };
        var properties = new AuthenticationProperties(propertyDictionary);

        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
        // Token is validated.
        context.Validated(ticket);
    }

    public override Task TokenEndpoint(OAuthTokenEndpointContext context)
    {
        foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
        {
            context.AdditionalResponseParameters.Add(property.Key, property.Value);
        }
        return Task.FromResult<object>(null);
    }

    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        // Resource owner password credentials does not provide a client ID.
        if (context.ClientId == null)
            context.Validated();

        return Task.FromResult<object>(null);
    }

    public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
    {
        if (context.ClientId == _publicClientId)
        {
            var expectedRootUri = new Uri(context.Request.Uri, "/");

            if (expectedRootUri.AbsoluteUri == context.RedirectUri)
                context.Validated();
        }
        return Task.FromResult<object>(null);
    }

}

As you can see there is no controller involved in retrieving the token. In fact, you can remove all MVC references if you want a Web Api only. I have simplified the server side code to make it more readable. You can add code to upgrade the security.

Make sure you use SSL only. Implement the RequireHttpsAttribute to force this.

You can use the Authorize / AllowAnonymous attributes to secure your Web Api. Additionally you can add filters (like RequireHttpsAttribute) to make your Web Api more secure. I hope this helps.

Button background as transparent

Try new way to set background transparent

    android:background="?android:attr/selectableItemBackground"

Pass parameter from a batch file to a PowerShell script

Assuming your script is something like the below snippet and named testargs.ps1

param ([string]$w)
Write-Output $w

You can call this at the commandline as:

PowerShell.Exe -File C:\scripts\testargs.ps1 "Test String"

This will print "Test String" (w/o quotes) at the console. "Test String" becomes the value of $w in the script.

AngularJS : automatically detect change in model

And if you need to style your form elements according to it's state (modified/not modified) dynamically or to test whether some values has actually changed, you can use the following module, developed by myself: https://github.com/betsol/angular-input-modified

It adds additional properties and methods to the form and it's child elements. With it, you can test whether some element contains new data or even test if entire form has new unsaved data.

You can setup the following watch: $scope.$watch('myForm.modified', handler) and your handler will be called if some form elements actually contains new data or if it reversed to initial state.

Also, you can use modified property of individual form elements to actually reduce amount of data sent to a server via AJAX call. There is no need to send unchanged data.

As a bonus, you can revert your form to initial state via call to form's reset() method.

You can find the module's demo here: http://plnkr.co/edit/g2MDXv81OOBuGo6ORvdt?p=preview

Cheers!

android - how to convert int to string and place it in a EditText?

Try using String.format() :

ed = (EditText) findViewById (R.id.box); 
int x = 10; 
ed.setText(String.format("%s",x)); 

SOAP request in PHP with CURL

Tested and working!

  • with https, user & password

     <?php 
     //Data, connection, auth
     $dataFromTheForm = $_POST['fieldName']; // request data from the form
     $soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
     $soapUser = "username";  //  username
     $soapPassword = "password"; // password
    
     // xml post structure
    
     $xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
                         <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                           <soap:Body>
                             <GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
                               <PRICE>'.$dataFromTheForm.'</PRICE> 
                             </GetItemPrice >
                           </soap:Body>
                         </soap:Envelope>';   // data from the form, e.g. some ID number
    
        $headers = array(
                     "Content-type: text/xml;charset=\"utf-8\"",
                     "Accept: text/xml",
                     "Cache-Control: no-cache",
                     "Pragma: no-cache",
                     "SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice", 
                     "Content-length: ".strlen($xml_post_string),
                 ); //SOAPAction: your op URL
    
         $url = $soapUrl;
    
         // PHP cURL  for https connection with auth
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
         curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
         // converting
         $response = curl_exec($ch); 
         curl_close($ch);
    
         // converting
         $response1 = str_replace("<soap:Body>","",$response);
         $response2 = str_replace("</soap:Body>","",$response1);
    
         // convertingc to XML
         $parser = simplexml_load_string($response2);
         // user $parser to get your data out of XML response and to display it. 
     ?>
    

CSS: How to change colour of active navigation page menu

I think you are getting confused about what the a:active CSS selector does. This will only change the colour of your link when you click it (and only for the duration of the click i.e. how long your mouse button stays down). What you need to do is introduce a new class e.g. .selected into your CSS and when you select a link, update the selected menu item with new class e.g.

<div class="menuBar">
    <ul>
        <li class="selected"><a href="index.php">HOME</a></li>
        <li><a href="two.php">PORTFOLIO</a></li>
        ....
    </ul>
</div>

// specific CSS for your menu
div.menuBar li.selected a { color: #FF0000; } 
// more general CSS
li.selected a { color: #FF0000; }

You will need to update your template page to take in a selectedPage parameter.

DBNull if statement

The idiomatic way is to say:

if(rsData["usr.ursrdaystime"] != DBNull.Value) {
    strLevel = rsData["usr.ursrdaystime"].ToString();
}

This:

rsData = objCmd.ExecuteReader();
rsData.Read();

Makes it look like you're reading exactly one value. Use IDbCommand.ExecuteScalar instead.

How to execute XPath one-liners from shell?

clacke’s answer is great but I think only works if your source is well-formed XML, not normal HTML.

So to do the same for normal Web content—HTML docs that aren’t necessarily well-formed XML:

echo "<p>foo<div>bar</div><p>baz" | python -c "from sys import stdin; \
from lxml import html; \
print '\n'.join(html.tostring(node) for node in html.parse(stdin).xpath('//p'))"

And to instead use html5lib (to ensure you get the same parsing behavior as Web browsers—because like browser parsers, html5lib conforms to the parsing requirements in the HTML spec).

echo "<p>foo<div>bar</div><p>baz" | python -c "from sys import stdin; \
import html5lib; from lxml import html; \
doc = html5lib.parse(stdin, treebuilder='lxml', namespaceHTMLElements=False); \
print '\n'.join(html.tostring(node) for node in doc.xpath('//p'))

How to add Active Directory user group as login in SQL Server

Go to the SQL Server Management Studio, navigate to Security, go to Logins and right click it. A Menu will come up with a button saying "New Login". There you will be able to add users and/or groups from Active Directory to your SQL Server "permissions". Hope this helps

How to Toggle a div's visibility by using a button click

Try following logic:

<script type="text/javascript">
function showHideDiv(id) {
    var e = document.getElementById(id);
    if(e.style.display == null || e.style.display == "none") {
        e.style.display = "block";
    } else {
        e.style.display = "none";
    }
}
</script>

Import Maven dependencies in IntelliJ IDEA

The problem appears to be that despite listing your dependencies in the pom.xml, IntelliJ IDEA does not rebuild those dependencies when you run your project.

What worked for me is this:

Go to 'Run' -> 'Edit Configurations...', find your application, make sure the "Before launch:" section is expanded, click the green plus sign, and select "Build Project".

enter image description here

HttpContext.Current.User.Identity.Name is Empty

These might resolve the issue(It did for me). In IIS Express change the project property values, "Anonymous Authentication" and "Windows Authentication". To do this, when project is selected, press F4 and then change these properties.

enter image description here

In case you are deploying it on IIS locally, make sure local machines "Windows Authentication" feature is enabled and "Anonymous Authentication" is disabled.

Refer to

https://grekai.wordpress.com/2011/03/31/httpcontext-current-user-identity-name-is-empty/

iterating through Enumeration of hastable keys throws NoSuchElementException error

You're calling e.nextElement() twice inside your loop when you're only guaranteed that you can call it once without an exception. Rewrite the loop like so:

while(e.hasMoreElements()){
  String param = e.nextElement();
  System.out.println(param);
}