Programs & Examples On #Membership provider

Membership providers provide the interface between Microsoft ASP.NET's membership service and membership data sources. ASP.NET 2.0 ships with two membership providers: SqlMembershipProvider, which stores membership data in Microsoft SQL Server and SQL Server Express databases ActiveDirectoryMembershipProvider, which retrieves membership data from Microsoft Active Directory

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

Same issue. In my case I solved setting the project as the "StartUp Project".

Make an HTTP request with android

Look at this awesome new library which is available via gradle :)

build.gradle: compile 'com.apptakk.http_request:http-request:0.1.2'

Usage:

new HttpRequestTask(
    new HttpRequest("http://httpbin.org/post", HttpRequest.POST, "{ \"some\": \"data\" }"),
    new HttpRequest.Handler() {
      @Override
      public void response(HttpResponse response) {
        if (response.code == 200) {
          Log.d(this.getClass().toString(), "Request successful!");
        } else {
          Log.e(this.getClass().toString(), "Request unsuccessful: " + response);
        }
      }
    }).execute();

https://github.com/erf/http-request

Most common C# bitwise operations on enums

This was inspired by using Sets as indexers in Delphi, way back when:

/// Example of using a Boolean indexed property
/// to manipulate a [Flags] enum:

public class BindingFlagsIndexer
{
  BindingFlags flags = BindingFlags.Default;

  public BindingFlagsIndexer()
  {
  }

  public BindingFlagsIndexer( BindingFlags value )
  {
     this.flags = value;
  }

  public bool this[BindingFlags index]
  {
    get
    {
      return (this.flags & index) == index;
    }
    set( bool value )
    {
      if( value )
        this.flags |= index;
      else
        this.flags &= ~index;
    }
  }

  public BindingFlags Value 
  {
    get
    { 
      return flags;
    } 
    set( BindingFlags value ) 
    {
      this.flags = value;
    }
  }

  public static implicit operator BindingFlags( BindingFlagsIndexer src )
  {
     return src != null ? src.Value : BindingFlags.Default;
  }

  public static implicit operator BindingFlagsIndexer( BindingFlags src )
  {
     return new BindingFlagsIndexer( src );
  }

}

public static class Class1
{
  public static void Example()
  {
    BindingFlagsIndexer myFlags = new BindingFlagsIndexer();

    // Sets the flag(s) passed as the indexer:

    myFlags[BindingFlags.ExactBinding] = true;

    // Indexer can specify multiple flags at once:

    myFlags[BindingFlags.Instance | BindingFlags.Static] = true;

    // Get boolean indicating if specified flag(s) are set:

    bool flatten = myFlags[BindingFlags.FlattenHierarchy];

    // use | to test if multiple flags are set:

    bool isProtected = ! myFlags[BindingFlags.Public | BindingFlags.NonPublic];

  }
}

How to add an event after close the modal window?

I find answer. Thanks all but right answer next:

$("#myModal").on("hidden", function () {
  $('#result').html('yes,result');
});

Events here http://bootstrap-ru.com/javascript.php#modals

UPD

For Bootstrap 3.x need use hidden.bs.modal:

$("#myModal").on("hidden.bs.modal", function () {
  $('#result').html('yes,result');
});

Find which version of package is installed with pip

As of pip 1.3, there is a pip show command.

$ pip show Jinja2
---
Name: Jinja2
Version: 2.7.3
Location: /path/to/virtualenv/lib/python2.7/site-packages
Requires: markupsafe

In older versions, pip freeze and grep should do the job nicely.

$ pip freeze | grep Jinja2
Jinja2==2.7.3

Get the string representation of a DOM node

I dont think you need any complicated script for this. Just use

get_string=(el)=>el.outerHTML;

How to create a string with format?

Simple functionality is not included in Swift, expected because it's included in other languages, can often be quickly coded for reuse. Pro tip for programmers to create a bag of tricks file that contains all this reuse code.

So from my bag of tricks we first need string multiplication for use in indentation.

@inlinable func * (string: String, scalar: Int) -> String {
    let array = [String](repeating: string, count: scalar)
    return array.joined(separator: "")
}

and then the code to add commas.

extension Int {
    @inlinable var withCommas:String {
        var i = self
        var retValue:[String] = []
        while i >= 1000 {
            retValue.append(String(format:"%03d",i%1000))
            i /= 1000
        }
        retValue.append("\(i)")
        return retValue.reversed().joined(separator: ",")
    }

    @inlinable func withCommas(_ count:Int = 0) -> String {
        let retValue = self.withCommas
        let indentation = count - retValue.count
        let indent:String = indentation >= 0 ? " " * indentation : ""

        return indent + retValue
    }
}

I just wrote this last function so I could get the columns to line up.

The @inlinable is great because it takes small functions and reduces their functionality so they run faster.

You can use either the variable version or, to get a fixed column, use the function version. Lengths set less than the needed columns will just expand the field.

Now you have something that is pure Swift and does not rely on some old objective C routine for NSString.

In vb.net, how to get the column names from a datatable

' i modify the code for Datatable 

For Each c as DataColumn in dt.Columns
 For j=0 To _dataTable.Columns.Count-1
            xlWorksheet.Cells (i+1, j+1) = _dataTable.Columns(j).ColumnName
Next
Next

Hope this could be help!

How to show multiline text in a table cell

the below code works like magic to me >>

td { white-space:pre-line }

What is $@ in Bash?

Just from reading that i would have never understood that "$@" expands into a list of separate parameters. Whereas, "$*" is one parameter consisting of all the parameters added together.

If it still makes no sense do this.

http://www.thegeekstuff.com/2010/05/bash-shell-special-parameters/

How do I change the background color of the ActionBar of an ActionBarActivity using XML?

Use this, it would work.

ActionBar actionbar = getActionBar();
actionbar.setBackgroundDrawable(new ColorDrawable("color"));

Check mySQL version on Mac 10.8.5

Or just call mysql command with --version option.

mysql --version

What does "make oldconfig" do exactly in the Linux kernel makefile?

Updates an old config with new/changed/removed options.

Android: how to convert whole ImageView to Bitmap?

Have you tried:

BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();

How to unmerge a Git merge?

You can reset your branch to the state it was in just before the merge if you find the commit it was on then.

One way is to use git reflog, it will list all the HEADs you've had. I find that git reflog --relative-date is very useful as it shows how long ago each change happened.

Once you find that commit just do a git reset --hard <commit id> and your branch will be as it was before.

If you have SourceTree, you can look up the <commit id> there if git reflog is too overwhelming.

Accessing Objects in JSON Array (JavaScript)

You can loop the array with a for loop and the object properties with for-in loops.

for (var i=0; i<result.length; i++)
    for (var name in result[i]) {
        console.log("Item name: "+name);
        console.log("Source: "+result[i][name].sourceUuid);
        console.log("Target: "+result[i][name].targetUuid);
    }

Clear android application user data

Hello UdayaLakmal,

public class MyApplication extends Application {
    private static MyApplication instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    public static MyApplication getInstance(){
        return instance;
    }

    public void clearApplicationData() {
        File cache = getCacheDir();
        File appDir = new File(cache.getParent());
        if(appDir.exists()){
            String[] children = appDir.list();
            for(String s : children){
                if(!s.equals("lib")){
                    deleteDir(new File(appDir, s));
                    Log.i("TAG", "File /data/data/APP_PACKAGE/" + s +" DELETED");
                }
            }
        }
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

        return dir.delete();
    }
}

Please check this and let me know...

You can download code from here

Making heatmap from pandas DataFrame

You want matplotlib.pcolor:

import numpy as np 
from pandas import DataFrame
import matplotlib.pyplot as plt

index = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
columns = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(5, 4)), index=index, columns=columns)

plt.pcolor(df)
plt.yticks(np.arange(0.5, len(df.index), 1), df.index)
plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)
plt.show()

This gives:

Output sample

What is the Auto-Alignment Shortcut Key in Eclipse?

Auto-alignment? Lawful good?

If you mean formatting, then Ctrl+Shift+F.

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

USE YourDB
GO
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO

OR YOU CAN USE ANOTHER WAY

INSERT INTO MyTable (FirstCol, SecondCol)
VALUES 
('First',1),
('Second',2),
('Third',3),
('Fourth',4),
('Fifth',5)

python list by value not by reference

I found that we can use extend() to implement the function of copy()

a=['help', 'copyright', 'credits', 'license']
b = []
b.extend(a)
b.append("XYZ") 

Python list / sublist selection -1 weirdness

I get consistent behaviour for both instances:

>>> ls[0:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[10:-1]
[10, 11, 12, 13, 14, 15, 16, 17, 18]

Note, though, that tenth element of the list is at index 9, since the list is 0-indexed. That might be where your hang-up is.

In other words, [0:10] doesn't go from index 0-10, it effectively goes from 0 to the tenth element (which gets you indexes 0-9, since the 10 is not inclusive at the end of the slice).

Switch firefox to use a different DNS than what is in the windows.host file

It appears from your question that you already have a second set of DNS servers available that reference the development site instead of the live site.

I would suggest that you simply run a standard SOCKS proxy either on that DNS server system or on a low-end spare system and have that system configured to use the development DNS server. You can then tell Firefox to use that proxy instead of downloading pages directly.

Doing it this way, the actual DNS lookups will be done on the proxy machine and not on the machine that's running the web browser.

PHP compare time

$ThatTime ="14:08:10";
if (time() >= strtotime($ThatTime)) {
  echo "ok";
}

A solution using DateTime (that also regards the timezone).

$dateTime = new DateTime($ThatTime);
if ($dateTime->diff(new DateTime)->format('%R') == '+') {
  echo "OK";
}

http://php.net/datetime.diff

What is the maximum length of data I can put in a BLOB column in MySQL?

May or may not be accurate, but according to this site: http://www.htmlite.com/mysql003.php.

BLOB A string with a maximum length of 65535 characters.

The MySQL manual says:

The maximum size of a BLOB or TEXT object is determined by its type, but the largest value you actually can transmit between the client and server is determined by the amount of available memory and the size of the communications buffers

I think the first site gets their answers from interpreting the MySQL manual, per http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html

How do I create a table based on another table

select * into newtable from oldtable

Declare a variable in DB2 SQL

I'm coming from a SQL Server background also and spent the past 2 weeks figuring out how to run scripts like this in IBM Data Studio. Hope it helps.

CREATE VARIABLE v_lookupid INTEGER DEFAULT (4815162342); --where 4815162342 is your variable data 
  SELECT * FROM DB1.PERSON WHERE PERSON_ID = v_lookupid;
  SELECT * FROM DB1.PERSON_DATA WHERE PERSON_ID = v_lookupid;
  SELECT * FROM DB1.PERSON_HIST WHERE PERSON_ID = v_lookupid;
DROP VARIABLE v_lookupid; 

how do you view macro code in access?

You can try the following VBA code to export Macro contents directly without converting them to VBA first. Unlike Tables, Forms, Reports, and Modules, the Macros are in a container called Scripts. But they are there and can be exported and imported using SaveAsText and LoadFromText

Option Compare Database

Option Explicit

Public Sub ExportDatabaseObjects()
On Error GoTo Err_ExportDatabaseObjects

    Dim db As Database
    Dim d As Document
    Dim c As Container
    Dim sExportLocation As String

    Set db = CurrentDb()

    sExportLocation = "C:\SomeFolder\"
    Set c = db.Containers("Scripts")
    For Each d In c.Documents
        Application.SaveAsText acMacro, d.Name, sExportLocation & "Macro_" & d.Name & ".txt"
    Next d

An alternative object to use is as follows:

  For Each obj In Access.Application.CurrentProject.AllMacros
    Access.Application.SaveAsText acMacro, obj.Name, strFilePath & "\Macro_" & obj.Name & ".txt"
  Next

How to install JQ on Mac by command-line?

For CentOS, RHEL, Amazon Linux: sudo yum install jq

jquery background-color change on focus and blur

#FFFFEEE is not a correct color code. Try with #FFFFEE instead.

asp.net mvc @Html.CheckBoxFor

CheckBoxFor takes a bool, you're passing a List<CheckBoxes> to it. You'd need to do:

@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
    @Html.CheckBoxFor(m => m.EmploymentType[i].Checked, new { id = "employmentType_" + i })
    @Html.HiddenFor(m => m.EmploymentType[i].Text)
    @Html.DisplayFor(m => m.EmploymentType[i].Text)
}

Notice I've added a HiddenFor for the Text property too, otherwise you'd lose that when you posted the form, so you wouldn't know which items you'd checked.

Edit, as shown in your comments, your EmploymentType list is null when the view is served. You'll need to populate that too, by doing this in your action method:

public ActionResult YourActionMethod()
{
    CareerForm model = new CareerForm();

    model.EmploymentType = new List<CheckBox>
    {
        new CheckBox { Text = "Fulltime" },
        new CheckBox { Text = "Partly" },
        new CheckBox { Text = "Contract" }
    };

    return View(model);
}

Check If only numeric values were entered in input. (jQuery)

http://docs.jquery.com/Plugins/Validation/CustomMethods/phoneUS

Check that out. It should be just what you're looking for. A US phone validation plugin for jQuery.

If you want to do it on your own, you're going to be in for a good amount of work. Check out the isNaN() function. It tells you if it is not a number. You're also going to want to brush up on your regular expressions for validation. If you're using RegEx, you can go without isNaN(), as you'll be testing for that anyway.

How do I create a user account for basic authentication?

Right click on Computer and choose "Manage" (or go to Control Panel > Administrative Tools > Computer Management) and under "Local Users and Groups" you can add a new user. Then, give that user permission to read the directory where the site is hosted.

Note: After creating the user, be sure to edit the user and remove all roles.

npm install doesn't create node_modules directory

my problem was to copy the whole source files contains .idea directory and my webstorm terminal commands were run on the original directory of the source
I delete the .idea directory and it worked fine

How do you echo a 4-digit Unicode character in Bash?

The printf builtin (just as the coreutils' printf) knows the \u escape sequence which accepts 4-digit Unicode characters:

   \uHHHH Unicode (ISO/IEC 10646) character with hex value HHHH (4 digits)

Test with Bash 4.2.37(1):

$ printf '\u2620\n'
?

How can I get the key value in a JSON object?

When you parse the JSON representation, it'll become a JavaScript array of objects.

Because of this, you can use the .length property of the JavaScript array to see how many elements are contained, and use a for loop to enumerate it.

C# : "A first chance exception of type 'System.InvalidOperationException'"

Consider using System.Windows.Forms.Timer instead of System.Threading.Timer for a GUI application, for timers that are based on the Windows message queue instead of on dedicated threads or the thread pool.

In your scenario, for the purpose of periodic updates of UI, it seems particularly appropriate since you don't really have a background work or long calculation to perform. You just want to do periodic small tasks that have to happen on the UI thread anyway.

What is the correct JSON content type?

IANA has registered the official MIME Type for JSON as application/json.

When asked about why not text/json, Crockford seems to have said JSON is not really JavaScript nor text and also IANA was more likely to hand out application/* than text/*.

More resources:

Java Timer vs ExecutorService?

ExecutorService is newer and more general. A timer is just a thread that periodically runs stuff you have scheduled for it.

An ExecutorService may be a thread pool, or even spread out across other systems in a cluster and do things like one-off batch execution, etc...

Just look at what each offers to decide.

Reading entire html file to String?

For string operations use StringBuilder or StringBuffer classes for accumulating string data blocks. Do not use += operations for string objects. String class is immutable and you will produce a large amount of string objects upon runtime and it will affect on performance.

Use .append() method of StringBuilder/StringBuffer class instance instead.

PYODBC--Data source name not found and no default driver specified

Try below:

import pyodbc

server = 'servername'

database = 'DB'

username = 'UserName'

password = 'Password'

cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)

cursor = cnxn.cursor()


cursor.execute('SELECT * FROM Tbl')

for row in cursor:
    print('row = %r' % (row,))

Run react-native on android emulator

You can also try use "doctor" command. It will fix most cases.

npx @react-native-community/cli doctor

Form Submit jQuery does not work

Since every control element gets referenced with its name on the form element (see forms specs), controls with name "submit" will override the build-in submit function.

Which leads to the error mentioned in comments above:

Uncaught TypeError: Property 'submit' of object #<HTMLFormElement> is not a function

As in the accepted answer above the simplest solution would be to change the name of that control element.

However another solution could be to use dispatchEvent method on form element:

$("#form_id")[0].dispatchEvent(new Event('submit')); 

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

First thing, define a type or interface for your object, it will make things much more readable:

type Product = { productId: number; price: number; discount: number };

You used a tuple of size one instead of array, it should look like this:

let myarray: Product[];
let priceListMap : Map<number, Product[]> = new Map<number, Product[]>();

So now this works fine:

myarray.push({productId : 1 , price : 100 , discount : 10});
myarray.push({productId : 2 , price : 200 , discount : 20});
myarray.push({productId : 3 , price : 300 , discount : 30});
priceListMap.set(1 , this.myarray);
myarray = null;

(code in playground)

RecyclerView onClick

I'm aware there are a lot of answers, but I thought I might just provide my implementation of it as well. (Full details can be found on another question I answered).

So, to add a click listener, your inner ViewHolder class needs to implement View.OnClickListener. This is because you will set an OnClickListener to the itemView parameter of the ViewHolder's constructor. Let me show you what I mean:

public class ExampleClickViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    TextView text1, text2;

    ExampleClickViewHolder(View itemView) {
        super(itemView);

        // we do this because we want to check when an item has been clicked:
        itemView.setOnClickListener(this);

        // now, like before, we assign our View variables
        title = (TextView) itemView.findViewById(R.id.text1);
        subtitle = (TextView) itemView.findViewById(R.id.text2);
    }

    @Override
    public void onClick(View v) {
        // The user may not set a click listener for list items, in which case our listener
        // will be null, so we need to check for this
        if (mOnEntryClickListener != null) {
            mOnEntryClickListener.onEntryClick(v, getLayoutPosition());
        }
    }
}

The only other things you need to add are a custom interface for your Adapter and a setter method:

private OnEntryClickListener mOnEntryClickListener;

public interface OnEntryClickListener {
    void onEntryClick(View view, int position);
}

public void setOnEntryClickListener(OnEntryClickListener onEntryClickListener) {
    mOnEntryClickListener = onEntryClickListener;
}

So your new, click-supporting Adapter is complete.

Now, let's use it...

    ExampleClickAdapter clickAdapter = new ExampleClickAdapter(yourObjects);
    clickAdapter.setOnEntryClickListener(new ExampleClickAdapter.OnEntryClickListener() {
        @Override
        public void onEntryClick(View view, int position) {
            // stuff that will happen when a list item is clicked
        }
    });

It's basically how you would set up a normal Adapter, except that you use your setter method that you created to control what you will do when your user clicks a particular list item.

You can also look through a set of examples I made on this Gist on GitHub:

https://gist.github.com/FarbodSalamat-Zadeh/7646564f48ee708c1582c013e1de4f07

Add vertical scroll bar to panel

Panel has an AutoScroll property. Just set that property to True and the panel will automatically add a scroll bar when needed.

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

You're trying to concatenate a string and an integer, which is incorrect.

Change print(numlist.pop(2)+" has been removed") to any of these:

Explicit int to str conversion:

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

Use , instead of +:

print(numlist.pop(2), "has been removed")

String formatting:

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

How do I push a new local branch to a remote Git repository and track it too?

I think this is the simplest alias, add to your ~/.gitconfig

[alias]
  publish-branch = !git push -u origin $(git rev-parse --abbrev-ref HEAD)

You just run

git publish-branch

and... it publishes the branch

Test if a variable is a list or tuple

Not the most elegant, but I do (for Python 3):

if hasattr(instance, '__iter__') and not isinstance(instance, (str, bytes)):
    ...

This allows other iterables (like Django querysets) but excludes strings and bytestrings. I typically use this in functions that accept either a single object ID or a list of object IDs. Sometimes the object IDs can be strings and I don't want to iterate over those character by character. :)

I want to declare an empty array in java and then I want do update it but the code is not working

You can't set a number in an arbitrary place in the array without telling the array how big it needs to be. For your example: int[] array = new int[4];

Wait until ActiveWorkbook.RefreshAll finishes - VBA

I was having this same problem, and tried all the above solutions with no success. I finally solved the problem by deleting the entire query and creating a new one.

The new one had the exact same settings as the one that didn't work (literally the same query definition as I simply copied the old one).

I have no idea why this solved the problem, but it did.

Mod of negative number is melting my brain

Just add your modulus (arrayLength) to the negative result of % and you'll be fine.

Getting selected value of a combobox

You have to cast the selected item to your custom class (ComboboxItem) Try this:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
            int selectedIndex = cmb.SelectedIndex;
            string selectedText = this.comboBox1.Text;
            string selectedValue = ((ComboboxItem)cmb.SelectedItem).Value.ToString();

ComboboxItem selectedCar = (ComboboxItem)cmb.SelectedItem;
MessageBox.Show(String.Format("Index: [{0}] CarName={1}; Value={2}", selectedIndex, selectedCar.Text, selecteVal));        

}

Show/Hide Table Rows using Javascript classes

Well one way to do it would be to just put a class on the "parent" rows and remove all the ids and inline onclick attributes:

<table id="products">
    <thead>
    <tr>
        <th>Product</th>
        <th>Price</th>
        <th>Destination</th>
        <th>Updated on</th>
    </tr>
    </thead>
    <tbody>
    <tr class="parent">
        <td>Oranges</td>
        <td>100</td>
        <td><a href="#">+ On Store</a></td>
        <td>22/10</td>
    </tr>
    <tr>
        <td></td>
        <td>120</td>
        <td>City 1</td>
        <td>22/10</td>
    </tr>
    <tr>
        <td></td>
        <td>140</td>
        <td>City 2</td>
        <td>22/10</td>
    </tr>
    ...etc.
    </tbody>
</table>

And then have some CSS that hides all non-parents:

tbody tr {
    display : none;          // default is hidden
}
tr.parent {
    display : table-row;     // parents are shown
}
tr.open {
    display : table-row;     // class to be given to "open" child rows
}

That greatly simplifies your html. Note that I've added <thead> and <tbody> to your markup to make it easy to hide data rows and ignore heading rows.

With jQuery you can then simply do this:

// when an anchor in the table is clicked
$("#products").on("click","a",function(e) {
    // prevent default behaviour
    e.preventDefault();
    // find all the following TR elements up to the next "parent"
    // and toggle their "open" class
    $(this).closest("tr").nextUntil(".parent").toggleClass("open");
});

Demo: http://jsfiddle.net/CBLWS/1/

Or, to implement something like that in plain JavaScript, perhaps something like the following:

document.getElementById("products").addEventListener("click", function(e) {
    // if clicked item is an anchor
    if (e.target.tagName === "A") {
        e.preventDefault();
        // get reference to anchor's parent TR
        var row = e.target.parentNode.parentNode;
        // loop through all of the following TRs until the next parent is found
        while ((row = nextTr(row)) && !/\bparent\b/.test(row.className))
            toggle_it(row);
    }
});

function nextTr(row) {
    // find next sibling that is an element (skip text nodes, etc.)
    while ((row = row.nextSibling) && row.nodeType != 1);
    return row;
}

function toggle_it(item){ 
     if (/\bopen\b/.test(item.className))       // if item already has the class
         item.className = item.className.replace(/\bopen\b/," "); // remove it
     else                                       // otherwise
         item.className += " open";             // add it
}

Demo: http://jsfiddle.net/CBLWS/

Either way, put the JavaScript in a <script> element that is at the end of the body, so that it runs after the table has been parsed.

How to force IE to reload javascript?

Paolo's general idea (i.e. effectively changing some part of the request uri) is your best bet. However, I'd suggest using a more static value such as a version number that you update when you have changed your script file so that you can still get the performance gains of caching.

So either something like this:

<script src="/my/js/file.js?version=2.1.3" ></script>

or maybe

<script src="/my/js/file.2.1.3.js" ></script>

I prefer the first option because it means you can maintain the one file instead of having to constantly rename it (which for example maintains consistent version history in your source control). Of course either one (as I've described them) would involve updating your include statements each time, so you may want to come up with a dynamic way of doing it, such as replacing a fixed value with a dynamic one every time you deploy (using Ant or whatever).

How to Run the Procedure?

In SQL Plus:

VAR rc REFCURSOR
EXEC gokul_proc(1,'GOKUL', :rc);
print rc

Why does intellisense and code suggestion stop working when Visual Studio is open?

Intellisense did not recognized an imported namespace in my case, although I could compile the project successfully. The solution was to uncheck imported namespace on project references tab, save the project, check it again and save the project again.

How to get a certain element in a list, given the position?

Maybe not the most efficient way. But you could convert the list into a vector.

#include <list>
#include <vector>

list<Object> myList;

vector<Object> myVector(myList.begin(), myList.end());

Then access the vector using the [x] operator.

auto x = MyVector[0];

You could put that in a helper function:

#include <memory>
#include <vector>
#include <list>

template<class T>
shared_ptr<vector<T>> 
ListToVector(list<T> List) {
shared_ptr<vector<T>> Vector {
        new vector<string>(List.begin(), List.end()) }
return Vector;
}

Then use the helper funciton like this:

auto MyVector = ListToVector(Object);
auto x = MyVector[0];

Is there a GUI design app for the Tkinter / grid geometry?

Apart from the options already given in other answers, there's a current more active, recent and open-source project called pygubu.

This is the first description by the author taken from the github repository:

Pygubu is a RAD tool to enable quick & easy development of user interfaces for the python tkinter module.

The user interfaces designed are saved as XML, and by using the pygubu builder these can be loaded by applications dynamically as needed. Pygubu is inspired by Glade.


Pygubu hello world program is an introductory video explaining how to create a first project using Pygubu.

The following in an image of interface of the last version of pygubu designer on a OS X Yosemite 10.10.2:

enter image description here

I would definitely give it a try, and contribute to its development.

ant warning: "'includeantruntime' was not set"

The answer from Daniel works just perfect. Here is a sample snippet that I added to my build.xml:

<target name="compile">
    <mkdir dir="${classes.dir}"/>
    <javac srcdir="${src.dir}" destdir="${classes.dir}" includeantruntime="false">
                                                 <!--   ^^^^^^^^^^^^^^^^^^^^^^^^^  -->
        <classpath>
            <path id="application" location="${jar.dir}/${ant.project.name}.jar"/>
            <path id="junit" location="${lib.dir}/junit-4.9b2.jar"/>
        </classpath>
    </javac>
</target>

At least one JAR was scanned for TLDs yet contained no TLDs

For me I was getting the problem when deploying a geoserver WAR into tomcat 7

To fix it, I was on Java 7 and upgrading to Java 8.

This is running under a docker container. Tomcat 7.0.75 + Java 8 + Geos 2.10.2

jQuery addClass onClick

Using jQuery:

$('#Button').click(function(){
    $(this).addClass("active");
});

This way, you don't have to pollute your HTML markup with onclick handlers.

IPhone/IPad: How to get screen width programmatically?

As of iOS 9.0 there's no way to get the orientation reliably. This is the code I used for an app I design for only portrait mode, so if the app is opened in landscape mode it will still be accurate:

screenHeight = [[UIScreen mainScreen] bounds].size.height;
screenWidth = [[UIScreen mainScreen] bounds].size.width;
if (screenWidth > screenHeight) {
    float tempHeight = screenWidth;
    screenWidth = screenHeight;
    screenHeight = tempHeight;
}

Add space between two particular <td>s

you have to set cellpadding and cellspacing that's it.

<table cellpadding="5" cellspacing="5">
<tr> 
<td>One</td> 
<td>Two</td> 
<td>Three</td> 
<td>Four</td> 
</tr>
</table>

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

you can return a FileResult from your MVC action.

*********************MVC action************

    public FileResult OpenPDF(parameters)
    {
       //code to fetch your pdf byte array
       return File(pdfBytes, "application/pdf");
    }

**************js**************

Use formpost to post your data to action

    var inputTag = '<input name="paramName" type="text" value="' + payloadString + '">';
    var form = document.createElement("form");
    jQuery(form).attr("id", "pdf-form").attr("name", "pdf-form").attr("class", "pdf-form").attr("target", "_blank");
    jQuery(form).attr("action", "/Controller/OpenPDF").attr("method", "post").attr("enctype", "multipart/form-data");
    jQuery(form).append(inputTag);
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
    return false;

You need to create a form to post your data, append it your dom, post your data and remove the form your document body.

However, form post wouldn't post data to new tab only on EDGE browser. But a get request works as it's just opening new tab with a url containing query string for your action parameters.

How to make background of table cell transparent

It is possible
You just also need to apply the color to 'tbody' element as that's the table body that's been causing our trouble by peeking underneath.
table, tbody, tr, th, td{ background-color: rgba(0, 0, 0, 0.0) !important; }

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

ALTER TABLE `tbl_celebrity_rows` ADD CONSTRAINT `tbl_celebrity_rows_ibfk_1` FOREIGN KEY (`celebrity_id`) 
REFERENCES `tbl_celebrities`(`id`) ON DELETE CASCADE ON UPDATE RESTRICT;

Scroll back to the top of scrollable div

As per François Noël's answer "For those who still can't make this work, make sure that the overflowed element is displayed before using the jQuery function."

I had been working in a bootstrap modal that I repeatedly bring up with account permissions in a div that overflows on the y dimension. My problem was, I was trying to use the jquery .scrollTop(0) function and it would not work no matter how I tried to do it. I had to setup an event for the modal that didn't reset the scrollbar until the modal had stopped animating. The code that finally worked for me is here:

    $('#add-modal').on('shown.bs.modal', function (e) {
        $('div.border').scrollTop(0);
    });

Using SSH keys inside docker container

You can also link your .ssh directory between the host and the container, I don't know if this method has any security implications but it may be the easiest method. Something like this should work:

$ sudo docker run -it -v /root/.ssh:/root/.ssh someimage bash

Remember that docker runs with sudo (unless you don't), if this is the case you'll be using the root ssh keys.

How do I iterate through each element in an n-dimensional matrix in MATLAB?

As pointed out in a few other answers, you can iterate over all elements in a matrix A (of any dimension) using a linear index from 1 to numel(A) in a single for loop. There are also a couple of functions you can use: arrayfun and cellfun.

Let's first assume you have a function that you want to apply to each element of A (called my_func). You first create a function handle to this function:

fcn = @my_func;

If A is a matrix (of type double, single, etc.) of arbitrary dimension, you can use arrayfun to apply my_func to each element:

outArgs = arrayfun(fcn, A);

If A is a cell array of arbitrary dimension, you can use cellfun to apply my_func to each cell:

outArgs = cellfun(fcn, A);

The function my_func has to accept A as an input. If there are any outputs from my_func, these are placed in outArgs, which will be the same size/dimension as A.

One caveat on outputs... if my_func returns outputs of different sizes and types when it operates on different elements of A, then outArgs will have to be made into a cell array. This is done by calling either arrayfun or cellfun with an additional parameter/value pair:

outArgs = arrayfun(fcn, A, 'UniformOutput', false);
outArgs = cellfun(fcn, A, 'UniformOutput', false);

Get list of filenames in folder with Javascript

I use the following (stripped-down code) in Firefox 69.0 (on Ubuntu) to read a directory and show the image as part of a digital photo frame. The page is made in HTML, CSS, and JavaScript, and it is located on the same machine where I run the browser. The images are located on the same machine as well, so there is no viewing from "outside".

var directory = <path>;
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', directory, false); // false for synchronous request
xmlHttp.send(null);
var ret = xmlHttp.responseText;
var fileList = ret.split('\n');
for (i = 0; i < fileList.length; i++) {
    var fileinfo = fileList[i].split(' ');
    if (fileinfo[0] == '201:') {
        document.write(fileinfo[1] + "<br>");
        document.write('<img src=\"' + directory + fileinfo[1] + '\"/>');
    }
}

This requires the policy security.fileuri.strict_origin_policy to be disabled. This means it might not be a solution you want to use. In my case I deemed it ok.

How to update gradle in android studio?

For those who still have this problem (for example to switch from 2.8.0 to 2.10.0), move to the file gradle-wrapper.properties and set distributionUrl like that.

distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip

I changed 2.8.0 to 2.10.0 and don't forget to Sync after

Python truncate a long string

There's no need for a regular expression but you do want to use string formatting rather than the string concatenation in the accepted answer.

This is probably the most canonical, Pythonic way to truncate the string data at 75 characters.

>>> data = "saddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsaddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsadddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
>>> info = "{}..".format(data[:75]) if len(data) > 75 else data
>>> info
'111111111122222222223333333333444444444455555555556666666666777777777788888...'

builder for HashMap

This is something I always wanted, especially while setting up test fixtures. Finally, I decided to write a simple fluent builder of my own that could build any Map implementation - https://gist.github.com/samshu/b471f5a2925fa9d9b718795d8bbdfe42#file-mapbuilder-java

    /**
     * @param mapClass Any {@link Map} implementation type. e.g., HashMap.class
     */
    public static <K, V> MapBuilder<K, V> builder(@SuppressWarnings("rawtypes") Class<? extends Map> mapClass)
            throws InstantiationException,
            IllegalAccessException {
        return new MapBuilder<K, V>(mapClass);
    }

    public MapBuilder<K, V> put(K key, V value) {
        map.put(key, value);
        return this;
    }

    public Map<K, V> build() {
        return map;
    }

Get the current displaying UIViewController on the screen in AppDelegate.m

Way less code than all other solutions:

Objective-C version:

- (UIViewController *)getTopViewController {
    UIViewController *topViewController = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
    while (topViewController.presentedViewController) topViewController = topViewController.presentedViewController;

    return topViewController;
}

Swift 2.0 version: (credit goes to Steve.B)

func getTopViewController() -> UIViewController {
    var topViewController = UIApplication.sharedApplication().delegate!.window!!.rootViewController!
    while (topViewController.presentedViewController != nil) {
        topViewController = topViewController.presentedViewController!
    }
    return topViewController
}

Works anywhere in your app, even with modals.

SQL: Return "true" if list of records exists?

If the IN clause is a parameter (either to SP or hot-built SQL), then this can always be done:

SELECT (SELECT COUNT(1)
          FROM product_a
         WHERE product_id IN (1, 8, 100)
       ) = (number of commas in product_id as constant)

If the IN clause is a table, then this can always be done:

SELECT (SELECT COUNT(*)
          FROM product_a
         WHERE product_id IN (SELECT Products
                                FROM #WorkTable)
       ) = (SELECT COUNT(*)
              FROM #WorkTable)

If the IN clause is complex then either spool it into a table or write it twice.

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

Here is how I would do it, its an idea not bulletproof design, you need to modify it

  • The user clicks the save as PDF button
  • The server is sent a call using ajax
  • The server responds with a URL for PDF generated using HTML, I have used Apache FOP very succssfully
  • The js handling the ajax response does a location.href to point the URL send by JS and as soon as that URL loads, it sends the file using content disposition header as attachment forcing user to download the file.

HTTP POST and GET using cURL in Linux

*nix provides a nice little command which makes our lives a lot easier.

GET:

with JSON:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource

with XML:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource

POST:

For posting data:

curl --data "param1=value1&param2=value2" http://hostname/resource

For file upload:

curl --form "[email protected]" http://hostname/resource

RESTful HTTP Post:

curl -X POST -d @filename http://hostname/resource

For logging into a site (auth):

curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/

Pretty-printing the curl results:

For JSON:

If you use npm and nodejs, you can install json package by running this command:

npm install -g json

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json

If you use pip and python, you can install pjson package by running this command:

pip install pjson

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | pjson

If you use Python 2.6+, json tool is bundled within.

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | python -m json.tool

If you use gem and ruby, you can install colorful_json package by running this command:

gem install colorful_json

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | cjson

If you use apt-get (aptitude package manager of your Linux distro), you can install yajl-tools package by running this command:

sudo apt-get install yajl-tools

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource |  json_reformat

For XML:

If you use *nix with Debian/Gnome envrionment, install libxml2-utils:

sudo apt-get install libxml2-utils

Usage:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | xmllint --format -

or install tidy:

sudo apt-get install tidy

Usage:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | tidy -xml -i -

Saving the curl response to a file

curl http://hostname/resource >> /path/to/your/file

or

curl http://hostname/resource -o /path/to/your/file

For detailed description of the curl command, hit:

man curl

For details about options/switches of the curl command, hit:

curl -h

How to make unicode string with python3

In a Python 2 program that I used for many years there was this line:

ocd[i].namn=unicode(a[:b], 'utf-8')

This did not work in Python 3.

However, the program turned out to work with:

ocd[i].namn=a[:b]

I don't remember why I put unicode there in the first place, but I think it was because the name can contains Swedish letters åäöÅÄÖ. But even they work without "unicode".

What is a callback function?

Call After would be a better name than the stupid name, callback. When or if condition gets met within a function, call another function, the Call After function, the one received as argument.

Rather than hard-code an inner function within a function, one writes a function to accept an already-written Call After function as argument. The Call After might get called based on state changes detected by code in the function receiving the argument.

How do I close an Android alertdialog

If you already use positive and negative button (like I do in my project) you can use Neutral Button to close the dialog.

I also noticed that in Android version >5 the dialog is closed by clicking outside of dialog window but in older version this is not happening.

ad.setNeutralButton("CLOSE", new DialogInterface.OnClickListener(){
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // close dialog
    }
});

How to correctly save instance state of Fragments in back stack?

On the latest support library none of the solutions discussed here are necessary anymore. You can play with your Activity's fragments as you like using the FragmentTransaction. Just make sure that your fragments can be identified either with an id or tag.

The fragments will be restored automatically as long as you don't try to recreate them on every call to onCreate(). Instead, you should check if savedInstanceState is not null and find the old references to the created fragments in this case.

Here is an example:

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

    if (savedInstanceState == null) {
        myFragment = MyFragment.newInstance();
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.my_container, myFragment, MY_FRAGMENT_TAG)
                .commit();
    } else {
        myFragment = (MyFragment) getSupportFragmentManager()
                .findFragmentByTag(MY_FRAGMENT_TAG);
    }
...
}

Note however that there is currently a bug when restoring the hidden state of a fragment. If you are hiding fragments in your activity, you will need to restore this state manually in this case.

Error with multiple definitions of function

The problem is that if you include fun.cpp in two places in your program, you will end up defining it twice, which isn't valid.

You don't want to include cpp files. You want to include header files.

The header file should just have the class definition. The corresponding cpp file, which you will compile separately, will have the function definition.

fun.hpp:

#include <iostream>

class classA {
    friend void funct();
public:
    classA(int a=1,int b=2):propa(a),propb(b){std::cout<<"constructor\n";}
private:
    int propa;
    int propb;
    void outfun(){
        std::cout<<"propa="<<propa<<endl<<"propb="<<propb<< std::endl;
    }
};

fun.cpp:

#include "fun.hpp"

using namespace std;

void funct(){
    cout<<"enter funct"<<endl;
    classA tmp(1,2);
    tmp.outfun();
    cout<<"exit funct"<<endl;
}

mainfile.cpp:

#include <iostream>
#include "fun.hpp"
using namespace std;

int main(int nargin,char* varargin[]) {
    cout<<"call funct"<<endl;
    funct();
    cout<<"exit main"<<endl;
    return 0;
}

Note that it is generally recommended to avoid using namespace std in header files.

How do I install cygwin components from the command line?

Old question, but still relevant. Here is what worked for me today (6/26/16).

From the bash shell:

lynx -source rawgit.com/transcode-open/apt-cyg/master/apt-cyg > apt-cyg
install apt-cyg /bin

How to append multiple values to a list in Python

Other than the append function, if by "multiple values" you mean another list, you can simply concatenate them like so.

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a + b
[1, 2, 3, 4, 5, 6]

Could not find module FindOpenCV.cmake ( Error in configuration process)

I am using Windows and get the same error message. I find another problem which is relevant. I defined OpenCV_DIR in my path at the end of the line. However when I typed "path" in the command line, my OpenCV_DIR was not shown. I found because Windows probably has a limit on how long the path can be, it cut my OpenCV_DIR to be only part of what I defined. So I removed some other part of the path, now it works.

Reset CSS display property to default value

According to my understanding to your question, as an example: you had a style at the beginning in style sheet (ex. background-color: red), then using java script you changed it to another style (ex. background-color: green), now you want to reset the style to its original value in style sheet (background-color: red) without mentioning or even knowing its value (ex. element.style.backgroundColor = 'red')...!

If I'm correct, I have a good solution for you which is using another class name for the element:

steps:

  1. set the default styles in style sheet as usual according to your desire.
  2. define a new class name in style sheet and add the new style you want.
  3. when you want to trigger between styles, add the new class name to the element or remove it.

if you want to edit or set a new style, get the element by the new class name and edit the style as desired.

I hope this helps. Regards!

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

"inconsistent use of tabs and spaces in indentation"

I use Notepad++ and got this error.

In Notepad++ you will see that both the tab and the four spaces are the same, but when you copy your code to Python IDLE you would see the difference and the line with a tab would have more space before it than the others.

To solve the problem, I just deleted the tab before the line then added four spaces.

jQuery set radio button

Using .filter() also works, and is flexible for id, value, name:

$('input[name="cols"]').filter("[value='Site']").attr('checked', true);

(seen on this blog)

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

For me it wasn't an angular problem. Was a field of type DateTime in the DB that has a value of (0000-00-00) and my model cannot bind that property correct so I changed to a valid value like (2019-08-12).

I'm using .net core, OData v4 and MySql (EF pomelo connector)

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.

Re-order columns of table in Oracle

Since the release of Oracle 12c it is now easier to rearrange columns logically.

Oracle 12c added support for making columns invisible and that feature can be used to rearrange columns logically.

Quote from the documentation on invisible columns:

When you make an invisible column visible, the column is included in the table's column order as the last column.

Example

Create a table:

CREATE TABLE t (
    a INT,
    b INT,
    d INT,
    e INT
);

Add a column:

ALTER TABLE t ADD (c INT);

Move the column to the middle:

ALTER TABLE t MODIFY (d INVISIBLE, e INVISIBLE);
ALTER TABLE t MODIFY (d VISIBLE, e VISIBLE);

DESCRIBE t;

Name
----
A
B
C
D
E

Credits

I learned about this from an article by Tom Kyte on new features in Oracle 12c.

NPM doesn't install module dependencies

happens with old node version. use latest version of node like this:

$ nvm use 8.0
$ rm -rf node_modules
$ npm install
$ npm i somemodule

edit: also make sure you save.
eg: npm install yourmoduleName --save

How do I search for files in Visual Studio Code?

If using vscodevim extension, ctrl + p won't work so I saw another answer using:

ctrl + shift + p

which opens the command palette. Hit backspace to remove the '>' and then start typing your filename.

Send private messages to friends

This thread says you can't do send private messages to a group of friends on facebook but I found this https://developers.facebook.com/docs/sharing/reference/send-dialog

Taking multiple inputs from user in python

You could use the below to take multiple inputs separated by a keyword

a,b,c=raw_input("Please enter the age of 3 people in one line using commas\n").split(',')

Showing an image from console in Python

If you would like to show it in a new window, you could use Tkinter + PIL library, like so:

import tkinter as tk
from PIL import ImageTk, Image

def show_imge(path):
    image_window = tk.Tk()
    img = ImageTk.PhotoImage(Image.open(path))
    panel = tk.Label(image_window, image=img)
    panel.pack(side="bottom", fill="both", expand="yes")
    image_window.mainloop()

This is a modified example that can be found all over the web.

Android – Listen For Incoming SMS Messages

In case you want to handle intent on opened activity, you can use PendintIntent (Complete steps below):

public class SMSReciver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        final Bundle bundle = intent.getExtras();
        try {
            if (bundle != null) {
                final Object[] pdusObj = (Object[]) bundle.get("pdus");
                for (int i = 0; i < pdusObj.length; i++) {
                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();
                    String senderNum = phoneNumber;
                    String message = currentMessage.getDisplayMessageBody();
                    try {
                        if (senderNum.contains("MOB_NUMBER")) {
                            Toast.makeText(context,"",Toast.LENGTH_SHORT).show();

                            Intent intentCall = new Intent(context, MainActivity.class);
                            intentCall.putExtra("message", currentMessage.getMessageBody());

                            PendingIntent pendingIntent= PendingIntent.getActivity(context, 0, intentCall, PendingIntent.FLAG_UPDATE_CURRENT);
                            pendingIntent.send();
                        }
                    } catch (Exception e) {
                    }
                }
            }
        } catch (Exception e) {
        }
    }
} 

manifest:

<activity android:name=".MainActivity"
            android:launchMode="singleTask"/>
<receiver android:name=".SMSReciver">
            <intent-filter android:priority="1000">
                <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>
        </receiver>

onNewIntent:

 @Override
         protected void onNewIntent(Intent intent) {
                super.onNewIntent(intent);
                Toast.makeText(this, "onNewIntent", Toast.LENGTH_SHORT).show();

                onSMSReceived(intent.getStringExtra("message"));

            }

permissions:

<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />

SELECT *, COUNT(*) in SQLite

SELECT *, COUNT(*) FROM my_table is not what you want, and it's not really valid SQL, you have to group by all the columns that's not an aggregate.

You'd want something like

SELECT somecolumn,someothercolumn, COUNT(*) 
   FROM my_table 
GROUP BY somecolumn,someothercolumn

Display filename before matching line

No trick necessary.

grep --with-filename 'pattern' file

With line numbers:

grep -n --with-filename 'pattern' file

How to call javascript function on page load in asp.net

Place this line before the closing script tag,writing from memory:

window.onload  = GetTimeZoneOffset;

i think the question is how to call the javascript function on pageload

How to specify HTTP error code?

I would recommend handling the sending of http error codes by using the Boom package.

Get first and last day of month using threeten, LocalDate

 LocalDate monthstart = LocalDate.of(year,month,1);
 LocalDate monthend = monthstart.plusDays(monthstart.lengthOfMonth()-1);

convert date string to mysql datetime field

If these strings are currently in the db, you can skip php by using mysql's STR_TO_DATE() function.

I assume the strings use a format like month/day/year where month and day are always 2 digits, and year is 4 digits.

UPDATE some_table
   SET new_column = STR_TO_DATE(old_column, '%m/%d/%Y')

You can support other date formats by using other format specifiers.

How to convert enum names to string in c

A function like that without validating the enum is a trifle dangerous. I suggest using a switch statement. Another advantage is that this can be used for enums that have defined values, for example for flags where the values are 1,2,4,8,16 etc.

Also put all your enum strings together in one array:-

static const char * allEnums[] = {
    "Undefined",
    "apple",
    "orange"
    /* etc */
};

define the indices in a header file:-

#define ID_undefined       0
#define ID_fruit_apple     1
#define ID_fruit_orange    2
/* etc */

Doing this makes it easier to produce different versions, for example if you want to make international versions of your program with other languages.

Using a macro, also in the header file:-

#define CASE(type,val) case val: index = ID_##type##_##val; break;

Make a function with a switch statement, this should return a const char * because the strings static consts:-

const char * FruitString(enum fruit e){

    unsigned int index;

    switch(e){
        CASE(fruit, apple)
        CASE(fruit, orange)
        CASE(fruit, banana)
        /* etc */
        default: index = ID_undefined;
    }
    return allEnums[index];
}

If programming with Windows then the ID_ values can be resource values.

(If using C++ then all the functions can have the same name.

string EnumToString(fruit e);

)

How to make layout with rounded corners..?

Function for set corner radius programmatically

static void setCornerRadius(GradientDrawable drawable, float topLeft,
        float topRight, float bottomRight, float bottomLeft) {
    drawable.setCornerRadii(new float[] { topLeft, topLeft, topRight, topRight,
            bottomRight, bottomRight, bottomLeft, bottomLeft });
}

static void setCornerRadius(GradientDrawable drawable, float radius) {
    drawable.setCornerRadius(radius);
}

Using

GradientDrawable gradientDrawable = new GradientDrawable();
gradientDrawable.setColor(Color.GREEN);
setCornerRadius(gradientDrawable, 20f);
//or setCornerRadius(gradientDrawable, 20f, 40f, 60f, 80f); 

view.setBackground(gradientDrawable);

Specify system property to Maven project

I have learned it is also possible to do this with the exec-maven-plugin if you're doing a "standalone" java app.

            <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>${maven.exec.plugin.version}</version>
            <executions>
                <execution>
                    <goals>
                        <goal>java</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <mainClass>${exec.main-class}</mainClass>
                <systemProperties>
                    <systemProperty>
                        <key>myproperty</key>
                        <value>myvalue</value>
                    </systemProperty>
                </systemProperties>
            </configuration>
        </plugin>

good postgresql client for windows?

I recommend Navicat strongly. What I found particularly excellent are it's import functions - you can import almost any data format (Access, Excel, DBF, Lotus ...), define a mapping between the source and destination which can be saved and is repeatable (I even keep my mappings under version control).

I have tried SQLMaestro and found it buggy (particularly for data import); PGAdmin is limited.

How to read PDF files using Java?

with Apache PDFBox it goes like this:

PDDocument document = PDDocument.load(new File("test.pdf"));
if (!document.isEncrypted()) {
    PDFTextStripper stripper = new PDFTextStripper();
    String text = stripper.getText(document);
    System.out.println("Text:" + text);
}
document.close();

Collection was modified; enumeration operation may not execute in ArrayList

I agree with several of the points I've read in this post and I've incorporated them into my solution to solve the exact same issue as the original posting.

That said, the comments I appreciated are:

  • "unless you are using .NET 1.0 or 1.1, use List<T> instead of ArrayList. "

  • "Also, add the item(s) to be deleted to a new list. Then go through and delete those items." .. in my case I just created a new List and the populated it with the valid data values.

e.g.

private List<string> managedLocationIDList = new List<string>();
string managedLocationIDs = ";1321;1235;;" // user input, should be semicolon seperated list of values

managedLocationIDList.AddRange(managedLocationIDs.Split(new char[] { ';' }));
List<string> checkLocationIDs = new List<string>();

// Remove any duplicate ID's and cleanup the string holding the list if ID's
Functions helper = new Functions();
checkLocationIDs = helper.ParseList(managedLocationIDList);

...
public List<string> ParseList(List<string> checkList)
{
    List<string> verifiedList = new List<string>();

    foreach (string listItem in checkList)
    if (!verifiedList.Contains(listItem.Trim()) && listItem != string.Empty)
        verifiedList.Add(listItem.Trim());

    verifiedList.Sort();
    return verifiedList;
}        

SQL query to check if a name begins and ends with a vowel

You can try one simple solution for MySQL:

SELECT DISTINCT city FROM station WHERE city REGEXP "^[aeiou].*[aeiou]$";

Comparing two hashmaps for equal values and same key sets?

Simply use :

mapA.equals(mapB);

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings

What is the iPad user agent?

I think it is worth mentioning that you don't generally need to use the whole agent string, unless perhaps you find a reason where you need to tailor the website to a specific model.

You can check for iPhone, iPad and iPod in the agent string and cover all your bases.

if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
    appleMobileDevice = true;
}
else {
    appleMobileDevice = false;
}

How do you add multi-line text to a UIButton?

The selected answer is correct but if you prefer to do this sort of thing in Interface Builder you can do this:

pic

Table with table-layout: fixed; and how to make one column wider

You could just give the first cell (therefore column) a width and have the rest default to auto

_x000D_
_x000D_
table {_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
}_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
  width: 150px;_x000D_
}_x000D_
td+td {_x000D_
  width: auto;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>150px</td>_x000D_
    <td>equal</td>_x000D_
    <td>equal</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_


or alternatively the "proper way" to get column widths might be to use the col element itself

_x000D_
_x000D_
table {_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
}_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
}_x000D_
.wide {_x000D_
  width: 150px;_x000D_
}
_x000D_
<table>_x000D_
  <col span="1" class="wide">_x000D_
    <tr>_x000D_
      <td>150px</td>_x000D_
      <td>equal</td>_x000D_
      <td>equal</td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How do I pass a variable by reference?

Since your example happens to be object-oriented, you could make the following change to achieve a similar result:

class PassByReference:
    def __init__(self):
        self.variable = 'Original'
        self.change('variable')
        print(self.variable)

    def change(self, var):
        setattr(self, var, 'Changed')

# o.variable will equal 'Changed'
o = PassByReference()
assert o.variable == 'Changed'

How to change border color of textarea on :focus

.input:focus {
    outline: none !important;
    border:1px solid red;
    box-shadow: 0 0 10px #719ECE;
}

What does (function($) {})(jQuery); mean?

Just small addition to explanation

This structure (function() {})(); is called IIFE (Immediately Invoked Function Expression), it will be executed immediately, when the interpreter will reach this line. So when you're writing these rows:

(function($) {
  // do something
})(jQuery);

this means, that the interpreter will invoke the function immediately, and will pass jQuery as a parameter, which will be used inside the function as $.

How to convert numbers to words without using num2word library?

Convert numbers to words:
Here is an example in which numbers have been converted into words using the dictionary.

string = input("Enter a string: ")
my_dict = {'0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine'}
for item in string:
  if item in my_dict.keys():
    string = string.replace(item, my_dict[item])
print(string)

Output

Right way to convert data.frame to a numeric matrix, when df also contains strings?

Here is an alternative way if the data frame just contains numbers.

_x000D_
_x000D_
apply(as.matrix.noquote(SFI),2,as.numeric)
_x000D_
_x000D_
_x000D_

but the most reliable way of converting a data frame to a matrix is using data.matrix() function.

How to use SVG markers in Google Maps API v3

You need to pass optimized: false.

E.g.

var img = { url: 'img/puff.svg', scaledSide: new google.maps.Size(5, 5) };
new google.maps.Marker({position: this.mapOptions.center, map: this.map, icon: img, optimized: false,});

Without passing optimized: false, my svg appeared as a static image.

Reading Space separated input in python

If you have it in a string, you can use .split() to separate them.

>>> for string in ('Mike 18', 'Kevin 35', 'Angel 56'):
...   l = string.split()
...   print repr(l[0]), repr(int(l[1]))
...
'Mike' 18
'Kevin' 35
'Angel' 56
>>>

Fake "click" to activate an onclick method

If you're using JQuery you can do:

$('#elementid').click();

Simple C example of doing an HTTP POST and consuming the response

After weeks of research. I came up with the following code. I believe this is the bare minimum needed to make a secure connection with SSL to a web server.

#include <stdio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/bio.h>

#define APIKEY "YOUR_API_KEY"
#define HOST "YOUR_WEB_SERVER_URI"
#define PORT "443"

int main() {

    //
    //  Initialize the variables
    //
    BIO* bio;
    SSL* ssl;
    SSL_CTX* ctx;

    //
    //   Registers the SSL/TLS ciphers and digests.
    //
    //   Basically start the security layer.
    //
    SSL_library_init();

    //
    //  Creates a new SSL_CTX object as a framework to establish TLS/SSL
    //  or DTLS enabled connections
    //
    ctx = SSL_CTX_new(SSLv23_client_method());

    //
    //  -> Error check
    //
    if (ctx == NULL)
    {
        printf("Ctx is null\n");
    }

    //
    //   Creates a new BIO chain consisting of an SSL BIO
    //
    bio = BIO_new_ssl_connect(ctx);

    //
    //  Use the variable from the beginning of the file to create a 
    //  string that contains the URL to the site that you want to connect
    //  to while also specifying the port.
    //
    BIO_set_conn_hostname(bio, HOST ":" PORT);

    //
    //   Attempts to connect the supplied BIO
    //
    if(BIO_do_connect(bio) <= 0)
    {
        printf("Failed connection\n");
        return 1;
    }
    else
    {
        printf("Connected\n");
    }

    //
    //  The bare minimum to make a HTTP request.
    //
    char* write_buf = "POST / HTTP/1.1\r\n"
                      "Host: " HOST "\r\n"
                      "Authorization: Basic " APIKEY "\r\n"
                      "Connection: close\r\n"
                      "\r\n";

    //
    //   Attempts to write len bytes from buf to BIO
    //
    if(BIO_write(bio, write_buf, strlen(write_buf)) <= 0)
    {
        //
        //  Handle failed writes here
        //
        if(!BIO_should_retry(bio))
        {
            // Not worth implementing, but worth knowing.
        }

        //
        //  -> Let us know about the failed writes
        //
        printf("Failed write\n");
    }

    //
    //  Variables used to read the response from the server
    //
    int size;
    char buf[1024];

    //
    //  Read the response message
    //
    for(;;)
    {
        //
        //  Get chunks of the response 1023 at the time.
        //
        size = BIO_read(bio, buf, 1023);

        //
        //  If no more data, then exit the loop
        //
        if(size <= 0)
        {
            break;
        }

        //
        //  Terminate the string with a 0, to let know C when the string 
        //  ends.
        //
        buf[size] = 0;

        //
        //  ->  Print out the response
        //
        printf("%s", buf);
    }

    //
    //  Clean after ourselves
    //
    BIO_free_all(bio);
    SSL_CTX_free(ctx);

    return 0;
}

The code above will explain in details how to establish a TLS connection with a remote server.

Important note: this code doesn't check if the public key was signed by a valid authority. Meaning I don't use root certificates for validation. Don't forget to implement this check otherwise you won't know if you are connecting the right website

When it comes to the request itself. It is nothing more then writing the HTTP request by hand.

You can also find under this link an explanation how to instal openSSL in your system, and how to compile the code so it uses the secure library.

ENOENT, no such file or directory

Another possibility is that you are missing an .npmrc file if you are pulling any packages that are not publicly available.

You will need to add an .npmrc file at the root directory and add the private/internal registry inside of the .npmrc file like this:

registry=http://private.package.source/secret/npm-packages/

DB query builder toArray() laravel 4

You can do this using the query builder. Just use SELECT instead of TABLE and GET.

DB::select('select * from user where name = ?',['Jhon']);

Notes: 1. Multiple question marks are allowed. 2. The second parameter must be an array, even if there is only one parameter. 3. Laravel will automatically clean parameters, so you don't have to.

Further info here: http://laravel.com/docs/5.0/database#running-queries

Hmmmmmm, turns out that still returns a standard class for me when I don't use a where clause. I found this helped:

foreach($results as $result)
{
print_r(get_object_vars($result));
}

However, get_object_vars isn't recursive, so don't use it on $results.

PHP post_max_size overrides upload_max_filesize

The normal method to send a file upload is POST, thus also post_max_size should be 16 Mb or more.

Incidentally, also memory_limit plays a role. It should be bigger than 16Mb, but since the default value is 128Mb, you won't see this problem. Example php.ini configuration:

post_max_size = 16M
upload_max_filesize = 16M
memory_limit = 128M

Change these value in php.ini if you've access to it, otherwise you can try to change them in an .htaccess file.

php_value upload_max_filesize 16M
php_value post_max_size 16M 

This will work only if the AllowOverride settings permit it. Otherwise, you've to ask to your hosting company.

intellij idea - Error: java: invalid source release 1.9

Alternatively via Project Settings:

  • Project Settings
  • Project
  • Project language Level (set to fit your needs)

Depending on how your build is set up, this may be the way to go.

How to repair a serialized string which has been corrupted by an incorrect byte count length?

There's another reason unserialize() failed because you improperly put serialized data into the database see Official Explanation here. Since serialize() returns binary data and php variables don't care encoding methods, so that putting it into TEXT, VARCHAR() will cause this error.

Solution: store serialized data into BLOB in your table.

Change drawable color programmatically

Simply use

    android:drawableTint="@color/primary_color"

in Your XML file. Replace primary_color to custom color

What is the difference between encode/decode?

anUnicode.encode('encoding') results in a string object and can be called on a unicode object

aString.decode('encoding') results in an unicode object and can be called on a string, encoded in given encoding.


Some more explanations:

You can create some unicode object, which doesn't have any encoding set. The way it is stored by Python in memory is none of your concern. You can search it, split it and call any string manipulating function you like.

But there comes a time, when you'd like to print your unicode object to console or into some text file. So you have to encode it (for example - in UTF-8), you call encode('utf-8') and you get a string with '\u<someNumber>' inside, which is perfectly printable.

Then, again - you'd like to do the opposite - read string encoded in UTF-8 and treat it as an Unicode, so the \u360 would be one character, not 5. Then you decode a string (with selected encoding) and get brand new object of the unicode type.

Just as a side note - you can select some pervert encoding, like 'zip', 'base64', 'rot' and some of them will convert from string to string, but I believe the most common case is one that involves UTF-8/UTF-16 and string.

Professional jQuery based Combobox control?

Unfortunately, the best thing I have seen is the jquery.combobox, but it doesn't really look like something I'd really want to use in my web applications. I think there are some usability issues with this control, but as a user I don't think I'd know to start typing for the dropdownlist to turn into a textbox.

I much prefer the Combo Dropdown Box, but it still has some features that I'd want and it's still in alpha. The only think I don't like about this other than its being alpha... is that once I type in the combobox, the original dropdownlist items disappear. However, maybe there is a setting for this... or maybe it could be added fairly easily.

Those are the only two options that I know of. Good luck in your search. I'd love to hear if you find one or if the second option works out for you.

Class has been compiled by a more recent version of the Java Environment

Your JDK version: Java 8
Your JRE version: Java 9

Here your JRE version is different than the JDK version that's the case. Here you can compile all the java classes using JDK version 1.8. If you want to compile only one java class just change the *.java into <yourclassname>.java

javac -source 1.8 -target 1.8  *.java

source: The version that your source code requires to compile.
target: The oldest JRE version you want to support.

File Upload without Form

You can use FormData to submit your data by a POST request. Here is a simple example:

var myFormData = new FormData();
myFormData.append('pictureFile', pictureInput.files[0]);

$.ajax({
  url: 'upload.php',
  type: 'POST',
  processData: false, // important
  contentType: false, // important
  dataType : 'json',
  data: myFormData
});

You don't have to use a form to make an ajax request, as long as you know your request setting (like url, method and parameters data).

Preserve line breaks in angularjs

Well it depends, if you want to bind datas, there shouldn't be any formatting in it, otherwise you can bind-html and do description.replace(/\\n/g, '<br>') not sure it's what you want though.

Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

These are different Form content types defined by W3C. If you want to send simple text/ ASCII data, then x-www-form-urlencoded will work. This is the default.

But if you have to send non-ASCII text or large binary data, the form-data is for that.

You can use Raw if you want to send plain text or JSON or any other kind of string. Like the name suggests, Postman sends your raw string data as it is without modifications. The type of data that you are sending can be set by using the content-type header from the drop down.

Binary can be used when you want to attach non-textual data to the request, e.g. a video/audio file, images, or any other binary data file.

Refer to this link for further reading: Forms in HTML documents

Close all infowindows in Google Maps API v3

When dealing with marker clusters this one worked for me.

var infowindow = null;

google.maps.event.addListener(marker, "click", function () {

        if (infowindow) {
            infowindow.close();
        }
        var markerMap = this.getMap();
        infowindow = this.info;
        this.info.open(markerMap, this);


    });

FirstOrDefault returns NullReferenceException if no match is found

That is because FirstOrDefaultcan return null causing your following .Value to cause the exception. You need to change it to something like:

var myThing = things.FirstOrDefault(t => t.Id == idToFind);

if(myThing == null)
    return; // we failed to find what we wanted
var displayName = myThing.DisplayName;

Testing web application on Mac/Safari when I don't own a Mac

https://turbo.net/ offers a browser sandbox in which containerised virtual machines run browser sessions for you. I tried it with Safari on my Windows development machine and it seems to work very well.

importing go files in same folder

No import is necessary as long as you declare both a.go and b.go to be in the same package. Then, you can use go run to recognize multiple files with:

$ go run a.go b.go

What's the difference between align-content and align-items?

align-content

align-content controls the cross-axis (i.e. vertical direction if the flex-direction is row, and horizontal if the flex-direction is column) positioning of multiple lines relative to each other.

(Think lines of a paragraph being vertically spread out, stacked toward the top, stacked toward the bottom. This is under a flex-direction row paradigm).

align-items

align-items controls the cross-axis of an individual line of flex elements.

(Think how an individual line of a paragraph is aligned, if it contains some normal text and some taller text like math equations. In that case, will it be the bottom, top, or center of each type of text in a line that will be aligned?)

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

I used this tutorial to create my maven web project http://crunchify.com/how-to-create-dynamic-web-project-using-maven-in-eclipse/ and eclipse did not create src/main/java folder for me. When i tired to create the source folder src/main/java eclipse did not let me. So i created the folder outside eclipse in the project directly and then src/main/java appeared in eclipse.

MySql server startup error 'The server quit without updating PID file '

try to find your log file with suffix ".err", there should be more info. It might be in:

/usr/local/var/mysql/your_computer_name.local.err

It's probably problem with permissions

  1. check if any mysql instance is running

    ps -ef | grep mysql

    if yes, you should stop it, or kill the process

    kill -9 PID

    where PID is the number displayed next to username on output of previous command

  2. check ownership of /usr/local/var/mysql/

    ls -laF /usr/local/var/mysql/

    if it is owner by root you should change it mysql or your_user

    sudo chown -R mysql /usr/local/var/mysql/

Can an abstract class have a constructor?

You would define a constructor in an abstract class if you are in one of these situations:

  • you want to perform some initialization (to fields of the abstract class) before the instantiation of a subclass actually takes place
  • you have defined final fields in the abstract class but you did not initialize them in the declaration itself; in this case, you MUST have a constructor to initialize these fields

Note that:

  • you may define more than one constructor (with different arguments)
  • you can (should?) define all your constructors protected (making them public is pointless anyway)
  • your subclass constructor(s) can call one constructor of the abstract class; it may even have to call it (if there is no no-arg constructor in the abstract class)

In any case, don't forget that if you don't define a constructor, then the compiler will automatically generate one for you (this one is public, has no argument, and does nothing).

Disabling of EditText in Android

Set this in your XML code, It works.

android:focusableInTouchMode="false"

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

If both your client and service is installed on the same machine, and you are facing this problem with the correct (read: tried and tested elsewhere) client and service configurations, then this might be worth checking.

Check host entries in your host file

%windir%/system32/drivers/etc/hosts

Check to see if you are accessing your web service with a hostname, and that same hostname has been associated with an IP address in the hosts file mentioned above. If yes, NTLM/Windows credentials will NOT be passed from the client to the service as any request for that hostname will be routed again at the machine level.

Try either of the following

  • Remove the host entry of that hostname from the hosts file
  • OR
  • If removing host entry is not possible, then try accessing your service with another hostname. You might also try with IP address instead of hostname

Edit: Somehow the above situation is relevant on a load-balanced scenario. However, if removing the host entries is not possible, then disabling loop back check on the machine will help. Refer method 2 in the article https://support.microsoft.com/en-us/kb/896861

What is the total amount of public IPv4 addresses?

https://www.ripe.net/internet-coordination/press-centre/understanding-ip-addressing

For IPv4, this pool is 32-bits (2³²) in size and contains 4,294,967,296 IPv4 addresses.

In case of IPv6

The IPv6 address space is 128-bits (2¹²8) in size, containing 340,282,366,920,938,463,463,374,607,431,768,211,456 IPv6 addresses.

inclusive of RESERVED IP

 Reserved address blocks
 Range  Description Reference

 0.0.0.0/8  Current network (only valid as source address)  RFC 6890
 10.0.0.0/8 Private network RFC 1918
 100.64.0.0/10  Shared Address Space    RFC 6598
 127.0.0.0/8    Loopback    RFC 6890
 169.254.0.0/16 Link-local  RFC 3927
 172.16.0.0/12  Private network RFC 1918
 192.0.0.0/24   IETF Protocol Assignments   RFC 6890
 192.0.2.0/24   TEST-NET-1, documentation and examples  RFC 5737
 192.88.99.0/24 IPv6 to IPv4 relay (includes 2002::/16) RFC 3068
 192.168.0.0/16 Private network RFC 1918
 198.18.0.0/15  Network benchmark tests RFC 2544
 198.51.100.0/24    TEST-NET-2, documentation and examples  RFC 5737
 203.0.113.0/24 TEST-NET-3, documentation and examples  RFC 5737
 224.0.0.0/4    IP multicast (former Class D network)   RFC 5771
 240.0.0.0/4    Reserved (former Class E network)   RFC 1700
 255.255.255.255    Broadcast   RFC 919

wiki has full details and this has details of IPv6.

Simplest way to do grouped barplot

There are several ways to do plots in R; lattice is one of them, and always a reasonable solution, +1 to @agstudy. If you want to do this in base graphics, you could try the following:

Reasonstats <- read.table(text="Category         Reason  Species
                                 Decline        Genuine       24
                                Improved        Genuine       16
                                Improved  Misclassified       85
                                 Decline  Misclassified       41
                                 Decline      Taxonomic        2
                                Improved      Taxonomic        7
                                 Decline        Unclear       41
                                Improved        Unclear      117", header=T)

ReasonstatsDec <- Reasonstats[which(Reasonstats$Category=="Decline"),]
ReasonstatsImp <- Reasonstats[which(Reasonstats$Category=="Improved"),]
Reasonstats3   <- cbind(ReasonstatsImp[,3], ReasonstatsDec[,3])
colnames(Reasonstats3) <- c("Improved", "Decline")
rownames(Reasonstats3) <- ReasonstatsImp$Reason

windows()
  barplot(t(Reasonstats3), beside=TRUE, ylab="number of species", 
          cex.names=0.8, las=2, ylim=c(0,120), col=c("darkblue","red"))
  box(bty="l")

enter image description here

Here's what I did: I created a matrix with two columns (because your data were in columns) where the columns were the species counts for Decline and for Improved. Then I made those categories the column names. I also made the Reasons the row names. The barplot() function can operate over this matrix, but wants the data in rows rather than columns, so I fed it a transposed version of the matrix. Lastly, I deleted some of your arguments to your barplot() function call that were no longer needed. In other words, the problem was that your data weren't set up the way barplot() wants for your intended output.

how does Request.QueryString work?

A query string is an array of parameters sent to a web page.

This url: http://page.asp?x=1&y=hello

Request.QueryString[0] is the same as 
Request.QueryString["x"] and holds a string value "1"

Request.QueryString[1] is the same as 
Request.QueryString["y"] and holds a string value "hello"

Drop multiple columns in pandas

You don't need to wrap it in a list with [..], just provide the subselection of the columns index:

df.drop(df.columns[[1, 69]], axis=1, inplace=True)

as the index object is already regarded as list-like.

Pass entire form as data in jQuery Ajax function

The other solutions didn't work for me. Maybe the old DOCTYPE in the project I am working on prevents HTML5 options.

My solution:

<form id="form_1" action="result.php" method="post"
 onsubmit="sendForm(this.id);return false">
    <input type="hidden" name="something" value="1">
</form>

js:

function sendForm(form_id){
    var form = $('#'+form_id);
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: $(form).serialize(),
        success: function(result) {
            console.log(result)
        }
    });
}

Difference between FetchType LAZY and EAGER in Java Persistence API?

Both FetchType.LAZY and FetchType.EAGER are used to define the default fetch plan.

Unfortunately, you can only override the default fetch plan for LAZY fetching. EAGER fetching is less flexible and can lead to many performance issues.

My advice is to restrain the urge of making your associations EAGER because fetching is a query-time responsibility. So all your queries should use the fetch directive to only retrieve what's necessary for the current business case.

PHP Unset Session Variable

// set
$_SESSION['test'] = 1;

// destroy
unset($_SESSION['test']);

How to close IPython Notebook properly?

There isn't currently a better way to do it than Ctrl+C in the terminal.

We're thinking about how to have an explicit shutdown, but there's some tension between the notebook as a single-user application, where the user is free to stop it, and as a multi-user server, where only an admin should be able to stop it. We haven't quite worked out how to handle the differences yet.

(For future readers, this is the situation with 0.12 released and 0.13 in development.)

Update December 2017

The IPython Notebook has become the Jupyter Notebook. A recent version has added a jupyter notebook stop shell command which will shut down a server running on that system. You can pass the port number at the command line if it's not the default port 8888.

You can also use nbmanager, a desktop application which can show running servers and shut them down.

Finally, we are working on adding:

  • A config option to automatically shut down the server if you don't use it for a specified time.
  • A button in the user interface to shut the server down. (We know it's a bit crazy that it has taken this long. Changing UI is controversial.)

Http Post request with content type application/x-www-form-urlencoded not working in Spring

Remove @ResponseBody annotation from your use parameters in method. Like this;

   @Autowired
    ProjectService projectService;

    @RequestMapping(path = "/add", method = RequestMethod.POST)
    public ResponseEntity<Project> createNewProject(Project newProject){
        Project project = projectService.save(newProject);

        return new ResponseEntity<Project>(project,HttpStatus.CREATED);
    }

How to center HTML5 Videos?

Do this:

<video style="display:block; margin: 0 auto;" controls>....</video>

Works perfect! :D

Rewrite URL after redirecting 404 error htaccess

Put this code in your .htaccess file

RewriteEngine On
ErrorDocument 404 /404.php

where 404.php is the file name and placed at root. You can put full path over here.

Format number to always show 2 decimal places

This is how I solve my problem:

parseFloat(parseFloat(floatString).toFixed(2));

Connect to Oracle DB using sqlplus

it would be something like this

sqlplus -s /nolog  <<-!
connect ${ORACLE_UID}/${ORACLE_PWD}@${ORACLE_DB};
whenever sqlerror exit sql.sqlcode;
set pagesize 0;
set linesize 150;
spool <query_output.dat> APPEND
@$<input_query.dat>
spool off;
exit;
!

here

ORACLE_UID=<user name>
ORACLE_PWD=<password>
ORACLE_DB=//<host>:<port>/<DB name>

Uncaught Typeerror: cannot read property 'innerHTML' of null

Looks like the script executes before the DOM loads. Try loading the script asynchronously.

 <script src="yourcode.js" async></script>

Listen to changes within a DIV and act accordingly

Try this

$('#D25,#E37,#E31,#F37,#E16,#E40,#F16,#F40,#E41,#F41').bind('DOMNodeInserted DOMNodeRemoved',function(){
          // your code;
       });

Do not use this. This may crash the page.

$('mydiv').bind("DOMSubtreeModified",function(){
  alert('changed');
});

Creating a LinkedList class from scratch

What you have coded is not a LinkedList, at least not one that I recognize. For this assignment, you want to create two classes:

LinkNode
LinkedList

A LinkNode has one member field for the data it contains, and a LinkNode reference to the next LinkNode in the LinkedList. Yes, it's a self referential data structure. A LinkedList just has a special LinkNode reference that refers to the first item in the list.

When you add an item in the LinkedList, you traverse all the LinkNode's until you reach the last one. This LinkNode's next should be null. You then construct a new LinkNode here, set it's value, and add it to the LinkedList.

public class LinkNode { 

    String data;
    LinkNode next;

    public LinkNode(String item) { 

       data = item;

    }

}

public class LinkedList { 

    LinkNode head;

    public LinkedList(String item) { 

       head = new LinkNode(item);

    }

    public void add(String item) { 

       //pseudo code: while next isn't null, walk the list
       //once you reach the end, create a new LinkNode and add the item to it.  Then
       //set the last LinkNode's next to this new LinkNode

    }


}

How to use regex in String.contains() method in Java

If you want to check if a string contains substring or not using regex, the closest you can do is by using find() -

    private static final validPattern =   "\\bstores\\b.*\\bstore\\b.*\\bproduct\\b"
    Pattern pattern = Pattern.compile(validPattern);
    Matcher matcher = pattern.matcher(inputString);
    System.out.print(matcher.find()); // should print true or false.

Note the difference between matches() and find(), matches() return true if the whole string matches the given pattern. find() tries to find a substring that matches the pattern in a given input string. Also by using find() you don't have to add extra matching like - (?s).* at the beginning and .* at the end of your regex pattern.

Check if passed argument is file or directory in Bash

#!/bin/bash                                                                                               
echo "Please Enter a file name :"                                                                          
read filename                                                                                             
if test -f $filename                                                                                      
then                                                                                                      
        echo "this is a file"                                                                             
else                                                                                                      
        echo "this is not a file"                                                                         
fi 

Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click

The best solution is to override the click functionality:

public void _click(WebElement element){
    boolean flag = false;
    while(true) {
        try{
            element.click();
            flag=true;
        }
        catch (Exception e){
            flag = false;
        }
        if(flag)
        {
            try{
                element.click();
            }
            catch (Exception e){
                System.out.printf("Element: " +element+ " has beed clicked, Selenium exception triggered: " + e.getMessage());
            }
            break;
        }
    }
}

Warning: implode() [function.implode]: Invalid arguments passed

function my_get_tags_sitemap(){
    if ( !function_exists('wp_tag_cloud') || get_option('cb2_noposttags')) return;
    $unlinkTags = get_option('cb2_unlinkTags'); 
    echo '<div class="tags"><h2>Tags</h2>';
    $ret = []; // here you need to add array which you call inside implode function
    if($unlinkTags)
    {
        $tags = get_tags();
        foreach ($tags as $tag){
            $ret[]= $tag->name;
        }
        //ERROR OCCURS HERE
        echo implode(', ', $ret);
    }
    else
    {
        wp_tag_cloud('separator=, &smallest=11&largest=11');
    }
    echo '</div>';
}

"Cross origin requests are only supported for HTTP." error when loading a local file

  • Install local webserver for java e.g Tomcat,for php you can use lamp etc
  • Drop the json file in the public accessible app server directory
  • List item

  • Start the app server,and you should be able to access the file from localhost

How to change JFrame icon

Add the following code within the constructor like so:

public Calculator() {
    initComponents();
//the code to be added        this.setIconImage(newImageIcon(getClass().getResource("color.png")).getImage());     }

Change "color.png" to the file name of the picture you want to insert. Drag and drop this picture onto the package (under Source Packages) of your project.

Run your project.

How do I replace a character at a particular index in JavaScript?

You can extend the string type to include the inset method:

_x000D_
_x000D_
String.prototype.append = function (index,value) {_x000D_
  return this.slice(0,index) + value + this.slice(index);_x000D_
};_x000D_
_x000D_
var s = "New string";_x000D_
alert(s.append(4,"complete "));
_x000D_
_x000D_
_x000D_

Then you can call the function:

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

My templatized inline in-place find-and-replace:

template<class T>
int inline findAndReplace(T& source, const T& find, const T& replace)
{
    int num=0;
    typename T::size_t fLen = find.size();
    typename T::size_t rLen = replace.size();
    for (T::size_t pos=0; (pos=source.find(find, pos))!=T::npos; pos+=rLen)
    {
        num++;
        source.replace(pos, fLen, replace);
    }
    return num;
}

It returns a count of the number of items substituted (for use if you want to successively run this, etc). To use it:

std::string str = "one two three";
int n = findAndReplace(str, "one", "1");

When should I use git pull --rebase?

I would like to provide a different perspective on what "git pull --rebase" actually means, because it seems to get lost sometimes.

If you've ever used Subversion (or CVS), you may be used to the behavior of "svn update". If you have changes to commit and the commit fails because changes have been made upstream, you "svn update". Subversion proceeds by merging upstream changes with yours, potentially resulting in conflicts.

What Subversion just did, was essentially "pull --rebase". The act of re-formulating your local changes to be relative to the newer version is the "rebasing" part of it. If you had done "svn diff" prior to the failed commit attempt, and compare the resulting diff with the output of "svn diff" afterwards, the difference between the two diffs is what the rebasing operation did.

The major difference between Git and Subversion in this case is that in Subversion, "your" changes only exist as non-committed changes in your working copy, while in Git you have actual commits locally. In other words, in Git you have forked the history; your history and the upstream history has diverged, but you have a common ancestor.

In my opinion, in the normal case of having your local branch simply reflecting the upstream branch and doing continuous development on it, the right thing to do is always "--rebase", because that is what you are semantically actually doing. You and others are hacking away at the intended linear history of a branch. The fact that someone else happened to push slightly prior to your attempted push is irrelevant, and it seems counter-productive for each such accident of timing to result in merges in the history.

If you actually feel the need for something to be a branch for whatever reason, that is a different concern in my opinion. But unless you have a specific and active desire to represent your changes in the form of a merge, the default behavior should, in my opinion, be "git pull --rebase".

Please consider other people that need to observe and understand the history of your project. Do you want the history littered with hundreds of merges all over the place, or do you want only the select few merges that represent real merges of intentional divergent development efforts?

Regex match one of two words

This will do:

/^(apple|banana)$/

to exclude from captured strings (e.g. $1,$2):

(?:apple|banana)

$watch'ing for data changes in an Angular directive

My version for a directive that uses jqplot to plot the data once it becomes available:

    app.directive('lineChart', function() {
        $.jqplot.config.enablePlugins = true;

        return function(scope, element, attrs) {
            scope.$watch(attrs.lineChart, function(newValue, oldValue) {
                if (newValue) {
                    // alert(scope.$eval(attrs.lineChart));
                    var plot = $.jqplot(element[0].id, scope.$eval(attrs.lineChart), scope.$eval(attrs.options));
                }
            });
        }
});

How do I execute a file in Cygwin?

When you start in Cygwin you are in the "/home/Administrator" zone, so put your a.exe file there.

Then at the prompt run:

cd a.exe

It will be read in by Cygwin and you will be asked to install it.

Any way to replace characters on Swift String?

you can test this:

let newString = test.stringByReplacingOccurrencesOfString(" ", withString: "+", options: nil, range: nil)

Basic example for sharing text or image with UIActivityViewController in Swift

I found this to work flawlessly if you want to share whole screen.

@IBAction func shareButton(_ sender: Any) {

    let bounds = UIScreen.main.bounds
    UIGraphicsBeginImageContextWithOptions(bounds.size, true, 0.0)
    self.view.drawHierarchy(in: bounds, afterScreenUpdates: false)
    let img = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    let activityViewController = UIActivityViewController(activityItems: [img!], applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view
    self.present(activityViewController, animated: true, completion: nil)
}

try/catch with InputMismatchException creates infinite loop

@Limp, your answer is right, just use .nextLine() while reading the input. Sample code:

    do {
        try {
            System.out.println("Enter first num: ");
            n1 = Integer.parseInt(input.nextLine());
            System.out.println("Enter second num: ");
            n2 = Integer.parseInt(input.nextLine());
            nQuotient = n1 / n2;
            bError = false;
        } catch (Exception e) {
            System.out.println("Error!");
        }
    } while (bError);

    System.out.printf("%d/%d = %d", n1, n2, nQuotient);

Read the description of why this problem was caused in the link below. Look for the answer I posted for the detail in this thread. Java Homework user input issue

Ok, I will briefly describe it. When you read input using nextInt(), you just read the number part but the ENDLINE character was still on the stream. That was the main cause. Now look at the code above, all I did is read the whole line and parse it , it still throws the exception and work the way you were expecting it to work. Rest of your code works fine.

Creating custom function in React component

With React Functional way

import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import Button from "@material-ui/core/Button";

const App = () => {
  const saySomething = (something) => {
    console.log(something);
  };
  useEffect(() => {
    saySomething("from useEffect");
  });
  const handleClick = (e) => {
    saySomething("element clicked");
  };
  return (
    <Button variant="contained" color="primary" onClick={handleClick}>
      Hello World
    </Button>
  );
};

ReactDOM.render(<App />, document.querySelector("#app"));

https://codesandbox.io/s/currying-meadow-gm9g0

What is “assert” in JavaScript?

There is no standard assert in JavaScript itself. Perhaps you're using some library that provides one; for instance, if you're using Node.js, perhaps you're using the assertion module. (Browsers and other environments that offer a console implementing the Console API provide console.assert.)

The usual meaning of an assert function is to throw an error if the expression passed into the function is false; this is part of the general concept of assertion checking. Usually assertions (as they're called) are used only in "testing" or "debug" builds and stripped out of production code.

Suppose you had a function that was supposed to always accept a string. You'd want to know if someone called that function with something that wasn't a string (without having a type checking layer like TypeScript or Flow). So you might do:

assert(typeof argumentName === "string");

...where assert would throw an error if the condition were false.

A very simple version would look like this:

function assert(condition, message) {
    if (!condition) {
        throw message || "Assertion failed";
    }
}

Better yet, make use of the Error object, which has the advantage of collecting a stack trace and such:

function assert(condition, message) {
    if (!condition) {
        throw new Error(message || "Assertion failed");
    }
}

Checking to see if one array's elements are in another array in PHP

You can use array_intersect().

$result = !empty(array_intersect($people, $criminals));

Base64 Decoding in iOS 7+

In case you want to write fallback code, decoding from base64 has been present in iOS since the very beginning by caveat of NSURL:

NSURL *URL = [NSURL URLWithString:
      [NSString stringWithFormat:@"data:application/octet-stream;base64,%@",
           base64String]];

return [NSData dataWithContentsOfURL:URL];

How can I append a query parameter to an existing URL?

Use the URI class.

Create a new URI with your existing String to "break it up" to parts, and instantiate another one to assemble the modified url:

URI u = new URI("http://[email protected]&name=John#fragment");

// Modify the query: append your new parameter
StringBuilder sb = new StringBuilder(u.getQuery() == null ? "" : u.getQuery());
if (sb.length() > 0)
    sb.append('&');
sb.append(URLEncoder.encode("paramName", "UTF-8"));
sb.append('=');
sb.append(URLEncoder.encode("paramValue", "UTF-8"));

// Build the new url with the modified query:
URI u2 = new URI(u.getScheme(), u.getAuthority(), u.getPath(),
    sb.toString(), u.getFragment());

Handling onchange event in HTML.DropDownList Razor MVC

Description

You can use another overload of the DropDownList method. Pick the one you need and pass in a object with your html attributes.

Sample

@Html.DropDownList("CategoryID", null, new { @onchange="location = this.value;" })

More Information

Python Pandas counting and summing specific conditions

I usually use numpy sum over the logical condition column:

>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame({'Age' : [20,24,18,5,78]})
>>> np.sum(df['Age'] > 20)
2

This seems to me slightly shorter than the solution presented above

Do the parentheses after the type name make a difference with new?

The rules for new are analogous to what happens when you initialize an object with automatic storage duration (although, because of vexing parse, the syntax can be slightly different).

If I say:

int my_int; // default-initialize ? indeterminate (non-class type)

Then my_int has an indeterminate value, since it is a non-class type. Alternatively, I can value-initialize my_int (which, for non-class types, zero-initializes) like this:

int my_int{}; // value-initialize ? zero-initialize (non-class type)

(Of course, I can't use () because that would be a function declaration, but int() works the same as int{} to construct a temporary.)

Whereas, for class types:

Thing my_thing; // default-initialize ? default ctor (class type)
Thing my_thing{}; // value-initialize ? default-initialize ? default ctor (class type)

The default constructor is called to create a Thing, no exceptions.

So, the rules are more or less:

  • Is it a class type?
    • YES: The default constructor is called, regardless of whether it is value-initialized (with {}) or default-initialized (without {}). (There is some additional prior zeroing behavior with value-initialization, but the default constructor is always given the final say.)
    • NO: Were {} used?
      • YES: The object is value-initialized, which, for non-class types, more or less just zero-initializes.
      • NO: The object is default-initialized, which, for non-class types, leaves it with an indeterminate value (it effectively isn't initialized).

These rules translate precisely to new syntax, with the added rule that () can be substituted for {} because new is never parsed as a function declaration. So:

int* my_new_int = new int; // default-initialize ? indeterminate (non-class type)
Thing* my_new_thing = new Thing; // default-initialize ? default ctor (class type)
int* my_new_zeroed_int = new int(); // value-initialize ? zero-initialize (non-class type)
     my_new_zeroed_int = new int{}; // ditto
       my_new_thing = new Thing(); // value-initialize ? default-initialize ? default ctor (class type)

(This answer incorporates conceptual changes in C++11 that the top answer currently does not; notably, a new scalar or POD instance that would end up an with indeterminate value is now technically now default-initialized (which, for POD types, technically calls a trivial default constructor). While this does not cause much practical change in behavior, it does simplify the rules somewhat.)

Checking if a SQL Server login already exists

This works on SQL Server 2000.

use master
select count(*) From sysxlogins WHERE NAME = 'myUsername'

on SQL 2005, change the 2nd line to

select count(*) From syslogins WHERE NAME = 'myUsername'

I'm not sure about SQL 2008, but I'm guessing that it will be the same as SQL 2005 and if not, this should give you an idea of where t start looking.

IPython/Jupyter Problems saving notebook as PDF

I had this error in Windows 10. I followed these three steps and it solved my problem:

  1. Install nbconvert

    pip install nbconvert

  2. Install pandoc

https://pandoc.org/installing.html

  1. Install miktex

https://miktex.org/download


Also it is good to update libraries:

pip install jupyter --upgrade
pip install --upgrade --user nbconvert

Plot width settings in ipython notebook

If you're not in an ipython notebook (like the OP), you can also just declare the size when you declare the figure:

width = 12
height = 12
plt.figure(figsize=(width, height))

Set disable attribute based on a condition for Html.TextBoxFor

One simple approach I have used is conditional rendering:

@(Model.ExpireDate == null ? 
  @Html.TextBoxFor(m => m.ExpireDate, new { @disabled = "disabled" }) : 
  @Html.TextBoxFor(m => m.ExpireDate)
)

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

I faced the same problem.

Just removed the server from configuration and added it back after restarting eclipse by adding it to the server runtime environment.

jQuery add text to span within a div

Careful - append() will append HTML, and you may run into cross-site-scripting problems if you use it all the time and a user makes you append('<script>alert("Hello")</script>').

Use text() to replace element content with text, or append(document.createTextNode(x)) to append a text node.

SQL how to increase or decrease one for a int column in one command

The single-step answer to the first question is to use something like:

update TBL set CLM = CLM + 1 where key = 'KEY'

That's very much a single-instruction way of doing it.

As for the second question, you shouldn't need to resort to DBMS-specific SQL gymnastics (like UPSERT) to get the result you want. There's a standard method to do update-or-insert that doesn't require a specific DBMS.

try:
    insert into TBL (key,val) values ('xyz',0)
catch:
    do nothing
update TBL set val = val + 1 where key = 'xyz'

That is, you try to do the creation first. If it's already there, ignore the error. Otherwise you create it with a 0 value.

Then do the update which will work correctly whether or not:

  • the row originally existed.
  • someone updated it between your insert and update.

It's not a single instruction and yet, surprisingly enough, it's how we've been doing it successfully for a long long time.

How do I disable text selection with CSS or JavaScript?

<div 
 style="-moz-user-select: none; -webkit-user-select: none; -ms-user-select:none; user-select:none;-o-user-select:none;" 
 unselectable="on"
 onselectstart="return false;" 
 onmousedown="return false;">
    Blabla
</div>