Programs & Examples On #Field

In computer science a field is a smaller piece of data from a larger collection.

Get list of all input objects using JavaScript, without accessing a form object

var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; ++i) {
  // ...
}

String field value length in mongoDB

For MongoDB 3.6 and newer:

The $expr operator allows the use of aggregation expressions within the query language, thus you can leverage the use of $strLenCP operator to check the length of the string as follows:

db.usercollection.find({ 
    "name": { "$exists": true },
    "$expr": { "$gt": [ { "$strLenCP": "$name" }, 40 ] } 
})

For MongoDB 3.4 and newer:

You can also use the aggregation framework with the $redact pipeline operator that allows you to proccess the logical condition with the $cond operator and uses the special operations $$KEEP to "keep" the document where the logical condition is true or $$PRUNE to "remove" the document where the condition was false.

This operation is similar to having a $project pipeline that selects the fields in the collection and creates a new field that holds the result from the logical condition query and then a subsequent $match, except that $redact uses a single pipeline stage which is more efficient.

As for the logical condition, there are String Aggregation Operators that you can use $strLenCP operator to check the length of the string. If the length is $gt a specified value, then this is a true match and the document is "kept". Otherwise it is "pruned" and discarded.


Consider running the following aggregate operation which demonstrates the above concept:

db.usercollection.aggregate([
    { "$match": { "name": { "$exists": true } } },
    {
        "$redact": {
            "$cond": [
                { "$gt": [ { "$strLenCP": "$name" }, 40] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    },
    { "$limit": 2 }
])

If using $where, try your query without the enclosing brackets:

db.usercollection.find({$where: "this.name.length > 40"}).limit(2);

A better query would be to to check for the field's existence and then check the length:

db.usercollection.find({name: {$type: 2}, $where: "this.name.length > 40"}).limit(2); 

or:

db.usercollection.find({name: {$exists: true}, $where: "this.name.length > 
40"}).limit(2); 

MongoDB evaluates non-$where query operations before $where expressions and non-$where query statements may use an index. A much better performance is to store the length of the string as another field and then you can index or search on it; applying $where will be much slower compared to that. It's recommended to use JavaScript expressions and the $where operator as a last resort when you can't structure the data in any other way, or when you are dealing with a small subset of data.


A different and faster approach that avoids the use of the $where operator is the $regex operator. Consider the following pattern which searches for

db.usercollection.find({"name": {"$type": 2, "$regex": /^.{41,}$/}}).limit(2); 

Note - From the docs:

If an index exists for the field, then MongoDB matches the regular expression against the values in the index, which can be faster than a collection scan. Further optimization can occur if the regular expression is a “prefix expression”, which means that all potential matches start with the same string. This allows MongoDB to construct a “range” from that prefix and only match against those values from the index that fall within that range.

A regular expression is a “prefix expression” if it starts with a caret (^) or a left anchor (\A), followed by a string of simple symbols. For example, the regex /^abc.*/ will be optimized by matching only against the values from the index that start with abc.

Additionally, while /^a/, /^a.*/, and /^a.*$/ match equivalent strings, they have different performance characteristics. All of these expressions use an index if an appropriate index exists; however, /^a.*/, and /^a.*$/ are slower. /^a/ can stop scanning after matching the prefix.

How to remove leading and trailing whitespace in a MySQL field?

I know its already accepted, but for thoses like me who look for "remove ALL whitespaces" (not just at the begining and endingof the string):

select SUBSTRING_INDEX('1234 243', ' ', 1);
// returns '1234'

EDIT 2019/6/20 : Yeah, that's not good. The function returns the part of the string since "when the character space occured for the first time". So, I guess that saying this remove the leading and trailling whitespaces and returns the first word :

select SUBSTRING_INDEX(TRIM(' 1234 243'), ' ', 1);

Add new field to every document in a MongoDB collection

To clarify, the syntax is as follows for MongoDB version 4.0.x:

db.collection.update({},{$set: {"new_field*":1}},false,true)

Here is a working example adding a published field to the articles collection and setting the field's value to true:

db.articles.update({},{$set: {"published":true}},false,true)

disable all form elements inside div

For me the accepted answer did not work as I had some asp net hidden fields which got disabled as well so I chose only to disable visible fields

//just to save the list so we can enable fields later
var list = [];
$('#parent-selector').find(':input:visible:not([readonly][disabled]),button').each(function () {
    list.push('#' + this.id);
});

$(list.join(',')).attr('readonly', true);

Mysql Compare two datetime fields

Your query apparently returned all correct dates, even considering the time.

If you're still not happy with the results, give DATEDIFF a shot and look for negaive/positive results between the two dates.

Make sure your mydate column is a datetime type.

PHP - Getting the index of a element from a array

function Index($index) {
    $Count = count($YOUR_ARRAY);
    if ($index <= $Count) {
        $Keys = array_keys($YOUR_ARRAY);
        $Value = array_values($YOUR_ARRAY);
        return $Keys[$index] . ' = ' . $Value[$index];
    } else {
        return "Out of the ring";
    }
}

echo 'Index : ' . Index(0);

Replace the ( $YOUR_ARRAY )

Why does Java have transient fields?

My small contribution :

What is a transient field?
Basically, any field modified with the transient keyword is a transient field.

Why are transient fields needed in Java?
The transient keyword gives you some control over the serialization process and allows you to exclude some object properties from this process. The serialization process is used to persist Java objects, mostly so that their states can be preserved while they are transferred or inactive. Sometimes, it makes sense not to serialize certain attributes of an object.

Which fields should you mark transient?
Now we know the purpose of the transient keyword and transient fields, it's important to know which fields to mark transient. Static fields aren't serialized either, so the corresponding keyword would also do the trick. But this might ruin your class design; this is where the transient keyword comes to the rescue. I try not to allow fields whose values can be derived from others to be serialized, so I mark them transient. If you have a field called interest whose value can be calculated from other fields (principal, rate & time), there is no need to serialize it.

Another good example is with article word counts. If you are saving an entire article, there's really no need to save the word count, because it can be computed when article gets "deserialized." Or think about loggers; Logger instances almost never need to be serialized, so they can be made transient.

How to add additional fields to form before submit?

Try this:

$('#form').submit(function(eventObj) {
    $(this).append('<input type="hidden" name="field_name" value="value" /> ');
    return true;
});

SSRS Field Expression to change the background color of the Cell

=IIF(Fields!ADPAction.Value.ToString().ToUpper().Contains("FAIL"),"Red","White")

Also need to convert to upper case for comparision is binary test.

PHP: check if any posted vars are empty - form: all fields required

Something like this:

// Required field names
$required = array('login', 'password', 'confirm', 'name', 'phone', 'email');

// Loop over field names, make sure each one exists and is not empty
$error = false;
foreach($required as $field) {
  if (empty($_POST[$field])) {
    $error = true;
  }
}

if ($error) {
  echo "All fields are required.";
} else {
  echo "Proceed...";
}

Best way to handle multiple constructors in Java

I would do the following:

public class Book
{
    private final String title;
    private final String isbn;

    public Book(final String t, final String i)
    {
        if(t == null)
        {
            throw new IllegalArgumentException("t cannot be null");
        }

        if(i == null)
        {
            throw new IllegalArgumentException("i cannot be null");
        }

        title = t;
        isbn  = i;
    }
}

I am making the assumption here that:

1) the title will never change (hence title is final) 2) the isbn will never change (hence isbn is final) 3) that it is not valid to have a book without both a title and an isbn.

Consider a Student class:

public class Student
{
    private final StudentID id;
    private String firstName;
    private String lastName;

    public Student(final StudentID i,
                   final String    first,
                   final String    last)
    {
        if(i == null)
        {
            throw new IllegalArgumentException("i cannot be null"); 
        }

        if(first == null)
        {
            throw new IllegalArgumentException("first cannot be null"); 
        }

        if(last == null)
        {
            throw new IllegalArgumentException("last cannot be null"); 
        }

        id        = i;
        firstName = first;
        lastName  = last;
    }
}

There a Student must be created with an id, a first name, and a last name. The student ID can never change, but a persons last and first name can change (get married, changes name due to losing a bet, etc...).

When deciding what constrructors to have you really need to think about what makes sense to have. All to often people add set/get methods because they are taught to - but very often it is a bad idea.

Immutable classes are much better to have (that is classes with final variables) over mutable ones. This book: http://books.google.com/books?id=ZZOiqZQIbRMC&pg=PA97&sig=JgnunNhNb8MYDcx60Kq4IyHUC58#PPP1,M1 (Effective Java) has a good discussion on immutability. Look at items 12 and 13.

In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

As pointed out in this answer, Django 1.9 added the Field.disabled attribute:

The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won’t be editable by users. Even if a user tampers with the field’s value submitted to the server, it will be ignored in favor of the value from the form’s initial data.

With Django 1.8 and earlier, to disable entry on the widget and prevent malicious POST hacks you must scrub the input in addition to setting the readonly attribute on the form field:

class ItemForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(ItemForm, self).__init__(*args, **kwargs)
        instance = getattr(self, 'instance', None)
        if instance and instance.pk:
            self.fields['sku'].widget.attrs['readonly'] = True

    def clean_sku(self):
        instance = getattr(self, 'instance', None)
        if instance and instance.pk:
            return instance.sku
        else:
            return self.cleaned_data['sku']

Or, replace if instance and instance.pk with another condition indicating you're editing. You could also set the attribute disabled on the input field, instead of readonly.

The clean_sku function will ensure that the readonly value won't be overridden by a POST.

Otherwise, there is no built-in Django form field which will render a value while rejecting bound input data. If this is what you desire, you should instead create a separate ModelForm that excludes the uneditable field(s), and just print them inside your template.

Making a DateTime field in a database automatic?

Yes, here's an example:

CREATE TABLE myTable ( col1 int, createdDate datetime DEFAULT(getdate()), updatedDate datetime DEFAULT(getdate()) )

You can INSERT into the table without indicating the createdDate and updatedDate columns:

INSERT INTO myTable (col1) VALUES (1)

Or use the keyword DEFAULT:

INSERT INTO myTable (col1, createdDate, updatedDate) VALUES (1, DEFAULT, DEFAULT)

Then create a trigger for updating the updatedDate column:

CREATE TRIGGER dbo.updateMyTable 
ON dbo.myTable
FOR UPDATE 
AS 
BEGIN 
    IF NOT UPDATE(updatedDate) 
        UPDATE dbo.myTable SET updatedDate=GETDATE() 
        WHERE col1 IN (SELECT col1 FROM inserted) 
END 
GO

How to update only one field using Entity Framework?

Entity framework tracks your changes on objects that you queried from database via DbContext. For example if you DbContext instance name is dbContext

public void ChangePassword(int userId, string password){
     var user = dbContext.Users.FirstOrDefault(u=>u.UserId == userId);
     user.password = password;
     dbContext.SaveChanges();
}

Overriding fields or properties in subclasses

I'd go with option 3, but have an abstract setMyInt method that subclasses are forced to implement. This way you won't have the problem of a derived class forgetting to set it in the constructor.

abstract class Base 
{
 protected int myInt;
 protected abstract void setMyInt();
}

class Derived : Base 
{
 override protected void setMyInt()
 {
   myInt = 3;
 }
}

By the way, with option one, if you don't specify set; in your abstract base class property, the derived class won't have to implement it.

abstract class Father
{
    abstract public int MyInt { get; }
}

class Son : Father
{
    public override int MyInt
    {
        get { return 1; }
    }
}

What is the difference between a field and a property?

when you have a class which is "Car". The properties are color,shape..

Where as fields are variables defined within the scope of a class.

Set field value with reflection

The method below sets a field on your object even if the field is in a superclass

/**
 * Sets a field value on a given object
 *
 * @param targetObject the object to set the field value on
 * @param fieldName    exact name of the field
 * @param fieldValue   value to set on the field
 * @return true if the value was successfully set, false otherwise
 */
public static boolean setField(Object targetObject, String fieldName, Object fieldValue) {
    Field field;
    try {
        field = targetObject.getClass().getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {
        field = null;
    }
    Class superClass = targetObject.getClass().getSuperclass();
    while (field == null && superClass != null) {
        try {
            field = superClass.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            superClass = superClass.getSuperclass();
        }
    }
    if (field == null) {
        return false;
    }
    field.setAccessible(true);
    try {
        field.set(targetObject, fieldValue);
        return true;
    } catch (IllegalAccessException e) {
        return false;
    }
}

How to read the value of a private field from a different class in Java?

In order to access private fields, you need to get them from the class's declared fields and then make them accessible:

Field f = obj.getClass().getDeclaredField("stuffIWant"); //NoSuchFieldException
f.setAccessible(true);
Hashtable iWantThis = (Hashtable) f.get(obj); //IllegalAccessException

EDIT: as has been commented by aperkins, both accessing the field, setting it as accessible and retrieving the value can throw Exceptions, although the only checked exceptions you need to be mindful of are commented above.

The NoSuchFieldException would be thrown if you asked for a field by a name which did not correspond to a declared field.

obj.getClass().getDeclaredField("misspelled"); //will throw NoSuchFieldException

The IllegalAccessException would be thrown if the field was not accessible (for example, if it is private and has not been made accessible via missing out the f.setAccessible(true) line.

The RuntimeExceptions which may be thrown are either SecurityExceptions (if the JVM's SecurityManager will not allow you to change a field's accessibility), or IllegalArgumentExceptions, if you try and access the field on an object not of the field's class's type:

f.get("BOB"); //will throw IllegalArgumentException, as String is of the wrong type

HTML text input field with currency symbol

If you only need to support Safari, you can do it like this:

input.currency:before {
  content: attr(data-symbol);
  float: left;
  color: #aaa;
}

and an input field like

<input class="currency" data-symbol="€" type="number" value="12.9">

This way you don't need an extra tag and keep the symbol information in the markup.

jquery how to empty input field

You can clear the input field by using $('#shares').val('');

jQuery - Detect value change on hidden input field

Since hidden input does not trigger "change" event on change, I used MutationObserver to trigger this instead.

(Sometimes hidden input value changes are done by some other scripts you can't modify)

This does not work in IE10 and below

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var trackChange = function(element) {
  var observer = new MutationObserver(function(mutations, observer) {
    if(mutations[0].attributeName == "value") {
        $(element).trigger("change");
    }
  });
  observer.observe(element, {
    attributes: true
  });
}

// Just pass an element to the function to start tracking
trackChange( $("input[name=foo]")[0] );

How do I enable saving of filled-in fields on a PDF form?

In Acrobat XI, (Close Form Editing if open) File > Save As Other > Reader Extended PDF > Enable Additional Features

Javascript - removing undefined fields from an object

I prefer to use something like Lodash:

import { pickBy, identity } from 'lodash'

const cleanedObject = pickBy(originalObject, identity)

Note that the identity function is just x => x and its result will be false for all falsy values. So this removes undefined, "", 0, null, ...

If you only want the undefined values removed you can do this:

const cleanedObject = pickBy(originalObject, v => v !== undefined)

It gives you a new object, which is usually preferable over mutating the original object like some of the other answers suggest.

nvarchar(max) vs NText

The advantages are that you can use functions like LEN and LEFT on nvarchar(max) and you cannot do that against ntext and text. It is also easier to work with nvarchar(max) than text where you had to use WRITETEXT and UPDATETEXT.

Also, text, ntext, etc., are being deprecated (http://msdn.microsoft.com/en-us/library/ms187993.aspx)

Bulk Record Update with SQL

Your way is correct, and here is another way you can do it:

update      Table1
set         Description = t2.Description
from        Table1 t1
inner join  Table2 t2
on          t1.DescriptionID = t2.ID

The nested select is the long way of just doing a join.

Run task only if host does not belong to a group

Here's another way to do this:

- name: my command
  command: echo stuff
  when: "'groupname' not in group_names"

group_names is a magic variable as documented here: https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#accessing-information-about-other-hosts-with-magic-variables :

group_names is a list (array) of all the groups the current host is in.

What are some uses of template template parameters?

I think you need to use template template syntax to pass a parameter whose type is a template dependent on another template like this:

template <template<class> class H, class S>
void f(const H<S> &value) {
}

Here, H is a template, but I wanted this function to deal with all specializations of H.

NOTE: I've been programming c++ for many years and have only needed this once. I find that it is a rarely needed feature (of course handy when you need it!).

I've been trying to think of good examples, and to be honest, most of the time this isn't necessary, but let's contrive an example. Let's pretend that std::vector doesn't have a typedef value_type.

So how would you write a function which can create variables of the right type for the vectors elements? This would work.

template <template<class, class> class V, class T, class A>
void f(V<T, A> &v) {
    // This can be "typename V<T, A>::value_type",
    // but we are pretending we don't have it

    T temp = v.back();
    v.pop_back();
    // Do some work on temp

    std::cout << temp << std::endl;
}

NOTE: std::vector has two template parameters, type, and allocator, so we had to accept both of them. Fortunately, because of type deduction, we won't need to write out the exact type explicitly.

which you can use like this:

f<std::vector, int>(v); // v is of type std::vector<int> using any allocator

or better yet, we can just use:

f(v); // everything is deduced, f can deal with a vector of any type!

UPDATE: Even this contrived example, while illustrative, is no longer an amazing example due to c++11 introducing auto. Now the same function can be written as:

template <class Cont>
void f(Cont &v) {

    auto temp = v.back();
    v.pop_back();
    // Do some work on temp

    std::cout << temp << std::endl;
}

which is how I'd prefer to write this type of code.

Complexities of binary tree traversals

T(n) = 2T(n/2)+ c

T(n/2) = 2T(n/4) + c => T(n) = 4T(n/4) + 2c + c

similarly T(n) = 8T(n/8) + 4c+ 2c + c

....

....

last step ... T(n) = nT(1) + c(sum of powers of 2 from 0 to h(height of tree))

so Complexity is O(2^(h+1) -1)

but h = log(n)

so, O(2n - 1) = O(n)

How to find out the number of CPUs using python

If you're interested into the number of processors available to your current process, you have to check cpuset first. Otherwise (or if cpuset is not in use), multiprocessing.cpu_count() is the way to go in Python 2.6 and newer. The following method falls back to a couple of alternative methods in older versions of Python:

import os
import re
import subprocess


def available_cpu_count():
    """ Number of available virtual or physical CPUs on this system, i.e.
    user/real as output by time(1) when called with an optimally scaling
    userspace-only program"""

    # cpuset
    # cpuset may restrict the number of *available* processors
    try:
        m = re.search(r'(?m)^Cpus_allowed:\s*(.*)$',
                      open('/proc/self/status').read())
        if m:
            res = bin(int(m.group(1).replace(',', ''), 16)).count('1')
            if res > 0:
                return res
    except IOError:
        pass

    # Python 2.6+
    try:
        import multiprocessing
        return multiprocessing.cpu_count()
    except (ImportError, NotImplementedError):
        pass

    # https://github.com/giampaolo/psutil
    try:
        import psutil
        return psutil.cpu_count()   # psutil.NUM_CPUS on old versions
    except (ImportError, AttributeError):
        pass

    # POSIX
    try:
        res = int(os.sysconf('SC_NPROCESSORS_ONLN'))

        if res > 0:
            return res
    except (AttributeError, ValueError):
        pass

    # Windows
    try:
        res = int(os.environ['NUMBER_OF_PROCESSORS'])

        if res > 0:
            return res
    except (KeyError, ValueError):
        pass

    # jython
    try:
        from java.lang import Runtime
        runtime = Runtime.getRuntime()
        res = runtime.availableProcessors()
        if res > 0:
            return res
    except ImportError:
        pass

    # BSD
    try:
        sysctl = subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
                                  stdout=subprocess.PIPE)
        scStdout = sysctl.communicate()[0]
        res = int(scStdout)

        if res > 0:
            return res
    except (OSError, ValueError):
        pass

    # Linux
    try:
        res = open('/proc/cpuinfo').read().count('processor\t:')

        if res > 0:
            return res
    except IOError:
        pass

    # Solaris
    try:
        pseudoDevices = os.listdir('/devices/pseudo/')
        res = 0
        for pd in pseudoDevices:
            if re.match(r'^cpuid@[0-9]+$', pd):
                res += 1

        if res > 0:
            return res
    except OSError:
        pass

    # Other UNIXes (heuristic)
    try:
        try:
            dmesg = open('/var/run/dmesg.boot').read()
        except IOError:
            dmesgProcess = subprocess.Popen(['dmesg'], stdout=subprocess.PIPE)
            dmesg = dmesgProcess.communicate()[0]

        res = 0
        while '\ncpu' + str(res) + ':' in dmesg:
            res += 1

        if res > 0:
            return res
    except OSError:
        pass

    raise Exception('Can not determine number of CPUs on this system')

Define global variable with webpack

There are several way to approach globals:

  1. Put your variables in a module.

Webpack evaluates modules only once, so your instance remains global and carries changes through from module to module. So if you create something like a globals.js and export an object of all your globals then you can import './globals' and read/write to these globals. You can import into one module, make changes to the object from a function and import into another module and read those changes in a function. Also remember the order things happen. Webpack will first take all the imports and load them up in order starting in your entry.js. Then it will execute entry.js. So where you read/write to globals is important. Is it from the root scope of a module or in a function called later?

config.js

export default {
    FOO: 'bar'
}

somefile.js

import CONFIG from './config.js'
console.log(`FOO: ${CONFIG.FOO}`)

Note: If you want the instance to be new each time, then use an ES6 class. Traditionally in JS you would capitalize classes (as opposed to the lowercase for objects) like
import FooBar from './foo-bar' // <-- Usage: myFooBar = new FooBar()

  1. Webpack's ProvidePlugin

Here's how you can do it using Webpack's ProvidePlugin (which makes a module available as a variable in every module and only those modules where you actually use it). This is useful when you don't want to keep typing import Bar from 'foo' again and again. Or you can bring in a package like jQuery or lodash as global here (although you might take a look at Webpack's Externals).

Step 1) Create any module. For example, a global set of utilities would be handy:

utils.js

export function sayHello () {
  console.log('hello')
}

Step 2) Alias the module and add to ProvidePlugin:

webpack.config.js

var webpack = require("webpack");
var path = require("path");

// ...

module.exports = {

  // ...

  resolve: {
    extensions: ['', '.js'],
    alias: {
      'utils': path.resolve(__dirname, './utils')  // <-- When you build or restart dev-server, you'll get an error if the path to your utils.js file is incorrect.
    }
  },

  plugins: [

    // ...

    new webpack.ProvidePlugin({
      'utils': 'utils'
    })
  ]  

}

Now just call utils.sayHello() in any js file and it should work. Make sure you restart your dev-server if you are using that with Webpack.

Note: Don't forget to tell your linter about the global, so it won't complain. For example, see my answer for ESLint here.

  1. Use Webpack's DefinePlugin

If you just want to use const with string values for your globals, then you can add this plugin to your list of Webpack plugins:

new webpack.DefinePlugin({
  PRODUCTION: JSON.stringify(true),
  VERSION: JSON.stringify("5fa3b9"),
  BROWSER_SUPPORTS_HTML5: true,
  TWO: "1+1",
  "typeof window": JSON.stringify("object")
})

Use it like:

console.log("Running App version " + VERSION);
if(!BROWSER_SUPPORTS_HTML5) require("html5shiv");
  1. Use the global window object (or Node's global)

window.foo = 'bar'  // For SPA's, browser environment.
global.foo = 'bar'  // Webpack will automatically convert this to window if your project is targeted for web (default), read more here: https://webpack.js.org/configuration/node/

You'll see this commonly used for polyfills, for example: window.Promise = Bluebird

  1. Use a package like dotenv

(For server side projects) The dotenv package will take a local configuration file (which you could add to your .gitignore if there are any keys/credentials) and adds your configuration variables to Node's process.env object.

// As early as possible in your application, require and configure dotenv.    
require('dotenv').config()

Create a .env file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE. For example:

DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

That's it.

process.env now has the keys and values you defined in your .env file.

var db = require('db')
db.connect({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS
})

Notes:

Regarding Webpack's Externals, use it if you want to exclude some modules from being included in your built bundle. Webpack will make the module globally available but won't put it in your bundle. This is handy for big libraries like jQuery (because tree shaking external packages doesn't work in Webpack) where you have these loaded on your page already in separate script tags (perhaps from a CDN).

How to push elements in JSON from javascript array

var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item

How to disable back swipe gesture in UINavigationController on iOS 7

swift 5, swift 4.2 can use the code in the below.

// disable
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
// enable
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

  • Accelerate
  • CoreData
  • CoreText
  • CoreGraphics
  • CoreTelephony
  • Foundation
  • QuartzCore
  • StoreKit
  • SystemConfiguration
  • UIKit

    -ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit  

How to sign in kubernetes dashboard?

You need to follow these steps before the token authentication

  1. Create a Cluster Admin service account

    kubectl create serviceaccount dashboard -n default
    
  2. Add the cluster binding rules to your dashboard account

    kubectl create clusterrolebinding dashboard-admin -n default --clusterrole=cluster-admin --serviceaccount=default:dashboard
    
  3. Get the secret token with this command

    kubectl get secret $(kubectl get serviceaccount dashboard -o jsonpath="{.secrets[0].name}") -o jsonpath="{.data.token}" | base64 --decode
    
  4. Choose token authentication in the Kubernetes dashboard login page enter image description here

  5. Now you can able to login

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

jquery Ajax call - data parameters are not being passed to MVC Controller action

  var json = {"ListID" : "1", "ItemName":"test"};
    $.ajax({
            url: url,
            type: 'POST',        
            data: username, 
            cache:false,
            beforeSend: function(xhr) {  
                xhr.setRequestHeader("Accept", "application/json");  
                xhr.setRequestHeader("Content-Type", "application/json");  
            },       
            success:function(response){
             console.log("Success")
            },
              error : function(xhr, status, error) {
            console.log("error")
            }
);

Understanding .get() method in Python

The get method of a dict (like for example characters) works just like indexing the dict, except that, if the key is missing, instead of raising a KeyError it returns the default value (if you call .get with just one argument, the key, the default value is None).

So an equivalent Python function (where calling myget(d, k, v) is just like d.get(k, v) might be:

def myget(d, k, v=None):
  try: return d[k]
  except KeyError: return v

The sample code in your question is clearly trying to count the number of occurrences of each character: if it already has a count for a given character, get returns it (so it's just incremented by one), else get returns 0 (so the incrementing correctly gives 1 at a character's first occurrence in the string).

Rename package in Android Studio

This I believe what you are looking for is Refactor > Move. You can also press F6.

You will get two popups. Make sure you select rename package on both. After that you will get a pop up to place the new package name.

Please note that if your package name is, for example, com.example.android.projectname then this will let you change com.example.android to something else.

One more thing, this will update the applicationId in your build.gradle as well. Just make sure that the checkboxes for "search in comments and strings" and "search for text occurrences" are both checked for it to work.

How to find the path of Flutter SDK

To find the Flutter SDK path [ used Windows10 ]

  1. In your Android Studio home page on the bottom right click on Configure
  2. Then Click on SDK Manager
  3. Then on System Settings
  4. Then on AndroidSDK

You will see the path at the top

npm command to uninstall or prune unused packages in Node.js

You can use npm-prune to remove extraneous packages.

npm prune [[<@scope>/]<pkg>...] [--production] [--dry-run] [--json]

This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.

Extraneous packages are packages that are not listed on the parent package's dependencies list.

If the --production flag is specified or the NODE_ENV environment variable is set to production, this command will remove the packages specified in your devDependencies. Setting --no-production will negate NODE_ENV being set to production.

If the --dry-run flag is used then no changes will actually be made.

If the --json flag is used then the changes npm prune made (or would have made with --dry-run) are printed as a JSON object.

In normal operation with package-locks enabled, extraneous modules are pruned automatically when modules are installed and you'll only need this command with the --production flag.

If you've disabled package-locks then extraneous modules will not be removed and it's up to you to run npm prune from time-to-time to remove them.

Use npm-dedupe to reduce duplication

npm dedupe
npm ddp

Searches the local package tree and attempts to simplify the overall structure by moving dependencies further up the tree, where they can be more effectively shared by multiple dependent packages.

For example, consider this dependency graph:

a
+-- b <-- depends on [email protected]
|    `-- [email protected]
`-- d <-- depends on c@~1.0.9
     `-- [email protected]

In this case, npm-dedupe will transform the tree to:

 a
 +-- b
 +-- d
 `-- [email protected]

Because of the hierarchical nature of node's module lookup, b and d will both get their dependency met by the single c package at the root level of the tree.

The deduplication algorithm walks the tree, moving each dependency as far up in the tree as possible, even if duplicates are not found. This will result in both a flat and deduplicated tree.

C++ sorting and keeping track of indexes

Well, my solution uses residue technique. We can place the values under sorting in the upper 2 bytes and the indices of the elements - in the lower 2 bytes:

int myints[] = {32,71,12,45,26,80,53,33};

for (int i = 0; i < 8; i++)
   myints[i] = myints[i]*(1 << 16) + i;

Then sort the array myints as usual:

std::vector<int> myvector(myints, myints+8);
sort(myvector.begin(), myvector.begin()+8, std::less<int>());

After that you can access the elements' indices via residuum. The following code prints the indices of the values sorted in the ascending order:

for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
   std::cout << ' ' << (*it)%(1 << 16);

Of course, this technique works only for the relatively small values in the original array myints (i.e. those which can fit into upper 2 bytes of int). But it has additional benefit of distinguishing identical values of myints: their indices will be printed in the right order.

How to send a GET request from PHP?

In the other hand, using REST API of other servers are very popular in PHP. Suppose you are looking for a way to redirect some HTTP requests into the other server (for example getting an xml file). Here is a PHP package to help you:

https://github.com/romanpitak/PHP-REST-Client

So, getting the xml file:

$client = new Client('http://example.com');
$request = $client->newRequest('/filename.xml');
$response = $request->getResponse();
echo $response->getParsedResponse();

Extracting Ajax return data in jQuery

on success: function (response) { alert(response.d); }

How to verify element present or visible in selenium 2 (Selenium WebDriver)

To make sure that an element is present you can do the following:

driver.findElements(By.id("id"));

That will return an array, if that array size is > 0 then the element/s is present.

Also, you need to provide more information, such as language and what have you tried before asking,

Good luck

How to Find Item in Dictionary Collection?

Sometimes you still need to use FirstOrDefault if you have to do different tests. If the Key component of your dictionnary is nullable, you can do this:

thisTag = _tags.FirstOrDefault(t => t.Key.SubString(1,1) == 'a');
if(thisTag.Key != null) { ... }

Using FirstOrDefault, the returned KeyValuePair's key and value will both be null if no match is found.

PHP remove commas from numeric strings

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)


Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;
}

The easiest would be:

$var = intval(preg_replace('/[^\d.]/', '', $var));

or if you need float:

$var = floatval(preg_replace('/[^\d.]/', '', $var));

How to Navigate from one View Controller to another using Swift

let objViewController = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
self.navigationController?.pushViewController(objViewController, animated: true)

How do I fix a Git detached head?

Realizing I had a detached head without knowing how I managed to get it (like three commits away), I also found out that trying to merge, rebase or cherry-pick triggered hundreds of merge-conflicts, so I took a different approach:

  1. (Assuming everything is committed (working tree is "clean"))

  2. Save my commit messages: git log > /tmp/log

  3. Save my working tree: mkdir /tmp/backup && cp -a all_my files_and_directories /tmp/backup

  4. Revert to master: git checkout master

  5. Remove all the working files and directories: rm ...

  6. Use the backup: cp -a /tmp/backup/. .

  7. git add and git commit using messages from saved /tmp/log, maybe repeating it with different sub-sets of files...

The disadvantage is that you loose your commit history if one file was changed multiple times since master, but in the end I had a clean master.

Rewrite all requests to index.php with nginx

If you want to pass just the index.php ( no other php file will be passed to fastcgi ) to fastcgi in case you have routes like this in a framework like codeigniter

$route["/download.php"] = "controller/method";


location ~ index\.php$ {
        fastcgi_pass 127.0.0.1:9000;
        include fastcgi.conf;
}

NPM Install Error:Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0'

delete npm and npm-cache folders in C:\Users\admin\AppData\Roaming\ (windows) then execute cmd

npm cache clear --force

npm cache verify

update npm to latest version

npm i -g npm

then create your project 1)Angular

npm i -g @angular/cli@latest

ng new HelloWorld

2)React

npm i -g create-react-app

create-react-app react-app

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

You can also use evalAsync. It will run sometime after digest has finished!

scope.evalAsync(function(scope){
    //use the scope...
});

How to pass json POST data to Web API method as an object?

Microsoft gave a good example of doing this:

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-1

First validate the request

if (ModelState.IsValid)

and than use the serialized data.

Content = new StringContent(update.Status)

Here 'Status' is a field in the complex type. Serializing is done by .NET, no need to worry about that.

Good tool to visualise database schema?

A different approach, but if you're using Ruby on Rails try RailRoad: http://railroad.rubyforge.org

C# Linq Where Date Between 2 Dates

I had a problem getting this to work.

I had two dates in a db line and I need to add them to a list for yesterday, today and tomorrow.

this is my solution:

        var yesterday = DateTime.Today.AddDays(-1);
        var today = DateTime.Today;
        var tomorrow = DateTime.Today.AddDays(1);            
        var vm = new Model()
        {
            Yesterday = _context.Table.Where(x => x.From <= yesterday && x.To >= yesterday).ToList(),
            Today = _context.Table.Where(x => x.From <= today & x.To >= today).ToList(),
            Tomorrow = _context.Table.Where(x => x.From <= tomorrow & x.To >= tomorrow).ToList()
        };

How to perform Join between multiple tables in LINQ lambda

it has been a while but my answer may help someone:

if you already defined the relation properly you can use this:

        var res = query.Products.Select(m => new
        {
            productID = product.Id,
            categoryID = m.ProductCategory.Select(s => s.Category.ID).ToList(),
        }).ToList();

Bat file to run a .exe at the command prompt

What's stopping you?

Put this command in a text file, save it with the .bat (or .cmd) extension and double click on it...

Presuming the command executes on your system, I think that's it.

Disable native datepicker in Google Chrome

This works for me:

;
(function ($) {
    $(document).ready(function (event) {
        $(document).on('click input', 'input[type="date"], input[type="text"].date-picker', function (e) {
            var $this = $(this);
            $this.prop('type', 'text').datepicker({
                showOtherMonths: true,
                selectOtherMonths: true,
                showButtonPanel: true,
                changeMonth: true,
                changeYear: true,
                dateFormat: 'yy-mm-dd',
                showWeek: true,
                firstDay: 1
            });

            setTimeout(function() {
                $this.datepicker('show');
            }, 1);
        });
    });
})(jQuery, jQuery.ui);

See also:

How can I disable the new Chrome HTML5 date input?

http://zizhujy.com/blog/post/2014/09/18/Add-date-picker-to-dynamically-generated-input-elements.aspx

Truncate a string straight JavaScript

Yes, substring works great:

stringTruncate('Hello world', 5); //output "Hello..."
stringTruncate('Hello world', 20);//output "Hello world"

var stringTruncate = function(str, length){
  var dots = str.length > length ? '...' : '';
  return str.substring(0, length)+dots;
};

What's the difference between event.stopPropagation and event.preventDefault?

Terminology

From quirksmode.org:

Event capturing

When you use event capturing

               | |
---------------| |-----------------
| element1     | |                |
|   -----------| |-----------     |
|   |element2  \ /          |     |
|   -------------------------     |
|        Event CAPTURING          |
-----------------------------------

the event handler of element1 fires first, the event handler of element2 fires last.

Event bubbling

When you use event bubbling

               / \
---------------| |-----------------
| element1     | |                |
|   -----------| |-----------     |
|   |element2  | |          |     |
|   -------------------------     |
|        Event BUBBLING           |
-----------------------------------

the event handler of element2 fires first, the event handler of element1 fires last.

Any event taking place in the W3C event model is first captured until it reaches the target element and then bubbles up again.

                 | |  / \
-----------------| |--| |-----------------
| element1       | |  | |                |
|   -------------| |--| |-----------     |
|   |element2    \ /  | |          |     |
|   --------------------------------     |
|        W3C event model                 |
------------------------------------------

Interface

From w3.org, for event capture:

If the capturing EventListener wishes to prevent further processing of the event from occurring it may call the stopPropagation method of the Event interface. This will prevent further dispatch of the event, although additional EventListeners registered at the same hierarchy level will still receive the event. Once an event's stopPropagation method has been called, further calls to that method have no additional effect. If no additional capturers exist and stopPropagation has not been called, the event triggers the appropriate EventListeners on the target itself.

For event bubbling:

Any event handler may choose to prevent further event propagation by calling the stopPropagation method of the Event interface. If any EventListener calls this method, all additional EventListeners on the current EventTarget will be triggered but bubbling will cease at that level. Only one call to stopPropagation is required to prevent further bubbling.

For event cancelation:

Cancelation is accomplished by calling the Event's preventDefault method. If one or more EventListeners call preventDefault during any phase of event flow the default action will be canceled.

Examples

In the following examples, a click on the hyperlink in the web browser triggers the event's flow (the event listeners are executed) and the event target's default action (a new tab is opened).

HTML:

<div id="a">
  <a id="b" href="http://www.google.com/" target="_blank">Google</a>
</div>
<p id="c"></p>

JavaScript:

var el = document.getElementById("c");

function capturingOnClick1(ev) {
    el.innerHTML += "DIV event capture<br>";
}

function capturingOnClick2(ev) {
    el.innerHTML += "A event capture<br>";
}

function bubblingOnClick1(ev) {
    el.innerHTML += "DIV event bubbling<br>";
}

function bubblingOnClick2(ev) {
    el.innerHTML += "A event bubbling<br>";
}

// The 3rd parameter useCapture makes the event listener capturing (false by default)
document.getElementById("a").addEventListener("click", capturingOnClick1, true);
document.getElementById("b").addEventListener("click", capturingOnClick2, true);
document.getElementById("a").addEventListener("click", bubblingOnClick1, false);
document.getElementById("b").addEventListener("click", bubblingOnClick2, false);

Example 1: it results in the output

DIV event capture
A event capture
A event bubbling
DIV event bubbling

Example 2: adding stopPropagation() to the function

function capturingOnClick1(ev) {
    el.innerHTML += "DIV event capture<br>";
    ev.stopPropagation();
}

results in the output

DIV event capture

The event listener prevented further downward and upward propagation of the event. However it did not prevent the default action (a new tab opening).

Example 3: adding stopPropagation() to the function

function capturingOnClick2(ev) {
    el.innerHTML += "A event capture<br>";
    ev.stopPropagation();
}

or the function

function bubblingOnClick2(ev) {
    el.innerHTML += "A event bubbling<br>";
    ev.stopPropagation();
}

results in the output

DIV event capture
A event capture
A event bubbling

This is because both event listeners are registered on the same event target. The event listeners prevented further upward propagation of the event. However they did not prevent the default action (a new tab opening).

Example 4: adding preventDefault() to any function, for instance

function capturingOnClick1(ev) {
    el.innerHTML += "DIV event capture<br>";
    ev.preventDefault();
}

prevents a new tab from opening.

Error: 10 $digest() iterations reached. Aborting! with dynamic sortby predicate

The cause of this error for me was...

ng-if="{{myTrustSrc(chat.src)}}"

in my template

It causes the function myTrustSrc in my controller to be called in an endless loop. If I remove the ng-if from this line, then the problem is solved.

<iframe ng-if="chat.src" id='chat' name='chat' class='chat' ng-src="{{myTrustSrc(chat.src)}}"></iframe>

The function is only called a few times when ng-if isn't used. I still wonder why the function is called more than once with ng-src?

This is the function in the controller

$scope.myTrustSrc = function(src) {
    return $sce.trustAsResourceUrl(src);
}

Angular 4 HttpClient Query Parameters

I ended up finding it through the IntelliSense on the get() function. So, I'll post it here for anyone who is looking for similar information.

Anyways, the syntax is nearly identical, but slightly different. Instead of using URLSearchParams() the parameters need to be initialized as HttpParams() and the property within the get() function is now called params instead of search.

import { HttpClient, HttpParams } from '@angular/common/http';
getLogs(logNamespace): Observable<any> {

    // Setup log namespace query parameter
    let params = new HttpParams().set('logNamespace', logNamespace);

    return this._HttpClient.get(`${API_URL}/api/v1/data/logs`, { params: params })
}

I actually prefer this syntax as its a little more parameter agnostic. I also refactored the code to make it slightly more abbreviated.

getLogs(logNamespace): Observable<any> {

    return this._HttpClient.get(`${API_URL}/api/v1/data/logs`, {
        params: new HttpParams().set('logNamespace', logNamespace)
    })
}

Multiple Parameters

The best way I have found thus far is to define a Params object with all of the parameters I want to define defined within. As @estus pointed out in the comment below, there are a lot of great answers in This Question as to how to assign multiple parameters.

getLogs(parameters) {

    // Initialize Params Object
    let params = new HttpParams();

    // Begin assigning parameters
    params = params.append('firstParameter', parameters.valueOne);
    params = params.append('secondParameter', parameters.valueTwo);

    // Make the API call using the new parameters.
    return this._HttpClient.get(`${API_URL}/api/v1/data/logs`, { params: params })

Multiple Parameters with Conditional Logic

Another thing I often do with multiple parameters is allow the use of multiple parameters without requiring their presence in every call. Using Lodash, it's pretty simple to conditionally add/remove parameters from calls to the API. The exact functions used in Lodash or Underscores, or vanilla JS may vary depending on your application, but I have found that checking for property definition works pretty well. The function below will only pass parameters that have corresponding properties within the parameters variable passed into the function.

getLogs(parameters) {

    // Initialize Params Object
    let params = new HttpParams();

    // Begin assigning parameters
    if (!_.isUndefined(parameters)) {
        params = _.isUndefined(parameters.valueOne) ? params : params.append('firstParameter', parameters.valueOne);
        params = _.isUndefined(parameters.valueTwo) ? params : params.append('secondParameter', parameters.valueTwo);
    }

    // Make the API call using the new parameters.
    return this._HttpClient.get(`${API_URL}/api/v1/data/logs`, { params: params })

cursor.fetchall() vs list(cursor) in Python

If you are using the default cursor, a MySQLdb.cursors.Cursor, the entire result set will be stored on the client side (i.e. in a Python list) by the time the cursor.execute() is completed.

Therefore, even if you use

for row in cursor:

you will not be getting any reduction in memory footprint. The entire result set has already been stored in a list (See self._rows in MySQLdb/cursors.py).

However, if you use an SSCursor or SSDictCursor:

import MySQLdb
import MySQLdb.cursors as cursors

conn = MySQLdb.connect(..., cursorclass=cursors.SSCursor)

then the result set is stored in the server, mysqld. Now you can write

cursor = conn.cursor()
cursor.execute('SELECT * FROM HUGETABLE')
for row in cursor:
    print(row)

and the rows will be fetched one-by-one from the server, thus not requiring Python to build a huge list of tuples first, and thus saving on memory.

Otherwise, as others have already stated, cursor.fetchall() and list(cursor) are essentially the same.

How to change already compiled .class file without decompile?

You can change the code when you decompiled it, but it has to be recompiled to a class file, the decompiler outputs java code, this has to be recompiled with the same classpath as the original jar/class file

How can one change the timestamp of an old commit in Git?

Edit the author date and the commit date of the last 3 commits:

git rebase -i HEAD~3 --committer-date-is-author-date --exec "git commit --amend --no-edit --date=now"

The --exec command is appended after each line in the rebase and you can choose the author date with the --date=..., the committer date will be the same of author date.

Difference between an API and SDK

Application Programming Interface is a set of routines/data structures/classes which specifies a way to interact with the target platform/software like OS X, Android, project management application, virtualization software etc.

While Software Development Kit is a wrapper around API/s that makes the job easy for developers.

For example, Android SDK facilitates developers to interact with the Android platform as a whole while the platform itself is built by composite software components communicating via APIs.

Also, sometimes SDKs are built to facilitate development in a specific programming language. For example, Selenium web driver (built in Java) provides APIs to drive any browser natively, while capybara can be considered an an SDK that facilitates Ruby developers to use Selenium web driver. However, Selenium web driver is also an SDK by itself as it combines interaction with various native browser drivers into one package.

Android Debug Bridge (adb) device - no permissions

Had the same issue. It was a problem with udev rules. Tried a few of the rules mentioned above but didnot fix the issue. Found a set of rules here, https://github.com/M0Rf30/android-udev-rules. Followed the guide there and, voila, fixed.

Play local (hard-drive) video file with HTML5 video tag?

It is possible to play a local video file.

<input type="file" accept="video/*"/>
<video controls autoplay></video>

When a file is selected via the input element:

  1. 'change' event is fired
  2. Get the first File object from the input.files FileList
  3. Make an object URL that points to the File object
  4. Set the object URL to the video.src property
  5. Lean back and watch :)

http://jsfiddle.net/dsbonev/cCCZ2/embedded/result,js,html,css/

_x000D_
_x000D_
(function localFileVideoPlayer() {_x000D_
  'use strict'_x000D_
  var URL = window.URL || window.webkitURL_x000D_
  var displayMessage = function(message, isError) {_x000D_
    var element = document.querySelector('#message')_x000D_
    element.innerHTML = message_x000D_
    element.className = isError ? 'error' : 'info'_x000D_
  }_x000D_
  var playSelectedFile = function(event) {_x000D_
    var file = this.files[0]_x000D_
    var type = file.type_x000D_
    var videoNode = document.querySelector('video')_x000D_
    var canPlay = videoNode.canPlayType(type)_x000D_
    if (canPlay === '') canPlay = 'no'_x000D_
    var message = 'Can play type "' + type + '": ' + canPlay_x000D_
    var isError = canPlay === 'no'_x000D_
    displayMessage(message, isError)_x000D_
_x000D_
    if (isError) {_x000D_
      return_x000D_
    }_x000D_
_x000D_
    var fileURL = URL.createObjectURL(file)_x000D_
    videoNode.src = fileURL_x000D_
  }_x000D_
  var inputNode = document.querySelector('input')_x000D_
  inputNode.addEventListener('change', playSelectedFile, false)_x000D_
})()
_x000D_
video,_x000D_
input {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
input {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.info {_x000D_
  background-color: aqua;_x000D_
}_x000D_
_x000D_
.error {_x000D_
  background-color: red;_x000D_
  color: white;_x000D_
}
_x000D_
<h1>HTML5 local video file player example</h1>_x000D_
<div id="message"></div>_x000D_
<input type="file" accept="video/*" />_x000D_
<video controls autoplay></video>
_x000D_
_x000D_
_x000D_

Javascript Cookie with no expiration date

If you don't set an expiration date the cookie will expire at the end of the user's session. I recommend using the date right before unix epoch time will extend passed a 32-bit integer. To put that in the cookie you would use document.cookie = "randomCookie=true; expires=Tue, 19 Jan 2038 03:14:07 UTC;, assuming that randomCookie is the cookie you are setting and true is it's respective value.

How do I get a substring of a string in Python?

Maybe I missed it, but I couldn't find a complete answer on this page to the original question(s) because variables are not further discussed here. So I had to go on searching.

Since I'm not yet allowed to comment, let me add my conclusion here. I'm sure I was not the only one interested in it when accessing this page:

 >>>myString = 'Hello World'
 >>>end = 5

 >>>myString[2:end]
 'llo'

If you leave the first part, you get

 >>>myString[:end]
 'Hello' 

And if you left the : in the middle as well you got the simplest substring, which would be the 5th character (count starting with 0, so it's the blank in this case):

 >>>myString[end]
 ' '

Using array map to filter results with if conditional

Here's some info if someone comes upon this in 2019.

I think reduce vs map + filter might be somewhat dependent on what you need to loop through. Not sure on this but reduce does seem to be slower.

One thing is for sure - if you're looking for performance improvements the way you write the code is extremely important!

Here a JS perf test that shows the massive improvements when typing out the code fully rather than checking for "falsey" values (e.g. if (string) {...}) or returning "falsey" values where a boolean is expected.

Hope this helps someone

How to change the background color on a input checkbox with css?

I always use pseudo elements :before and :after for changing the appearance of checkboxes and radio buttons. it's works like a charm.

Refer this link for more info

CODEPEN

Steps

  1. Hide the default checkbox using css rules like visibility:hidden or opacity:0 or position:absolute;left:-9999px etc.
  2. Create a fake checkbox using :before element and pass either an empty or a non-breaking space '\00a0';
  3. When the checkbox is in :checked state, pass the unicode content: "\2713", which is a checkmark;
  4. Add :focus style to make the checkbox accessible.
  5. Done

Here is how I did it.

_x000D_
_x000D_
.box {_x000D_
  background: #666666;_x000D_
  color: #ffffff;_x000D_
  width: 250px;_x000D_
  padding: 10px;_x000D_
  margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
  margin: 1.5em 0;_x000D_
  padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
  visibility: hidden;_x000D_
}_x000D_
label {_x000D_
  cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
  border: 1px solid #333;_x000D_
  content: "\00a0";_x000D_
  display: inline-block;_x000D_
  font: 16px/1em sans-serif;_x000D_
  height: 16px;_x000D_
  margin: 0 .25em 0 0;_x000D_
  padding: 0;_x000D_
  vertical-align: top;_x000D_
  width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
  background: #fff;_x000D_
  color: #333;_x000D_
  content: "\2713";_x000D_
  text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
    outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
  <div class="box">_x000D_
    <p>_x000D_
      <input type="checkbox" id="c1" name="cb">_x000D_
      <label for="c1">Option 01</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c2" name="cb">_x000D_
      <label for="c2">Option 02</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c3" name="cb">_x000D_
      <label for="c3">Option 03</label>_x000D_
    </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Much more stylish using :before and :after

_x000D_
_x000D_
body{_x000D_
  font-family: sans-serif;  _x000D_
}_x000D_
_x000D_
.container {_x000D_
    margin-top: 50px;_x000D_
    margin-left: 20px;_x000D_
    margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
    width: 100%;_x000D_
    margin: 15px auto;_x000D_
    position: relative;_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
    width: auto;_x000D_
    opacity: 0.00000001;_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
    position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    top: 0;_x000D_
    margin: 4px;_x000D_
    width: 22px;_x000D_
    height: 22px;_x000D_
    transition: transform 0.28s ease;_x000D_
    border-radius: 3px;_x000D_
    border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
  content: '';_x000D_
    display: block;_x000D_
    width: 10px;_x000D_
    height: 5px;_x000D_
    border-bottom: 2px solid #7bbe72;_x000D_
    border-left: 2px solid #7bbe72;_x000D_
    -webkit-transform: rotate(-45deg) scale(0);_x000D_
    transform: rotate(-45deg) scale(0);_x000D_
    transition: transform ease 0.25s;_x000D_
    will-change: transform;_x000D_
    position: absolute;_x000D_
    top: 12px;_x000D_
    left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
    color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
    -webkit-transform: rotate(-45deg) scale(1);_x000D_
    transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
    min-height: 34px;_x000D_
    display: block;_x000D_
    padding-left: 40px;_x000D_
    margin-bottom: 0;_x000D_
    font-weight: normal;_x000D_
    cursor: pointer;_x000D_
    vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    -webkit-transform: translateY(-50%);_x000D_
    transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
    outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox" name="" value="">_x000D_
     <label for="checkbox"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
_x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox2" name="" value="">_x000D_
     <label for="checkbox2"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Delete all rows in table

As other have said, TRUNCATE TABLE is far quicker, but it does have some restrictions (taken from here):

You cannot use TRUNCATE TABLE on tables that:

- Are referenced by a FOREIGN KEY constraint. (You can truncate a table that has a foreign key that references itself.)
- Participate in an indexed view.
- Are published by using transactional replication or merge replication.

For tables with one or more of these characteristics, use the DELETE statement instead.

The biggest drawback is that if the table you are trying to empty has foreign keys pointing to it, then the truncate call will fail.

How do I check if an object's type is a particular subclass in C++?

#include <stdio.h>
#include <iostream.h>

class Base
{
  public: virtual ~Base() {}

  template<typename T>
  bool isA() {
    return (dynamic_cast<T*>(this) != NULL);
  }
};

class D1: public Base {};
class D2: public Base {};
class D22: public D2 {};

int main(int argc,char* argv[]);
{
  D1*   d1  = new D1();
  D2*   d2  = new D2();
  D22*  d22 = new D22();

  Base*  x = d22;

  if( x->isA<D22>() )
  {
    std::cout << "IS A D22" << std::endl;
  }
  if( x->isA<D2>() )
  {
    std::cout << "IS A D2" << std::endl;
  }
  if( x->isA<D1>() )
  {
    std::cout << "IS A D1" << std::endl;
  }
  if(x->isA<Base>() )
  {
    std::cout << "IS A Base" << std::endl;
  }
}

Result:

IS A D22
IS A D2
IS A Base

jQuery: How to get to a particular child of a parent?

$(this).parent()

Tree traversal is fun

$(this).parent().siblings(".something1");

$(this).parent().prev(); // if you always want the parent's previous sibling

$(this).parents(".box").children(".something1");

And much more ways, you might find these docs helpful.

CSS Animation onClick

Add a

-webkit-animation-play-state: paused;

to your CSS file, then you can control whether the animation is running or not by using this JS line:

document.getElementById("myDIV").style.WebkitAnimationPlayState = "running";

if you want the animation to run once, every time you click. Remember to set

-webkit-animation-iteration-count: 1;

CROSS JOIN vs INNER JOIN in SQL

Here is the best example of Cross Join and Inner Join.

Consider the following tables

TABLE : Teacher

x------------------------x
| TchrId   | TeacherName | 
x----------|-------------x
|    T1    |    Mary     |
|    T2    |    Jim      |
x------------------------x

TABLE : Student

x--------------------------------------x
|  StudId  |    TchrId   | StudentName | 
x----------|-------------|-------------x            
|    S1    |     T1      |    Vineeth  |
|    S2    |     T1      |    Unni     |
x--------------------------------------x

1. INNER JOIN

Inner join selects the rows that satisfies both the table.

Consider we need to find the teachers who are class teachers and their corresponding students. In that condition, we need to apply JOIN or INNER JOIN and will

enter image description here

Query

SELECT T.TchrId,T.TeacherName,S.StudentName 
FROM #Teacher T
INNER JOIN #Student S ON T.TchrId = S.TchrId

Result

x--------------------------------------x
|  TchrId  | TeacherName | StudentName | 
x----------|-------------|-------------x            
|    T1    |     Mary    |    Vineeth  |
|    T1    |     Mary    |    Unni     |
x--------------------------------------x

2. CROSS JOIN

Cross join selects the all the rows from the first table and all the rows from second table and shows as Cartesian product ie, with all possibilities

Consider we need to find all the teachers in the school and students irrespective of class teachers, we need to apply CROSS JOIN.

enter image description here

Query

SELECT T.TchrId,T.TeacherName,S.StudentName 
FROM #Teacher T
CROSS JOIN #Student S 

Result

x--------------------------------------x
|  TchrId  | TeacherName | StudentName | 
x----------|-------------|-------------x            
|    T2    |     Jim     |    Vineeth  |
|    T2    |     Jim     |    Unni     |
|    T1    |     Mary    |    Vineeth  |
|    T1    |     Mary    |    Unni     |
x--------------------------------------x

Python Pylab scatter plot error bars (the error on each point is unique)

>>> import matplotlib.pyplot as plt
>>> a = [1,3,5,7]
>>> b = [11,-2,4,19]
>>> plt.pyplot.scatter(a,b)
>>> plt.scatter(a,b)
<matplotlib.collections.PathCollection object at 0x00000000057E2CF8>
>>> plt.show()
>>> c = [1,3,2,1]
>>> plt.errorbar(a,b,yerr=c, linestyle="None")
<Container object of 3 artists>
>>> plt.show()

where a is your x data b is your y data c is your y error if any

note that c is the error in each direction already

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

https://services.gradle.org/distributions/gradle-2.1-all.zip

open this link in the browser and download the zip file and extract it to folder

Before extraction please delete the old folder whose name ends gradle-2.1-all and then you can start extracting

if you are window user extract it to this folder

C:\Users{Your-Name}.gradle\wrapper\dists

after that just restart your android studio. I hope it works it works for me .

User GETDATE() to put current date into SQL variable

You can also use CURRENT_TIMESTAMP for this.

According to BOL CURRENT_TIMESTAMP is the ANSI SQL euivalent to GETDATE()

DECLARE @LastChangeDate AS DATE;
SET @LastChangeDate = CURRENT_TIMESTAMP;

How do I find which transaction is causing a "Waiting for table metadata lock" state?

SHOW ENGINE INNODB STATUS \G

Look for the Section -

TRANSACTIONS

We can use INFORMATION_SCHEMA Tables.

Useful Queries

To check about all the locks transactions are waiting for:

USE INFORMATION_SCHEMA;
SELECT * FROM INNODB_LOCK_WAITS;

A list of blocking transactions:

SELECT * 
FROM INNODB_LOCKS 
WHERE LOCK_TRX_ID IN (SELECT BLOCKING_TRX_ID FROM INNODB_LOCK_WAITS);

OR

SELECT INNODB_LOCKS.* 
FROM INNODB_LOCKS
JOIN INNODB_LOCK_WAITS
  ON (INNODB_LOCKS.LOCK_TRX_ID = INNODB_LOCK_WAITS.BLOCKING_TRX_ID);

A List of locks on particular table:

SELECT * FROM INNODB_LOCKS 
WHERE LOCK_TABLE = db_name.table_name;

A list of transactions waiting for locks:

SELECT TRX_ID, TRX_REQUESTED_LOCK_ID, TRX_MYSQL_THREAD_ID, TRX_QUERY
FROM INNODB_TRX
WHERE TRX_STATE = 'LOCK WAIT';

Reference - MySQL Troubleshooting: What To Do When Queries Don't Work, Chapter 6 - Page 96.

SQL Inner-join with 3 tables?

SELECT 
A.P_NAME AS [INDIVIDUAL NAME],B.F_DETAIL AS [INDIVIDUAL FEATURE],C.PL_PLACE AS [INDIVIDUAL LOCATION]
FROM 
[dbo].[PEOPLE] A
INNER JOIN 
[dbo].[FEATURE] B ON A.P_FEATURE = B.F_ID
INNER JOIN 
[dbo].[PEOPLE_LOCATION] C ON A.P_LOCATION = C.PL_ID

python: SyntaxError: EOL while scanning string literal

In my situation, I had \r\n in my single-quoted dictionary strings. I replaced all instances of \r with \\r and \n with \\n and it fixed my issue, properly returning escaped line breaks in the eval'ed dict.

ast.literal_eval(my_str.replace('\r','\\r').replace('\n','\\n'))
  .....

403 Forbidden vs 401 Unauthorized HTTP responses

I think it is important to consider that, to a browser, 401 initiates an authentication dialog for the user to enter new credentials, while 403 does not. Browsers think that, if a 401 is returned, then the user should re-authenticate. So 401 stands for invalid authentication while 403 stands for a lack of permission.

Here are some cases under that logic where an error would be returned from authentication or authorization, with important phrases bolded.

  • A resource requires authentication but no credentials were specified.

401: The client should specify credentials.

  • The specified credentials are in an invalid format.

400: That's neither 401 nor 403, as syntax errors should always return 400.

  • The specified credentials reference a user which does not exist.

401: The client should specify valid credentials.

  • The specified credentials are invalid but specify a valid user (or don't specify a user if a specified user is not required).

401: Again, the client should specify valid credentials.

  • The specified credentials have expired.

401: This is practically the same as having invalid credentials in general, so the client should specify valid credentials.

  • The specified credentials are completely valid but do not suffice the particular resource, though it is possible that credentials with more permission could.

403: Specifying valid credentials would not grant access to the resource, as the current credentials are already valid but only do not have permission.

  • The particular resource is inaccessible regardless of credentials.

403: This is regardless of credentials, so specifying valid credentials cannot help.

  • The specified credentials are completely valid but the particular client is blocked from using them.

403: If the client is blocked, specifying new credentials will not do anything.

eslint: error Parsing error: The keyword 'const' is reserved

ESLint defaults to ES5 syntax-checking. You'll want to override to the latest well-supported version of JavaScript.

Try adding a .eslintrc file to your project. Inside it:

{
    "parserOptions": {
        "ecmaVersion": 2017
    },

    "env": {
        "es6": true
    }
}

Hopefully this helps.

EDIT: I also found this example .eslintrc which might help.

C function that counts lines in file

while(!feof(fp))
{
  ch = fgetc(fp);
  if(ch == '\n')
  {
    lines++;
  }
}

But please note: Why is “while ( !feof (file) )” always wrong?.

Difference between x86, x32, and x64 architectures?

Hans and DarkDust answer covered i386/i686 and amd64/x86_64, so there's no sense in revisiting them. This answer will focus on X32, and provide some info learned after a X32 port.

x32 is an ABI for amd64/x86_64 CPUs using 32-bit integers, longs and pointers. The idea is to combine the smaller memory and cache footprint from 32-bit data types with the larger register set of x86_64. (Reference: Debian X32 Port page).

x32 can provide up to about 30% reduction in memory usage and up to about 40% increase in speed. The use cases for the architecture are:

  • vserver hosting (memory bound)
  • netbooks/tablets (low memory, performance)
  • scientific tasks (performance)

x32 is a somewhat recent addition. It requires kernel support (3.4 and above), distro support (see below), libc support (2.11 or above), and GCC 4.8 and above (improved address size prefix support).

For distros, it was made available in Ubuntu 13.04 or Fedora 17. Kernel support only required pointer to be in the range from 0x00000000 to 0xffffffff. From the System V Application Binary Interface, AMD64 (With LP64 and ILP32 Programming Models), Section 10.4, p. 132 (its the only sentence):

10.4 Kernel Support
Kernel should limit stack and addresses returned from system calls between 0x00000000 to 0xffffffff.

When booting a kernel with the support, you must use syscall.x32=y option. When building a kernel, you must include the CONFIG_X86_X32=y option. (Reference: Debian X32 Port page and X32 System V Application Binary Interface).


Here is some of what I have learned through a recent port after the Debian folks reported a few bugs on us after testing:

  • the system is a lot like X86
  • the preprocessor defines __x86_64__ (and friends) and __ILP32__, but not __i386__/__i686__ (and friends)
  • you cannot use __ILP32__ alone because it shows up unexpectedly under Clang and Sun Studio
  • when interacting with the stack, you must use the 64-bit instructions pushq and popq
  • once a register is populated/configured from 32-bit data types, you can perform the 64-bit operations on them, like adcq
  • be careful of the 0-extension that occurs on the upper 32-bits.

If you are looking for a test platform, then you can use Debian 8 or above. Their wiki page at Debian X32 Port has all the information. The 3-second tour: (1) enable X32 in the kernel at boot; (2) use debootstrap to install the X32 chroot environment, and (3) chroot debian-x32 to enter into the environment and test your software.

How to parse JSON and access results

The main problem with your example code is that the $result variable you use to store the output of curl_exec() does not contain the body of the HTTP response - it contains the value true. If you try to print_r() that, it will just say "1".

The curl_exec() reference explains:

Return Values

Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.

So if you want to get the HTTP response body in your $result variable, you must first run

curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);

After that, you can call json_decode() on $result, as other answers have noted.

On a general note - the curl library for PHP is useful and has a lot of features to handle the minutia of HTTP protocol (and others), but if all you want is to GET some resource or even POST to some URL, and read the response - then file_get_contents() is all you'll ever need: it is much simpler to use and have much less surprising behavior to worry about.

plot a circle with pyplot

Hello I have written a code for drawing a circle. It will help for drawing all kind of circles. The image shows the circle with radius 1 and center at 0,0 The center and radius can be edited of any choice.

## Draw a circle with center and radius defined
## Also enable the coordinate axes
import matplotlib.pyplot as plt
import numpy as np
# Define limits of coordinate system
x1 = -1.5
x2 = 1.5
y1 = -1.5
y2 = 1.5

circle1 = plt.Circle((0,0),1, color = 'k', fill = False, clip_on = False)
fig, ax = plt.subplots()
ax.add_artist(circle1)
plt.axis("equal")
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
plt.xlim(left=x1)
plt.xlim(right=x2)
plt.ylim(bottom=y1)
plt.ylim(top=y2)
plt.axhline(linewidth=2, color='k')
plt.axvline(linewidth=2, color='k')

##plt.grid(True)
plt.grid(color='k', linestyle='-.', linewidth=0.5)
plt.show()

Good luck

Is it possible to get a history of queries made in postgres

FYI for those using the UI Navicat:

You MUST set your preferences to utilize a file as to where to store the history.

If this is blank your Navicat will be blank.

enter image description here

PS: I have no affiliation with or in association to Navicat or it's affiliates. Just looking to help.

Good Free Alternative To MS Access

The Access runtime license has never been all that expensive -- the cost for the developer tools/extensions has been around $300 as long as I can remember (which would be as far back to the Access 2 Developers Toolkit, or ADT), but that gives you the ability to distribute your app with the runtime to an unlimited number of users. As long as your runtime app was used by three or more users, you'd have been saving money (assuming a cost of $100/user to install a full copy of Access).

The runtime for Access 2007 is completely free, but really, the cost before that was not all that great.

Marc Gravell added (in what should have been a comment, in my opinion):
Being free, though, is certainly an encouragement for people to try it out which the $300 price really would have discouraged.

importing jar libraries into android-studio

If the code for your jar library is on GitHub then importing into Android Studio is easy with JitPack.

Your will just need to add the repository to build.gradle:

allprojects{
 repositories {
    jcenter()
    maven { url "https://jitpack.io" }
 }
}

and then the library's GitHub repository as a dependency:

dependencies {
    // ...
    compile 'com.github.YourUsername:LibraryRepo:ReleaseTag'
}

JitPack acts as a maven repository and can be used like Maven Central. The nice thing is that you don't have to upload the jar manually. Behind the scenes JitPack will check out the code from GitHub and compile it. Therefore it works only if the repo has a build file in it (build.gradle).

There is also a guide on how to prepare an Android project.

How to draw border on just one side of a linear layout?

An other great example example

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
<inset xmlns:android="http://schemas.android.com/apk/res/android"
     android:insetRight="-2dp">

     <shape android:shape="rectangle">
         <corners
             android:bottomLeftRadius="4dp"
             android:bottomRightRadius="0dp"
             android:topLeftRadius="4dp"
             android:topRightRadius="0dp" />
         <stroke
             android:width="1dp"
             android:color="@color/nasty_green" />
         <solid android:color="@android:color/transparent" />
     </shape>

</inset>

Objective C - Assign, Copy, Retain

The Memory Management Programming Guide from the iOS Reference Library has basics of assign, copy, and retain with analogies and examples.

copy Makes a copy of an object, and returns it with retain count of 1. If you copy an object, you own the copy. This applies to any method that contains the word copy where “copy” refers to the object being returned.

retain Increases the retain count of an object by 1. Takes ownership of an object.

release Decreases the retain count of an object by 1. Relinquishes ownership of an object.

Accessing attributes from an AngularJS directive

Although using '@' is more appropriate than using '=' for your particular scenario, sometimes I use '=' so that I don't have to remember to use attrs.$observe():

<su-label tooltip="field.su_documentation">{{field.su_name}}</su-label>

Directive:

myApp.directive('suLabel', function() {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        scope: {
            title: '=tooltip'
        },
        template: '<label><a href="#" rel="tooltip" title="{{title}}" data-placement="right" ng-transclude></a></label>',
        link: function(scope, element, attrs) {
            if (scope.title) {
                element.addClass('tooltip-title');
            }
        },
    }
});

Fiddle.

With '=' we get two-way databinding, so care must be taken to ensure scope.title is not accidentally modified in the directive. The advantage is that during the linking phase, the local scope property (scope.title) is defined.

How can I draw circle through XML Drawable - Android?

no need for the padding or the corners.

here's a sample:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
    <gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
        android:angle="270"/>
</shape>

based on :

https://stackoverflow.com/a/10104037/878126

How to resolve the C:\fakepath?

I am happy that browsers care to save us from intrusive scripts and the like. I am not happy with IE putting something into the browser that makes a simple style-fix look like a hack-attack!

I've used a < span > to represent the file-input so that I could apply appropriate styling to the < div > instead of the < input > (once again, because of IE). Now due to this IE want's to show the User a path with a value that's just guaranteed to put them on guard and in the very least apprehensive (if not totally scare them off?!)... MORE IE-CRAP!

Anyhow, thanks to to those who posted the explanation here: IE Browser Security: Appending "fakepath" to file path in input[type="file"], I've put together a minor fixer-upper...

The code below does two things - it fixes a lte IE8 bug where the onChange event doesn't fire until the upload field's onBlur and it updates an element with a cleaned filepath that won't scare the User.

// self-calling lambda to for jQuery shorthand "$" namespace
(function($){
    // document onReady wrapper
    $().ready(function(){
        // check for the nefarious IE
        if($.browser.msie) {
            // capture the file input fields
            var fileInput = $('input[type="file"]');
            // add presentational <span> tags "underneath" all file input fields for styling
            fileInput.after(
                $(document.createElement('span')).addClass('file-underlay')
            );
            // bind onClick to get the file-path and update the style <div>
            fileInput.click(function(){
                // need to capture $(this) because setTimeout() is on the
                // Window keyword 'this' changes context in it
                var fileContext = $(this);
                // capture the timer as well as set setTimeout()
                // we use setTimeout() because IE pauses timers when a file dialog opens
                // in this manner we give ourselves a "pseudo-onChange" handler
                var ieBugTimeout = setTimeout(function(){
                    // set vars
                    var filePath     = fileContext.val(),
                        fileUnderlay = fileContext.siblings('.file-underlay');
                    // check for IE's lovely security speil
                    if(filePath.match(/fakepath/)) {
                        // update the file-path text using case-insensitive regex
                        filePath = filePath.replace(/C:\\fakepath\\/i, '');
                    }
                    // update the text in the file-underlay <span>
                    fileUnderlay.text(filePath);
                    // clear the timer var
                    clearTimeout(ieBugTimeout);
                }, 10);
            });
        }
    });
})(jQuery);

send/post xml file using curl command line

With Jenkins 1.494, I was able to send a file to a job parameter on Ubuntu Linux 12.10 using curl with --form parameters:

curl --form name=myfileparam --form file=@/local/path/to/your/file.xml \
  -Fjson='{"parameter": {"name": "myfileparam", "file": "file"}}' \
  -Fsubmit=Build \
  http://user:password@jenkinsserver/job/jobname/build

On the Jenkins server, I configured a job that accepts a single parameter: a file upload parameter named myfileparam.

The first line of that curl call constructs a web form with a parameter named myfileparam (same as in the job); its value will be the contents of a file on the local file system named /local/path/to/your/file.txt. The @ symbol prefix tells curl to send a local file instead of the given filename.

The second line defines a JSON request that matches the form parameters on line one: a file parameter named myfileparam.

The third line activates the form's Build button. The forth line is the job URL with the "/build" suffix.

If this call is successful, curl returns 0. If it is unsuccessful, the error or exception from the service is printed to the console. This answer takes a lot from an old blog post relating to Hudson, which I deconstructed and re-worked for my own needs.

Uploading file using POST request in Node.js

Looks like you're already using request module.

in this case all you need to post multipart/form-data is to use its form feature:

var req = request.post(url, function (err, resp, body) {
  if (err) {
    console.log('Error!');
  } else {
    console.log('URL: ' + body);
  }
});
var form = req.form();
form.append('file', '<FILE_DATA>', {
  filename: 'myfile.txt',
  contentType: 'text/plain'
});

but if you want to post some existing file from your file system, then you may simply pass it as a readable stream:

form.append('file', fs.createReadStream(filepath));

request will extract all related metadata by itself.

For more information on posting multipart/form-data see node-form-data module, which is internally used by request.

WPF: Create a dialog / prompt

You don't need ANY of these other fancy answers. Below is a simplistic example that doesn't have all the Margin, Height, Width properties set in the XAML, but should be enough to show how to get this done at a basic level.

XAML
Build a Window page like you would normally and add your fields to it, say a Label and TextBox control inside a StackPanel:

<StackPanel Orientation="Horizontal">
    <Label Name="lblUser" Content="User Name:" />
    <TextBox Name="txtUser" />
</StackPanel>

Then create a standard Button for Submission ("OK" or "Submit") and a "Cancel" button if you like:

<StackPanel Orientation="Horizontal">
    <Button Name="btnSubmit" Click="btnSubmit_Click" Content="Submit" />
    <Button Name="btnCancel" Click="btnCancel_Click" Content="Cancel" />
</StackPanel>

Code-Behind
You'll add the Click event handler functions in the code-behind, but when you go there, first, declare a public variable where you will store your textbox value:

public static string strUserName = String.Empty;

Then, for the event handler functions (right-click the Click function on the button XAML, select "Go To Definition", it will create it for you), you need a check to see if your box is empty. You store it in your variable if it is not, and close your window:

private void btnSubmit_Click(object sender, RoutedEventArgs e)
{        
    if (!String.IsNullOrEmpty(txtUser.Text))
    {
        strUserName = txtUser.Text;
        this.Close();
    }
    else
        MessageBox.Show("Must provide a user name in the textbox.");
}

Calling It From Another Page
You're thinking, if I close my window with that this.Close() up there, my value is gone, right? NO!! I found this out from another site: http://www.dreamincode.net/forums/topic/359208-wpf-how-to-make-simple-popup-window-for-input/

They had a similar example to this (I cleaned it up a bit) of how to open your Window from another and retrieve the values:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void btnOpenPopup_Click(object sender, RoutedEventArgs e)
    {
        MyPopupWindow popup = new MyPopupWindow();  // this is the class of your other page

        //ShowDialog means you can't focus the parent window, only the popup
        popup.ShowDialog(); //execution will block here in this method until the popup closes

        string result = popup.strUserName;
        UserNameTextBlock.Text = result;  // should show what was input on the other page
    }
}

Cancel Button
You're thinking, well what about that Cancel button, though? So we just add another public variable back in our pop-up window code-behind:

public static bool cancelled = false;

And let's include our btnCancel_Click event handler, and make one change to btnSubmit_Click:

private void btnCancel_Click(object sender, RoutedEventArgs e)
{        
    cancelled = true;
    strUserName = String.Empty;
    this.Close();
}

private void btnSubmit_Click(object sender, RoutedEventArgs e)
{        
    if (!String.IsNullOrEmpty(txtUser.Text))
    {
        strUserName = txtUser.Text;
        cancelled = false;  // <-- I add this in here, just in case
        this.Close();
    }
    else
        MessageBox.Show("Must provide a user name in the textbox.");
}

And then we just read that variable in our MainWindow btnOpenPopup_Click event:

private void btnOpenPopup_Click(object sender, RoutedEventArgs e)
{
    MyPopupWindow popup = new MyPopupWindow();  // this is the class of your other page
    //ShowDialog means you can't focus the parent window, only the popup
    popup.ShowDialog(); //execution will block here in this method until the popup closes

    // **Here we find out if we cancelled or not**
    if (popup.cancelled == true)
        return;
    else
    {
        string result = popup.strUserName;
        UserNameTextBlock.Text = result;  // should show what was input on the other page
    }
}

Long response, but I wanted to show how easy this is using public static variables. No DialogResult, no returning values, nothing. Just open the window, store your values with the button events in the pop-up window, then retrieve them afterwards in the main window function.

How to sort List<Integer>?

Just use Collections.sort(yourListHere) here to sort.

You can read more about Collections from here.

Handling key-press events (F1-F12) using JavaScript and jQuery, cross-browser

You can do this with jquery like this:

        $("#elemenId").keydown(function (e) {
            if(e.key == "F12"){
                console.log(e.key);
            }

        });

Can I pass column name as input parameter in SQL stored Procedure

You can pass the column name but you cannot use it in a sql statemnt like

Select @Columnname From Table

One could build a dynamic sql string and execute it like EXEC (@SQL)

For more information see this answer on dynamic sql.

Dynamic SQL Pros and Cons

Best tool for inspecting PDF files?

There is also another option. Adobe Acrobat Pro is also able to display the internal tree structure of the PDF.

  1. Open Preflight
  2. Go to Options (right upper corner)
  3. Internal PDF Structure

On top Adobe Acrobat Pro can also display the internal structure of the Document Fonts in the PDF most of other "PDF tree structure viewer" don't have this otion

enter image description here

Git for Windows: .bashrc or equivalent configuration files for Git Bash shell

Sometimes the files are actually located at ~/. These are the steps I took to starting Zsh as the default terminal on Visual Studio Code/Windows 10.

  • cd ~/

  • vim .bashrc

  • Paste the following...

if test -t 1; then exec zsh fi

  • Save/close Vim.

  • Restart the terminal

How to split the name string in mysql?

To get the rest of the string after the second instance of the space delimiter

SELECT
   SUBSTRING_INDEX(SUBSTRING_INDEX('Sachin ramesh tendulkar', ' ', 1), ' ', -1) AS first_name, 
       SUBSTRING_INDEX(SUBSTRING_INDEX('Sachin ramesh tendulkar', ' ', 2), ' ', -1) 
           AS middle_name,
   SUBSTRING('Sachin ramesh tendulkar',LENGTH(SUBSTRING_INDEX('Sachin ramesh tendulkar', ' ', 2))+1) AS last_name

Loop through all nested dictionary values?

Here is pythonic way to do it. This function will allow you to loop through key-value pair in all the levels. It does not save the whole thing to the memory but rather walks through the dict as you loop through it

def recursive_items(dictionary):
    for key, value in dictionary.items():
        if type(value) is dict:
            yield (key, value)
            yield from recursive_items(value)
        else:
            yield (key, value)

a = {'a': {1: {1: 2, 3: 4}, 2: {5: 6}}}

for key, value in recursive_items(a):
    print(key, value)

Prints

a {1: {1: 2, 3: 4}, 2: {5: 6}}
1 {1: 2, 3: 4}
1 2
3 4
2 {5: 6}
5 6

'cout' was not declared in this scope

Use std::cout, since cout is defined within the std namespace. Alternatively, add a using std::cout; directive.

Setting the focus to a text field

I'm not sure if I'm missing something here, but there's no reason why you can't add a listener to your panel.

In Netbeans, just hit the "Source" button in the top left of the editor window and you can edit most of the code. The actual layout code is mostly locked, but you can even customize that if you need to.

As far as I'm aware, txtMessage.requestFocusInWindow() is supposed to set up the default focus for when the window is displayed the first time. If you want to request the focus after the window has been displayed already, you should use txtMessage.requestFocus()

For testing, you can just add a listener in the constructor:

addWindowListener(new WindowAdapter(){ 
  public void windowOpened( WindowEvent e){ 
    txtMessage.requestFocus();
  } 
}); 

The number of method references in a .dex file cannot exceed 64k API 17

Just a side comment, Before adding support for multidex - make sure you are not adding unnecessary dependencies.

For example In the official Facebook analytics guide

They clearly state that you should add the following dependency:

implementation 'com.facebook.android:facebook-android-sdk:[4,5)'

which is actually the entire FacebookSDK - so if you need for example just the Analytics you need to replace it with:

implementation 'com.facebook.android:facebook-core:5.+'

Facebook partial SDK options

Is there a way to use use text as the background with CSS?

You can have an absolutely positioned element inside of your relative positioned element:

_x000D_
_x000D_
#container {
   position: relative;
}

#background {
   position: absolute;
   top: 0;
   left: 0;
   bottom: 0;
   right: 0;
   z-index: -1;
   overflow: hidden;
}
_x000D_
<div id="container">
    <div id="background">
    Text to have as background
    </div>
    Normal contents
</div>
_x000D_
_x000D_
_x000D_

Here's an example of it.

What's the difference between a proxy server and a reverse proxy server?

Difference between Proxy server (also called forward proxy) and Reverse Proxy Server depends on the point of reference.

Technically, both are exactly the same. Both serve the same purpose of transmitting data to a destination on behalf of a source.

The difference lies in 'on whose behalf is the proxy server acting / who is the proxy server representing?'

If the proxy server is forwarding requests to internet server on behalf of the end users (Example: students in a college accessing internet through college proxy server.), then the proxy is called 'Forward proxy' or simply 'Proxy'.

If the proxy server is responding to incoming requests, on behalf of a server, then the proxy is called 'Reverse Proxy', as it is working in the reverse direction, from the point of view of the end user.

Some Examples of Reverse proxies:

  1. Load balancer in front of web servers acts as a reverse-proxy on behalf of the actual web servers.
  2. API gateway
  3. Free Website hosting services like (facebook pages / blog page servers) are also reverse proxies. The actual content may be in some web server, but the outside world knows it through specific url advertised by reverse-proxy.

Use of forward proxy:

  1. Monitor all outbound internet connections from an organization
  2. Apply security policies on internet browsing and block malicious content from being downloaded
  3. Block access to specific websites

Use of Reverse proxy:

  1. Present friendly URL for a website
  2. Perform load balancing across multiple web servers
  3. Apply security policy and protect actual web servers from attacks

Error converting data types when importing from Excel to SQL Server 2008

Going off of what Derloopkat said, which still can fail on conversion (no offense Derloopkat) because Excel is terrible at this:

  1. Paste from excel into Notepad and save as normal (.txt file).
  2. From within excel, open said .txt file.
  3. Select next as it is obviously tab delimited.
  4. Select "none" for text qualifier, then next again.
  5. Select the first row, hold shift, select the last row, and select the text radial button. Click Finish

It will open, check it to make sure it's accurate and then save as an excel file.

A good Sorted List for Java

This is the SortedList implementation I am using. Maybe this helps with your problem:

import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
/**
 * This class is a List implementation which sorts the elements using the
 * comparator specified when constructing a new instance.
 * 
 * @param <T>
 */
public class SortedList<T> extends ArrayList<T> {
    /**
     * Needed for serialization.
     */
    private static final long serialVersionUID = 1L;
    /**
     * Comparator used to sort the list.
     */
    private Comparator<? super T> comparator = null;
    /**
     * Construct a new instance with the list elements sorted in their
     * {@link java.lang.Comparable} natural ordering.
     */
    public SortedList() {
    }
    /**
     * Construct a new instance using the given comparator.
     * 
     * @param comparator
     */
    public SortedList(Comparator<? super T> comparator) {
        this.comparator = comparator;
    }
    /**
     * Construct a new instance containing the elements of the specified
     * collection with the list elements sorted in their
     * {@link java.lang.Comparable} natural ordering.
     * 
     * @param collection
     */
    public SortedList(Collection<? extends T> collection) {
        addAll(collection);
    }
    /**
     * Construct a new instance containing the elements of the specified
     * collection with the list elements sorted using the given comparator.
     * 
     * @param collection
     * @param comparator
     */
    public SortedList(Collection<? extends T> collection, Comparator<? super T> comparator) {
        this(comparator);
        addAll(collection);
    }
    /**
     * Add a new entry to the list. The insertion point is calculated using the
     * comparator.
     * 
     * @param paramT
     * @return <code>true</code> if this collection changed as a result of the call.
     */
    @Override
    public boolean add(T paramT) {
        int initialSize = this.size();
        // Retrieves the position of an existing, equal element or the 
        // insertion position for new elements (negative).
        int insertionPoint = Collections.binarySearch(this, paramT, comparator);
        super.add((insertionPoint > -1) ? insertionPoint : (-insertionPoint) - 1, paramT);
        return (this.size() != initialSize);
    }
    /**
     * Adds all elements in the specified collection to the list. Each element
     * will be inserted at the correct position to keep the list sorted.
     * 
     * @param paramCollection
     * @return <code>true</code> if this collection changed as a result of the call.
     */
    @Override
    public boolean addAll(Collection<? extends T> paramCollection) {
        boolean result = false;
        if (paramCollection.size() > 4) {
            result = super.addAll(paramCollection);
            Collections.sort(this, comparator);
        }
        else {
            for (T paramT:paramCollection) {
                result |= add(paramT);
            }
        }
        return result;
    }
    /**
     * Check, if this list contains the given Element. This is faster than the
     * {@link #contains(Object)} method, since it is based on binary search.
     * 
     * @param paramT
     * @return <code>true</code>, if the element is contained in this list;
     * <code>false</code>, otherwise.
     */
    public boolean containsElement(T paramT) {
        return (Collections.binarySearch(this, paramT, comparator) > -1);
    }
    /**
     * @return The comparator used for sorting this list.
     */
    public Comparator<? super T> getComparator() {
        return comparator;
    }
    /**
     * Assign a new comparator and sort the list using this new comparator.
     * 
     * @param comparator
     */
    public void setComparator(Comparator<? super T> comparator) {
        this.comparator = comparator;
        Collections.sort(this, comparator);
    }
}

This solution is very flexible and uses existing Java functions:

  • Completely based on generics
  • Uses java.util.Collections for finding and inserting list elements
  • Option to use a custom Comparator for list sorting

Some notes:

  • This sorted list is not synchronized since it inherits from java.util.ArrayList. Use Collections.synchronizedList if you need this (refer to the Java documentation for java.util.ArrayList for details).
  • The initial solution was based on java.util.LinkedList. For better performance, specifically for finding the insertion point (Logan's comment) and quicker get operations (https://dzone.com/articles/arraylist-vs-linkedlist-vs), this has been changed to java.util.ArrayList.

Could not open ServletContext resource

I think currently the application-context.xml file is into src/main/resources AND the social.properties file is into src/main/java... so when you package (mvn package) or when you run tomcat (mvn tomcat:run) your social.properties disappeared (I know you said when you checked into the .war the files are here... but your exception says the opposite).

The solution is simply to put all your configuration files (application-context.xml and social.properties) into src/main/resources to follow the maven standard structure.

Javascript onclick hide div

Simple & Best way:

onclick="parentNode.remove()"

Deletes the complete parent from html

How to return a part of an array in Ruby?

another way is to use the range method

foo = [1,2,3,4,5,6]
bar = [10,20,30,40,50,60]
a = foo[0...3]
b = bar[3...6]

print a + b 
=> [1, 2, 3, 40, 50 , 60]

Using SQL LOADER in Oracle to import CSV file

If your text is: Joe said, "Fred was here with his "Wife"".
This is saved in a CSV as:
"Joe said, ""Fred was here with his ""Wife""""."
(Rule is double quotes go around the whole field, and double quotes are converted to two double quotes). So a simple Optionally Enclosed By clause is needed but not sufficient. CSVs are tough due to this rule. You can sometimes use a Replace clause in the loader for that field but depending on your data this may not be enough. Often pre-processing of a CSV is needed to load in Oracle. Or save it as an XLS and use Oracle SQL Developer app to import to the table - great for one-time work, not so good for scripting.

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

The most simple and used by everyone mostly is javascript:void(0) You can use it instead of using # to stop tag redirect to header section.

<a href="javascript:void(0)" onclick="testFunction();">Click To check Function</a>

function testFunction() {
    alert("hello world");
}

Get ID of element that called a function

You can code the handler setup like this:

<area id="nose" shape="rect" coords="280,240,330,275" onmouseover="zoom.call(this)"/>

Then this in your handler will refer to the element. Now, I'll offer the caveat that I'm not 100% sure what happens when you've got a handler in an <area> tag, largely because I haven't seen an <area> tag in like a decade or so. I think it should give you the image tag, but that could be wrong.

edit — yes, it's wrong - you get the <area> tag, not the <img>. So you'll have to get that element's parent (the map), and then find the image that's using it (that is, the <img> whose "usemap" attribute refers to the map's name).

edit again — except it doesn't matter because you want the area's "id" durr. Sorry for not reading correctly.

Class name does not name a type in C++

It actually happend to me because I mistakenly named the source file "something.c" instead of "something.cpp". I hope this helps someone who has the same error.

How do you set up use HttpOnly cookies in PHP

You can specify it in the set cookie function see the php manual

setcookie('Foo','Bar',0,'/', 'www.sample.com'  , FALSE, TRUE);

Inserting values into a SQL Server database using ado.net via C#

you should remove last comma and as nrodic said your command is not correct.

you should change it like this :

SqlCommand cmd = new SqlCommand("INSERT INTO dbo.regist (" + " FirstName, Lastname, Username, Password, Age, Gender,Contact " + ") VALUES (" + " textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, comboBox1.Text,comboBox2.Text,textBox7.Text" + ")", cn);

How can I install the Beautiful Soup module on the Mac?

Brian beat me too it, but since I already have the transcript:

easy_install

aaron@ares ~$ sudo easy_install BeautifulSoup
Searching for BeautifulSoup
Best match: BeautifulSoup 3.0.7a
Processing BeautifulSoup-3.0.7a-py2.5.egg
BeautifulSoup 3.0.7a is already the active version in easy-install.pth

Using /Library/Python/2.5/site-packages/BeautifulSoup-3.0.7a-py2.5.egg
Processing dependencies for BeautifulSoup
Finished processing dependencies for BeautifulSoup

.. or the normal boring way:

aaron@ares ~/Downloads$ curl http://www.crummy.com/software/BeautifulSoup/download/BeautifulSoup.tar.gz > bs.tar.gz
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 71460  100 71460    0     0  84034      0 --:--:-- --:--:-- --:--:--  111k

aaron@ares ~/Downloads$ tar -xzvf bs.tar.gz 
BeautifulSoup-3.1.0.1/
BeautifulSoup-3.1.0.1/BeautifulSoup.py
BeautifulSoup-3.1.0.1/BeautifulSoup.py.3.diff
BeautifulSoup-3.1.0.1/BeautifulSoupTests.py
BeautifulSoup-3.1.0.1/BeautifulSoupTests.py.3.diff
BeautifulSoup-3.1.0.1/CHANGELOG
BeautifulSoup-3.1.0.1/README
BeautifulSoup-3.1.0.1/setup.py
BeautifulSoup-3.1.0.1/testall.sh
BeautifulSoup-3.1.0.1/to3.sh
BeautifulSoup-3.1.0.1/PKG-INFO
BeautifulSoup-3.1.0.1/BeautifulSoup.pyc
BeautifulSoup-3.1.0.1/BeautifulSoupTests.pyc

aaron@ares ~/Downloads$ cd BeautifulSoup-3.1.0.1/

aaron@ares ~/Downloads/BeautifulSoup-3.1.0.1$ sudo python setup.py install
running install
<... snip ...>

"Faceted Project Problem (Java Version Mismatch)" error message

In Spring STS, Right click the project & select "Open Project", This provision do the necessary action on the background & bring the project back to work space.

Thanks & Regards Vengat Maran

How to get input field value using PHP

For global use, you may use:

$val = $_REQUEST['subject'];

and to add yo your session, simply

session_start();
$_SESSION['subject'] =  $val;

And you dont need jQuery in this case.

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6

You may need to set both compileKotlin and compileTestKotlin. This works on gradle 6.5.1.

compileKotlin {
    kotlinOptions {
        languageVersion = "1.2"
        apiVersion = "1.2"
        jvmTarget = "1.8"
        javaParameters = true   // Useful for reflection.
    }
}

compileTestKotlin {
    kotlinOptions {
        languageVersion = "1.2"
        apiVersion = "1.2"
        jvmTarget = "1.8"
        javaParameters = true   // Useful for reflection.
    }
}

`IF` statement with 3 possible answers each based on 3 different ranges

This is what I did:

Very simply put:

=IF(C7>100,"Profit",IF(C7=100,"Quota Met","Loss"))

The first IF Statement, if true will input Profit, and if false will lead on to the next IF statement and so forth :)

I only have basic formula knowledge but it's working so I will accept I am right!

Listen to changes within a DIV and act accordingly

Though the event DOMSubtreeModified is deprecated, its working as of now, so for any makeshift projects you can use it as following.

$("body").on('DOMSubtreeModified', "#mydiv", function() {
    alert('changed');
});

In the long term though, you'll have to use the MutationObserver API.

Query for documents where array size is greater than 1

db.accommodations.find({"name":{"$exists":true, "$ne":[], "$not":{"$size":1}}})

How to update Pandas from Anaconda and is it possible to use eclipse with this last

The answer above did not work for me (python 3.6, Anaconda, pandas 0.20.3). It worked with

conda install -c anaconda pandas 

Unfortunately I do not know how to help with Eclipse.

window.print() not working in IE

Just wait some time before closing the window!

if (navigator.appName != 'Microsoft Internet Explorer') {
    newWin.close();
} else {
    window.setTimeout(function() {newWin.close()}, 3000);
}

DBMS_OUTPUT.PUT_LINE not printing

  1. Ensure that you have your Dbms Output window open through the view option in the menubar.
  2. Click on the green '+' sign and add your database name.
  3. Write 'DBMS_OUTPUT.ENABLE;' within your procedure as the first line. Hope this solves your problem.

Optimal way to DELETE specified rows from Oracle

Store all the to be deleted ID's into a table. Then there are 3 ways. 1) loop through all the ID's in the table, then delete one row at a time for X commit interval. X can be a 100 or 1000. It works on OLTP environment and you can control the locks.

2) Use Oracle Bulk Delete

3) Use correlated delete query.

Single query is usually faster than multiple queries because of less context switching, and possibly less parsing.

JavaScript OR (||) variable assignment explanation

This is made to assign a default value, in this case the value of y, if the x variable is falsy.

The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages.

The Logical OR operator (||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first operand is returned.

For example:

"foo" || "bar"; // returns "foo"
false || "bar"; // returns "bar"

Falsy values are those who coerce to false when used in boolean context, and they are 0, null, undefined, an empty string, NaN and of course false.

How to log cron jobs?

Incase you're running some command with sudo, it won't allow it. Sudo needs a tty.

How can I get the corresponding table header (th) from a table cell (td)?

Find matching th for a td, taking into account colspan index issues.

_x000D_
_x000D_
$('table').on('click', 'td', get_TH_by_TD)_x000D_
_x000D_
function get_TH_by_TD(e){_x000D_
   var idx = $(this).index(),_x000D_
       th, th_colSpan = 0;_x000D_
_x000D_
   for( var i=0; i < this.offsetParent.tHead.rows[0].cells.length; i++ ){_x000D_
      th = this.offsetParent.tHead.rows[0].cells[i];_x000D_
      th_colSpan += th.colSpan;_x000D_
      if( th_colSpan >= (idx + this.colSpan) )_x000D_
        break;_x000D_
   }_x000D_
   _x000D_
   console.clear();_x000D_
   console.log( th );_x000D_
   return th;_x000D_
}
_x000D_
table{ width:100%; }_x000D_
th, td{ border:1px solid silver; padding:5px; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p>Click a TD:</p>_x000D_
<table>_x000D_
    <thead> _x000D_
        <tr>_x000D_
            <th colspan="2"></th>_x000D_
            <th>Name</th>_x000D_
            <th colspan="2">Address</th>_x000D_
            <th colspan="2">Other</th>_x000D_
        </tr>_x000D_
    </thead> _x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td>X</td>_x000D_
            <td>1</td>_x000D_
            <td>Jon Snow</td>_x000D_
            <td>12</td>_x000D_
            <td>High Street</td>_x000D_
            <td>Postfix</td>_x000D_
            <td>Public</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to define servlet filter order of execution using annotations in WAR

The Servlet 3.0 spec doesn't seem to provide a hint on how a container should order filters that have been declared via annotations. It is clear how about how to order filters via their declaration in the web.xml file, though.

Be safe. Use the web.xml file order filters that have interdependencies. Try to make your filters all order independent to minimize the need to use a web.xml file.

How do I POST urlencoded form data with $http without jQuery?

I think you need to do is to transform your data from object not to JSON string, but to url params.

From Ben Nadel's blog.

By default, the $http service will transform the outgoing request by serializing the data as JSON and then posting it with the content- type, "application/json". When we want to post the value as a FORM post, we need to change the serialization algorithm and post the data with the content-type, "application/x-www-form-urlencoded".

Example from here.

$http({
    method: 'POST',
    url: url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    },
    data: {username: $scope.userName, password: $scope.password}
}).then(function () {});

UPDATE

To use new services added with AngularJS V1.4, see

Android/Java - Date Difference in days

        Date userDob = new SimpleDateFormat("yyyy-MM-dd").parse(dob);
        Date today = new Date();
        long diff =  today.getTime() - userDob.getTime();
        int numOfDays = (int) (diff / (1000 * 60 * 60 * 24));
        int hours = (int) (diff / (1000 * 60 * 60));
        int minutes = (int) (diff / (1000 * 60));
        int seconds = (int) (diff / (1000));

importing external ".txt" file in python

Import gives you access to other modules in your program. You can't decide to import a text file. If you want to read from a file that's in the same directory, you can look at this. Here's another StackOverflow post about it.

Multiple maven repositories in one gradle file

In short you have to do like this

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "https://maven.fabric.io/public" }
}

Detail:

You need to specify each maven URL in its own curly braces. Here is what I got working with skeleton dependencies for the web services project I’m going to build up:

apply plugin: 'java'

sourceCompatibility = 1.7
version = '1.0'

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "http://maven.restlet.org" }
  mavenCentral()
}

dependencies {
  compile group:'org.restlet.jee', name:'org.restlet', version:'2.1.1'
  compile group:'org.restlet.jee', name:'org.restlet.ext.servlet',version.1.1'
  compile group:'org.springframework', name:'spring-web', version:'3.2.1.RELEASE'
  compile group:'org.slf4j', name:'slf4j-api', version:'1.7.2'
  compile group:'ch.qos.logback', name:'logback-core', version:'1.0.9'
  testCompile group:'junit', name:'junit', version:'4.11'
}

Blog

How to import a .cer certificate into a java keystore?

The certificate that you already have is probably the server's certificate, or the certificate used to sign the server's certificate. You will need it so that your web service client can authenticate the server.

But if additionally you need to perform client authentication with SSL, then you need to get your own certificate, to authenticate your web service client. For this you need to create a certificate request; the process involves creating your own private key, and the corresponding public key, and attaching that public key along with some of your info (email, name, domain name, etc) to a file that's called the certificate request. Then you send that certificate request to the company that's already asked you for it, and they will create your certificate, by signing your public key with their private key, and they'll send you back an X509 file with your certificate, which you can now add to your keystore, and you'll be ready to connect to a web service using SSL requiring client authentication.

To generate your certificate request, use "keytool -certreq -alias -file -keypass -keystore ". Send the resulting file to the company that's going to sign it.

When you get back your certificate, run "keytool -importcert -alias -keypass -keystore ".

You may need to used -storepass in both cases if the keystore is protected (which is a good idea).

How to export html table to excel or pdf in php

<script src="jquery.min.js"></script>
<table border="1" id="ReportTable" class="myClass">
    <tr bgcolor="#CCC">
      <td width="100">xxxxx</td>
      <td width="700">xxxxxx</td>
      <td width="170">xxxxxx</td>
      <td width="30">xxxxxx</td>
    </tr>
    <tr bgcolor="#FFFFFF">
      <td><?php                 
            $date = date_create($row_Recordset3['fecha']);
            echo date_format($date, 'd-m-Y');
            ?></td>
      <td><?php echo $row_Recordset3['descripcion']; ?></td>
      <td><?php echo $row_Recordset3['producto']; ?></td>
      <td><img src="borrar.png" width="14" height="14" class="clickable" onClick="eliminarSeguimiento(<?php echo $row_Recordset3['idSeguimiento']; ?>)" title="borrar"></td>
    </tr>
  </table>

  <input type="hidden" id="datatodisplay" name="datatodisplay">  
    <input type="submit" value="Export to Excel"> 

exporttable.php

<?php
header('Content-Type: application/force-download');
header('Content-disposition: attachment; filename=export.xls');
// Fix for crappy IE bug in download.
header("Pragma: ");
header("Cache-Control: ");
echo $_REQUEST['datatodisplay'];
?>

Add new column in Pandas DataFrame Python

The easiest way that I found for adding a column to a DataFrame was to use the "add" function. Here's a snippet of code, also with the output to a CSV file. Note that including the "columns" argument allows you to set the name of the column (which happens to be the same as the name of the np.array that I used as the source of the data).

#  now to create a PANDAS data frame
df = pd.DataFrame(data = FF_maxRSSBasal, columns=['FF_maxRSSBasal'])
# from here on, we use the trick of creating a new dataframe and then "add"ing it
df2 = pd.DataFrame(data = FF_maxRSSPrism, columns=['FF_maxRSSPrism'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = FF_maxRSSPyramidal, columns=['FF_maxRSSPyramidal'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_strainE22, columns=['deltaFF_strainE22'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = scaled, columns=['scaled'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_orientation, columns=['deltaFF_orientation'])
df = df.add( df2, fill_value=0 )
#print(df)
df.to_csv('FF_data_frame.csv')

.gitignore is ignored by Git

If you are a Notepad++ user, try doing the following:

Open your .gitignore file using Notepad++ and do:

Menu EditEOL ConversionWindows FormatSave.

Try using git status again and see if it works for you.

I have posted the answer to a similar question here.

Paste MS Excel data to SQL Server

If the interface works the way it did last I used it, you can select the region in Excel, copy it, open SQL Server and paste the data into the table as you would with Access.

Or you could setup an ODBC link between Excel and SQL Server.

server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

What i did to solve this problem in the terminal(Ubuntu 18.04):

openssl s_client -showcerts -servername www.github.com -connect www.github.com:443

I got two chunks of certificate chunks. And i copied the certificate chunks to my certificate file to /etc/ssl/certs/ca-certificates.crt.

fatal: bad default revision 'HEAD'

just do an initial commit and the error will go away:

git commit -m "initial commit"

for each inside a for each - Java

So you really want:

for each tweet
    unless tweet is in db
        insert tweet

If so, just write it down in your programming language. Hint: The loop over the array is to be done before the insert, which is done depending on the outcome.

What you want to test is that all array elements are not equal to the current one. But your for loop does not do that.

How to set up a cron job to run an executable every hour?

You can also use @hourly instant of 0 * * * *

Can I assume (bool)true == (int)1 for any C++ compiler?

Yes. The casts are redundant. In your expression:

true == 1

Integral promotion applies and the bool value will be promoted to an int and this promotion must yield 1.

Reference: 4.7 [conv.integral] / 4: If the source type is bool... true is converted to one.

Android ACTION_IMAGE_CAPTURE Intent

this is a well documented bug in some versions of android. that is, on google experience builds of android, image capture doesn't work as documented. what i've generally used is something like this in a utilities class.

public boolean hasImageCaptureBug() {

    // list of known devices that have the bug
    ArrayList<String> devices = new ArrayList<String>();
    devices.add("android-devphone1/dream_devphone/dream");
    devices.add("generic/sdk/generic");
    devices.add("vodafone/vfpioneer/sapphire");
    devices.add("tmobile/kila/dream");
    devices.add("verizon/voles/sholes");
    devices.add("google_ion/google_ion/sapphire");

    return devices.contains(android.os.Build.BRAND + "/" + android.os.Build.PRODUCT + "/"
            + android.os.Build.DEVICE);

}

then when i launch image capture, i create an intent that checks for the bug.

Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (hasImageCaptureBug()) {
    i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File("/sdcard/tmp")));
} else {
    i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
}
startActivityForResult(i, mRequestCode);

then in activity that i return to, i do different things based on the device.

protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
     switch (requestCode) {
         case GlobalConstants.IMAGE_CAPTURE:
             Uri u;
             if (hasImageCaptureBug()) {
                 File fi = new File("/sdcard/tmp");
                 try {
                     u = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(), fi.getAbsolutePath(), null, null));
                     if (!fi.delete()) {
                         Log.i("logMarker", "Failed to delete " + fi);
                     }
                 } catch (FileNotFoundException e) {
                     e.printStackTrace();
                 }
             } else {
                u = intent.getData();
            }
    }

this saves you having to write a new camera app, but this code isn't great either. the big problems are

  1. you never get full sized images from the devices with the bug. you get pictures that are 512px wide that are inserted into the image content provider. on devices without the bug, everything works as document, you get a big normal picture.

  2. you have to maintain the list. as written, it is possible for devices to be flashed with a version of android (say cyanogenmod's builds) that has the bug fixed. if that happens, your code will crash. the fix is to use the entire device fingerprint.

pip install access denied on Windows

I met a similar problem.But the error report is about

[SSL: TLSV1_ALERT_ACCESS_DENIED] tlsv1 alert access denied (_ssl.c:777)

First I tried this https://python-forum.io/Thread-All-pip-install-attempts-are-met-with-SSL-error#pid_28035 ,but seems it couldn't solve my problems,and still repeat the same issue.

And Second if you are working on a business computer,generally it may exist a web content filter(but I can access https://pypi.python.org through browser directly).And solve this issue by adding a proxy server.

For windows,open the Internet properties through IE or Chrome or whatsoever ,then set valid proxy address and port,and this way solve my problems

Or just adding the option pip --proxy [proxy-address]:port install mitmproxy.But you always need to add this option while installing by pypi

The above two solution is alternative for you demand.

Scrollbar without fixed height/Dynamic height with scrollbar

Use this:

style="height: 150px; max-height: 300px; overflow: auto;" 

fixe a height, it will be the default height and then a scroll bar come to access to the entire height

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

Take a closer look at the ?axis documentation. If you look at the description of the labels argument, you'll see that it is:

"a logical value specifying whether (numerical) annotations are 
to be made at the tickmarks,"

So, just change it to true, and you'll get your tick labels.

x <- seq(10,200,10)
y <- runif(x)
plot(x,y,xaxt='n')
axis(side = 1, at = x,labels = T)
# Since TRUE is the default for labels, you can just use axis(side=1,at=x)

Be careful that if you don't stretch your window width, then R might not be able to write all your labels in. Play with the window width and you'll see what I mean.


It's too bad that you had such trouble finding documentation! What were your search terms? Try typing r axis into Google, and the first link you will get is that Quick R page that I mentioned earlier. Scroll down to "Axes", and you'll get a very nice little guide on how to do it. You should probably check there first for any plotting questions, it will be faster than waiting for a SO reply.

Convert Month Number to Month Name Function in SQL

Use this statement for getting month name:

DECLARE @date datetime
SET @date='2015/1/4 00:00:00'

SELECT CAST(DATENAME(month,@date )  AS CHAR(3))AS 'Month Name'

This will give you short month name. Like this: Jan, Feb, Mar, etc.

Use String.split() with multiple delimiters

s.trim().split("[\\W]+") 

should work.

How do I monitor the computer's CPU, memory, and disk usage in Java?

Have a look at this very detailled article: http://nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking#UsingaSuninternalclasstogetJVMCPUtime

To get the percentage of CPU used, all you need is some simple maths:

MBeanServerConnection mbsc = ManagementFactory.getPlatformMBeanServer();

OperatingSystemMXBean osMBean = ManagementFactory.newPlatformMXBeanProxy(
mbsc, ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);

long nanoBefore = System.nanoTime();
long cpuBefore = osMBean.getProcessCpuTime();

// Call an expensive task, or sleep if you are monitoring a remote process

long cpuAfter = osMBean.getProcessCpuTime();
long nanoAfter = System.nanoTime();

long percent;
if (nanoAfter > nanoBefore)
 percent = ((cpuAfter-cpuBefore)*100L)/
   (nanoAfter-nanoBefore);
else percent = 0;

System.out.println("Cpu usage: "+percent+"%");

Note: You must import com.sun.management.OperatingSystemMXBean and not java.lang.management.OperatingSystemMXBean.

How to set the matplotlib figure default size in ipython notebook?

If you don't have this ipython_notebook_config.py file, you can create one by following the readme and typing

ipython profile create

How can I get the height of an element using css only

Unfortunately, it is not possible to "get" the height of an element via CSS because CSS is not a language that returns any sort of data other than rules for the browser to adjust its styling.

Your resolution can be achieved with jQuery, or alternatively, you can fake it with CSS3's transform:translateY(); rule.


The CSS Route

If we assume that your target div in this instance is 200px high - this would mean that you want the div to have a margin of 190px?

This can be achieved by using the following CSS:

.dynamic-height {
    -webkit-transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    transform: translateY(100%);         //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    margin-top: -10px;
}

In this instance, it is important to remember that translateY(100%) will move the element in question downwards by a total of it's own length.

The problem with this route is that it will not push element below it out of the way, where a margin would.


The jQuery Route

If faking it isn't going to work for you, then your next best bet would be to implement a jQuery script to add the correct CSS for you.

jQuery(document).ready(function($){ //wait for the document to load
    $('.dynamic-height').each(function(){ //loop through each element with the .dynamic-height class
        $(this).css({
            'margin-top' : $(this).outerHeight() - 10 + 'px' //adjust the css rule for margin-top to equal the element height - 10px and add the measurement unit "px" for valid CSS
        });
    });
});

How to prevent http file caching in Apache httpd (MAMP)

<FilesMatch "\.(js|css)$">
  ExpiresActive On
  ExpiresDefault A1
  Header append Cache-Control must-revalidate
</FilesMatch>

UnicodeDecodeError, invalid continuation byte

Because UTF-8 is multibyte and there is no char corresponding to your combination of \xe9 plus following space.

Why should it succeed in both utf-8 and latin-1?

Here how the same sentence should be in utf-8:

>>> o.decode('latin-1').encode("utf-8")
'a test of \xc3\xa9 char'

Replace all occurrences of a String using StringBuilder?

Yes. It is very simple to use String.replaceAll() method:

package com.test;

public class Replace {

    public static void main(String[] args) {
        String input = "Hello World";
        input = input.replaceAll("o", "0");
        System.out.println(input);
    }
}

Output:

Hell0 W0rld

If you really want to use StringBuilder.replace(int start, int end, String str) instead then here you go:

public static void main(String args[]) {
    StringBuilder sb = new StringBuilder("This is a new StringBuilder");

    System.out.println("Before: " + sb);

    String from = "new";
    String to = "replaced";
    sb = sb.replace(sb.indexOf(from), sb.indexOf(from) + from.length(), to);

    System.out.println("After: " + sb);
}

Output:

Before: This is a new StringBuilder
After: This is a replaced StringBuilder

How to use range-based for() loop with std::map?

From this paper: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2049.pdf

for( type-speci?er-seq simple-declarator : expression ) statement

is syntactically equivalent to

{
    typedef decltype(expression) C;
    auto&& rng(expression);
    for (auto begin(std::For<C>::begin(rng)), end(std::For<C>::end(rng)); begin != end; ++ begin) {
        type-speci?er-seq simple-declarator(*begin);
        statement
    }
}

So you can clearly see that what is abc in your case will be std::pair<key_type, value_type >. So for printing you can do access each element by abc.first and abc.second

How to define an optional field in protobuf 3

Since protobuf release 3.15, proto3 supports using the optional keyword (just as in proto2) to give a scalar field presence information.

syntax = "proto3";

message Foo {
    int32 bar = 1;
    optional int32 baz = 2;
}

A has_baz()/hasBaz() method is generated for the optional field above, just as it was in proto2.

Under the hood, protoc effectively treats an optional field as if it were declared using a oneof wrapper, as CyberSnoopy’s answer suggested:

message Foo {
    int32 bar = 1;
    oneof optional_baz {
        int32 baz = 2;
    }
}

If you’ve already used that approach, you can now simplify your message declarations (switch from oneof to optional) and code, since the wire format is the same.

The nitty-gritty details about field presence and optional in proto3 can be found in the Application note: Field presence doc.

Historical note: Experimental support for optional in proto3 was first announced on Apr 23, 2020 in this comment. Using it required passing protoc the --experimental_allow_proto3_optional flag in releases 3.12-3.14.

Constructor of an abstract class in C#

an abstract class can have member variables that needs to be initialized,so they can be initialized in the abstract class constructor and this constructor is called when derived class object is initialized.

How can I create basic timestamps or dates? (Python 3.4)

Ultimately you want to review the datetime documentation and become familiar with the formatting variables, but here are some examples to get you started:

import datetime

print('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Timestamp: {:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Date now: %s' % datetime.datetime.now())
print('Date today: %s' % datetime.date.today())

today = datetime.date.today()
print("Today's date is {:%b, %d %Y}".format(today))

schedule = '{:%b, %d %Y}'.format(today) + ' - 6 PM to 10 PM Pacific'
schedule2 = '{:%B, %d %Y}'.format(today) + ' - 1 PM to 6 PM Central'
print('Maintenance: %s' % schedule)
print('Maintenance: %s' % schedule2)

The output:

Timestamp: 2014-10-18 21:31:12

Timestamp: 2014-Oct-18 21:31:12

Date now: 2014-10-18 21:31:12.318340

Date today: 2014-10-18

Today's date is Oct, 18 2014

Maintenance: Oct, 18 2014 - 6 PM to 10 PM Pacific

Maintenance: October, 18 2014 - 1 PM to 6 PM Central

Reference link: https://docs.python.org/3.4/library/datetime.html#strftime-strptime-behavior

Keyboard shortcuts in WPF

Try this.

First create a RoutedCommand object:

RoutedCommand newCmd = new RoutedCommand();
newCmd.InputGestures.Add(new KeyGesture(Key.N, ModifierKeys.Control));
CommandBindings.Add(new CommandBinding(newCmd, btnNew_Click));

How to calculate rolling / moving average using NumPy / SciPy?

By comparing the solution below with the one that uses cumsum of numpy, This one takes almost half the time. This is because it does not need to go through the entire array to do the cumsum and then do all the subtraction. Moreover, the cumsum can be "dangerous" if the array is huge and the number are huge (possible overflow). Of course, also here the danger exists but at least are summed together only the essential numbers.

def moving_average(array_numbers, n):
    if n > len(array_numbers):
      return []
    temp_sum = sum(array_numbers[:n])
    averages = [temp_sum / float(n)]
    for first_index, item in enumerate(array_numbers[n:]):
        temp_sum += item - array_numbers[first_index]
        averages.append(temp_sum / float(n))
    return averages

Web-scraping JavaScript page with Python

If you have ever used the Requests module for python before, I recently found out that the developer created a new module called Requests-HTML which now also has the ability to render JavaScript.

You can also visit https://html.python-requests.org/ to learn more about this module, or if your only interested about rendering JavaScript then you can visit https://html.python-requests.org/?#javascript-support to directly learn how to use the module to render JavaScript using Python.

Essentially, Once you correctly install the Requests-HTML module, the following example, which is shown on the above link, shows how you can use this module to scrape a website and render JavaScript contained within the website:

from requests_html import HTMLSession
session = HTMLSession()

r = session.get('http://python-requests.org/')

r.html.render()

r.html.search('Python 2 will retire in only {months} months!')['months']

'<time>25</time>' #This is the result.

I recently learnt about this from a YouTube video. Click Here! to watch the YouTube video, which demonstrates how the module works.

Can I set subject/content of email using mailto:?

Yes, look all tips and tricks with mailto: http://www.angelfire.com/dc/html-webmaster/mailto.htm

mailto subject example:

_x000D_
_x000D_
<a href="mailto:[email protected]?subject=free chocolate">example</a>
_x000D_
_x000D_
_x000D_

mailto with content:

_x000D_
_x000D_
<a href="mailto:[email protected]?subject=look at this website&body=Hi,I found this website and thought you might like it http://www.geocities.com/wowhtml/">tell a friend</a>
_x000D_
_x000D_
_x000D_

As alluded to in the comments, both subject and body must be escaped properly. Use encodeURIComponent(subject) on each, rather than hand-coding for specific cases.

As Hoody mentioned in the comments, you can add line breaks by adding the following encoded sequence in the string:

%0D%0A // one line break

C# Help reading foreign characters using StreamReader

I had the same problem and my solution was simple: instead of

Encoding.ASCII

use

Encoding.GetEncoding("iso-8859-1")

The answer was found here.

Edit: more solutions. This maybe more accurate one:

Encoding.GetEncoding(1252);

Also, in some cases this will work for you too if your OS default encoding matches file encoding:

Encoding.Default;

Convert dictionary values into array

There is a ToArray() function on Values:

Foo[] arr = new Foo[dict.Count];    
dict.Values.CopyTo(arr, 0);

But I don't think its efficient (I haven't really tried, but I guess it copies all these values to the array). Do you really need an Array? If not, I would try to pass IEnumerable:

IEnumerable<Foo> foos = dict.Values;

How do you run CMD.exe under the Local System Account?

I would recommend you work out the minimum permission set that your service really needs and use that, rather than the far too privileged Local System context. For example, Local Service.

Interactive services no longer work - or at least, no longer show UI - on Windows Vista and Windows Server 2008 due to session 0 isolation.

html "data-" attribute as javascript parameter

you might use default parameters in your function and then just pass the entire dataset itself, since the dataset is already a DOMStringMap Object

<div data-uid="aaa" data-name="bbb" data-value="ccc"
onclick="fun(this.dataset)">

<script>
const fun = ({uid:'ddd', name:'eee', value:'fff', other:'default'} = {}) { 
    // 
}
</script>

that way, you can deal with any data-values that got set in the html tag, or use defaults if they weren't set - that kind of thing

maybe not in this situation, but in others, it might be advantageous to put all your preferences in a single data-attribute

<div data-all='{"uid":"aaa","name":"bbb","value":"ccc"}'
onclick="fun(JSON.parse(this.dataset.all))">

there are probably more terse ways of doing that, if you already know certain things about the order of the data

<div data-all="aaa,bbb,ccc" onclick="fun(this.dataset.all.split(','))">

How do I use IValidatableObject?

I liked cocogza's answer except that calling base.IsValid resulted in a stack overflow exception as it would re-enter the IsValid method again and again. So I modified it to be for a specific type of validation, in my case it was for an e-mail address.

[AttributeUsage(AttributeTargets.Property)]
class ValidEmailAddressIfTrueAttribute : ValidationAttribute
{
    private readonly string _nameOfBoolProp;

    public ValidEmailAddressIfTrueAttribute(string nameOfBoolProp)
    {
        _nameOfBoolProp = nameOfBoolProp;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (validationContext == null)
        {
            return null;
        }

        var property = validationContext.ObjectType.GetProperty(_nameOfBoolProp);
        if (property == null)
        {
            return new ValidationResult($"{_nameOfBoolProp} not found");
        }

        var boolVal = property.GetValue(validationContext.ObjectInstance, null);

        if (boolVal == null || boolVal.GetType() != typeof(bool))
        {
            return new ValidationResult($"{_nameOfBoolProp} not boolean");
        }

        if ((bool)boolVal)
        {
            var attribute = new EmailAddressAttribute {ErrorMessage = $"{value} is not a valid e-mail address."};
            return attribute.GetValidationResult(value, validationContext);
        }
        return null;
    }
}

This works much better! It doesn't crash and produces a nice error message. Hope this helps someone!

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

Use this:

$root = 'REST_SERVICE_URL'
$user = "user"
$pass= "password"
$secpasswd = ConvertTo-SecureString $pass -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($user, $secpasswd)

$result = Invoke-RestMethod $root -Credential $credential

call javascript function onchange event of dropdown list

You just try this, Its so easy

 <script>

  $("#YourDropDownId").change(function () {
            alert($("#YourDropDownId").val());
        });

</script>

How does numpy.newaxis work and when to use it?

What is np.newaxis?

The np.newaxis is just an alias for the Python constant None, which means that wherever you use np.newaxis you could also use None:

>>> np.newaxis is None
True

It's just more descriptive if you read code that uses np.newaxis instead of None.

How to use np.newaxis?

The np.newaxis is generally used with slicing. It indicates that you want to add an additional dimension to the array. The position of the np.newaxis represents where I want to add dimensions.

>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.shape
(10,)

In the first example I use all elements from the first dimension and add a second dimension:

>>> a[:, np.newaxis]
array([[0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])
>>> a[:, np.newaxis].shape
(10, 1)

The second example adds a dimension as first dimension and then uses all elements from the first dimension of the original array as elements in the second dimension of the result array:

>>> a[np.newaxis, :]  # The output has 2 [] pairs!
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
>>> a[np.newaxis, :].shape
(1, 10)

Similarly you can use multiple np.newaxis to add multiple dimensions:

>>> a[np.newaxis, :, np.newaxis]  # note the 3 [] pairs in the output
array([[[0],
        [1],
        [2],
        [3],
        [4],
        [5],
        [6],
        [7],
        [8],
        [9]]])
>>> a[np.newaxis, :, np.newaxis].shape
(1, 10, 1)

Are there alternatives to np.newaxis?

There is another very similar functionality in NumPy: np.expand_dims, which can also be used to insert one dimension:

>>> np.expand_dims(a, 1)  # like a[:, np.newaxis]
>>> np.expand_dims(a, 0)  # like a[np.newaxis, :]

But given that it just inserts 1s in the shape you could also reshape the array to add these dimensions:

>>> a.reshape(a.shape + (1,))  # like a[:, np.newaxis]
>>> a.reshape((1,) + a.shape)  # like a[np.newaxis, :]

Most of the times np.newaxis is the easiest way to add dimensions, but it's good to know the alternatives.

When to use np.newaxis?

In several contexts is adding dimensions useful:

  • If the data should have a specified number of dimensions. For example if you want to use matplotlib.pyplot.imshow to display a 1D array.

  • If you want NumPy to broadcast arrays. By adding a dimension you could for example get the difference between all elements of one array: a - a[:, np.newaxis]. This works because NumPy operations broadcast starting with the last dimension 1.

  • To add a necessary dimension so that NumPy can broadcast arrays. This works because each length-1 dimension is simply broadcast to the length of the corresponding1 dimension of the other array.


1 If you want to read more about the broadcasting rules the NumPy documentation on that subject is very good. It also includes an example with np.newaxis:

>>> a = np.array([0.0, 10.0, 20.0, 30.0])
>>> b = np.array([1.0, 2.0, 3.0])
>>> a[:, np.newaxis] + b
array([[  1.,   2.,   3.],
       [ 11.,  12.,  13.],
       [ 21.,  22.,  23.],
       [ 31.,  32.,  33.]])

How to set child process' environment variable in Makefile

I only needed the environment variables locally to invoke my test command, here's an example setting multiple environment vars in a bash shell, and escaping the dollar sign in make.

SHELL := /bin/bash

.PHONY: test tests
test tests:
    PATH=./node_modules/.bin/:$$PATH \
    JSCOVERAGE=1 \
    nodeunit tests/

How to order results with findBy() in Doctrine

$ens = $em->getRepository('AcmeBinBundle:Marks')
              ->findBy(
                 array(), 
                 array('id' => 'ASC')
               );

Using an IF Statement in a MySQL SELECT query

How to use an IF statement in the MySQL "select list":

select if (1>2, 2, 3);                         //returns 3
select if(1<2,'yes','no');                     //returns yes
SELECT IF(STRCMP('test','test1'),'no','yes');  //returns no

How to use an IF statement in the MySQL where clause search condition list:

create table penguins (id int primary key auto_increment, name varchar(100))
insert into penguins (name) values ('rico')
insert into penguins (name) values ('kowalski')
insert into penguins (name) values ('skipper')

select * from penguins where 3 = id
-->3    skipper

select * from penguins where (if (true, 2, 3)) = id
-->2    kowalski

How to use an IF statement in the MySQL "having clause search conditions":

select * from penguins 
where 1=1
having (if (true, 2, 3)) = id
-->1    rico

Use an IF statement with a column used in the select list to make a decision:

select (if (id = 2, -1, 1)) item
from penguins
where 1=1
--> 1
--> -1
--> 1

If statements embedded in SQL queries is a bad "code smell". Bad code has high "WTF's per minute" during code review. This is one of those things. If I see this in production with your name on it, I'm going to automatically not like you.

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

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

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

yes d | git mergetool -- the/subdirectory

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

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

More elegant "ps aux | grep -v grep"

You could use preg_split instead of explode and split on [ ]+ (one or more spaces). But I think in this case you could go with preg_match_all and capturing:

preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];

The pattern matches a space, php, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php as part of a user name but really only as a command.

An alternative to capturing is the "keep" feature of PCRE. If you use \K in the pattern, everything before it is discarded in the match:

preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];

I would use preg_match(). I do something similar for many of my system management scripts. Here is an example:

$test = "user     12052  0.2  0.1 137184 13056 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user     12054  0.2  0.1 137184 13064 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user     12055  0.6  0.1 137844 14220 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user     12057  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user     12058  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user     12059  0.3  0.1 135112 13000 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root     12068  0.0  0.0 106088  1164 pts/1    S+   10:00   0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root     12070  0.0  0.0 103240   828 pts/1    R+   10:00   0:00 grep utilities";

$lines = explode("\n", $test);

foreach($lines as $line){
        if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
                print_r($matches);
        }

}

The above prints:

Array
(
    [0] => .php cust1 cron
    [1] => cust1
)
Array
(
    [0] => .php cust3 cron
    [1] => cust3
)
Array
(
    [0] => .php cust4 cron
    [1] => cust4
)
Array
(
    [0] => .php cust89 cron
    [1] => cust89
)
Array
(
    [0] => .php cust435 cron
    [1] => cust435
)
Array
(
    [0] => .php cust16 cron
    [1] => cust16
)

You can set $test to equal the output from exec. the values you are looking for would be in the if statement under the foreach. $matches[1] will have the custx value.

Get just the filename from a path in a Bash script

basename and dirname solutions are more convenient. Those are alternative commands:

FILE_PATH="/opt/datastores/sda2/test.old.img"
echo "$FILE_PATH" | sed "s/.*\///"

This returns test.old.img like basename.

This is salt filename without extension:

echo "$FILE_PATH" | sed -r "s/.+\/(.+)\..+/\1/"

It returns test.old.

And following statement gives the full path like dirname command.

echo "$FILE_PATH" | sed -r "s/(.+)\/.+/\1/"

It returns /opt/datastores/sda2

getApplication() vs. getApplicationContext()

To answer the question, getApplication() returns an Application object and getApplicationContext() returns a Context object. Based on your own observations, I would assume that the Context of both are identical (i.e. behind the scenes the Application class calls the latter function to populate the Context portion of the base class or some equivalent action takes place). It shouldn't really matter which function you call if you just need a Context.

How can I check the extension of a file?

Use pathlib From Python3.4 onwards.

from pathlib import Path
Path('my_file.mp3').suffix == '.mp3'

Angular 4: How to include Bootstrap?

Angular 4 - Bootstrap / @ng-bootstrap setup

First install bootstrap into your project using below command:

npm install --save bootstrap

Then add this line "../node_modules/bootstrap/dist/css/bootstrap.min.css" to angular-cli.json file (root folder) in styles

"styles": [
   "../node_modules/bootstrap/dist/css/bootstrap.min.css",
   "styles.css"
],

After installing the above dependencies, install ng-bootstrap via:

npm install --save @ng-bootstrap/ng-bootstrap

Once installed you need to import main module.

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

After this, you can use All the Bootstrap widgets (ex. carousel, modal, popovers, tooltips, tabs etc.) and several additional goodies ( datepicker, rating, timepicker, typeahead).

Fill remaining vertical space - only CSS

Flexbox solution

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  width: 300px;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.first {_x000D_
  height: 50px;_x000D_
}_x000D_
_x000D_
.second {_x000D_
  flex-grow: 1;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="first" style="background:#b2efd8">First</div>_x000D_
  <div class="second" style="background:#80c7cd">Second</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to style HTML5 range input to have different color before and after slider?

It's now supported with pseudo elements in each of WebKit, Firefox and IE. But, of course, it's different in each one. : (

See this question's answers and/or search for a CodePen titled prettify <input type=range> #101 for some solutions.

Android: How to rotate a bitmap on a center point

You can also rotate the ImageView using a RotateAnimation:

RotateAnimation rotateAnimation = new RotateAnimation(from, to,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                0.5f);
rotateAnimation.setInterpolator(new LinearInterpolator());
rotateAnimation.setDuration(ANIMATION_DURATION);
rotateAnimation.setFillAfter(true);

imageView.startAnimation(rotateAnimation);

Table border left and bottom

You need to use the border property as seen here: jsFiddle

HTML:

<table width="770">
    <tr>
        <td class="border-left-bottom">picture (border only to the left and bottom ) </td>
        <td>text</td>
    </tr>
    <tr>
        <td>text</td>
        <td class="border-left-bottom">picture (border only to the left and bottom) </td>
    </tr>
</table>`

CSS:

td.border-left-bottom{
    border-left: solid 1px #000;
    border-bottom: solid 1px #000;
}

Toggle Checkboxes on/off

You can write like this also

$(function() {
    $("#checkbox-toggle").click(function() {
        $('input[type=checkbox][name=checkbox_id\\[\\]]').click();
    });
});

Just need to call click event of check box when user click on button with id '#checkbox-toggle'.

'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error

I wrestled with this problem and implemented the URL concatenation solution contributed by @Kushan in the accepted answer above. It worked in my local MySql instance. But when I deployed my Play/Scala app to Heroku it no longer would work. Heroku also concatenates several args to the DB URL that they provide users, and this solution, because of Heroku's use concatenation of "?" before their own set of args, will not work. However I found a different solution which seems to work equally well.

SET sql_mode = 'NO_ZERO_DATE';

I put this in my table descriptions and it solved the problem of '0000-00-00 00:00:00' can not be represented as java.sql.Timestamp

Access denied for user 'root'@'localhost' while attempting to grant privileges. How do I grant privileges?

This might happen when you attempt to grant all privileges on all tables to another user, because the mysql.users table is considered off-limits for a user other than root.

The following however, should work:

GRANT ALL PRIVILEGES ON `%`.* TO '[user]'@'[hostname]' IDENTIFIED BY '[password]' WITH GRANT OPTION;

Note that we use `%`.* instead of *.*

Run exe file with parameters in a batch file

If you need to see the output of the execute, use CALL together with or instead of START.

Example:

CALL "C:\Program Files\Certain Directory\file.exe" -param PAUSE

This will run the file.exe and print back whatever it outputs, in the same command window. Remember the PAUSE after the call or else the window may close instantly.

jQuery click anywhere in the page except on 1 div

I know that this question has been answered, And all the answers are nice. But I wanted to add my two cents to this question for people who have similar (but not exactly the same) problem.

In a more general way, we can do something like this:

$('body').click(function(evt){    
    if(!$(evt.target).is('#menu_content')) {
        //event handling code
    }
});

This way we can handle not only events fired by anything except element with id menu_content but also events that are fired by anything except any element that we can select using CSS selectors.

For instance in the following code snippet I am getting events fired by any element except all <li> elements which are descendants of div element with id myNavbar.

$('body').click(function(evt){    
    if(!$(evt.target).is('div#myNavbar li')) {
        //event handling code
    }
});

How to replace unicode characters in string with something else python?

import re
regex = re.compile("u'2022'",re.UNICODE)
newstring = re.sub(regex, something, yourstring, <optional flags>)

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

You may find the following windows command line useful in tracking down the offending jar file. it creates an index of all the class files in all the jars in the folder. Execute from within the lib folder of your deployed app, then search the index.txt file for the offending class.

for /r %X in (*.jar) do (echo %X & jar -tf %X) >> index.txt

insert password into database in md5 format?

use MD5,

$query="INSERT INTO ptb_users (id,
user_id,
first_name,
last_name,
email )
VALUES('NULL',
'NULL',
'".$firstname."',
'".$lastname."',
'".$email."',
MD5('".$password."')
)";

but MD5 is insecure. Use SHA2.

How to pass variables from one php page to another without form?

If you are trying to access the variable from another PHP file directly, you can include that file with include() or include_once(), giving you access to that variable. Note that this will include the entire first file in the second file.

How to set java_home on Windows 7?

if you have not restarted your computer after installing jdk just restart your computer.

if you want to make a portable java and set path before using java, just make a batch file i explained below.

if you want to run this batch file when your computer start just put your batch file shortcut in startup folder. In windows 7 startup folder is "C:\Users\user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"

make a batch file like this:

set Java_Home=C:\Program Files\Java\jdk1.8.0_11
set PATH=%PATH%;C:\Program Files\Java\jdk1.8.0_11\bin

note: java_home and path are variables. you can make any variable as you wish. for example set amir=good_boy and you can see amir by %amir% or you can see java_home by %java_home%

Remove scroll bar track from ScrollView in Android

try this is your activity onCreate:

ScrollView sView = (ScrollView)findViewById(R.id.deal_web_view_holder);
// Hide the Scollbar
sView.setVerticalScrollBarEnabled(false);
sView.setHorizontalScrollBarEnabled(false);

http://developer.android.com/reference/android/view/View.html#setVerticalScrollBarEnabled%28boolean%29

How to center links in HTML

The <p> will show up on a new line. Try wrapping all of your links in one single <p> tag:

<p style="text-align:center;"><a href="http//www.google.com">Search</a><a href="Contact Us">Contact Us</a></p>

Simplest way to merge ES6 Maps/Sets?

The approved answer is great but that creates a new set every time.

If you want to mutate an existing object instead, use a helper function.

Set

function concatSets(set, ...iterables) {
    for (const iterable of iterables) {
        for (const item of iterable) {
            set.add(item);
        }
    }
}

Usage:

const setA = new Set([1, 2, 3]);
const setB = new Set([4, 5, 6]);
const setC = new Set([7, 8, 9]);
concatSets(setA, setB, setC);
// setA will have items 1, 2, 3, 4, 5, 6, 7, 8, 9

Map

function concatMaps(map, ...iterables) {
    for (const iterable of iterables) {
        for (const item of iterable) {
            map.set(...item);
        }
    }
}

Usage:

const mapA = new Map().set('S', 1).set('P', 2);
const mapB = new Map().set('Q', 3).set('R', 4);
concatMaps(mapA, mapB);
// mapA will have items ['S', 1], ['P', 2], ['Q', 3], ['R', 4]

How to stretch div height to fill parent div - CSS

B2 container position relative

Top position B2 + of remaining height

Height of B2 + height B1 or remaining height

How do I print the full value of a long string in gdb?

As long as your program's in a sane state, you can also call (void)puts(your_string) to print it to stdout. Same principle applies to all functions available to the debugger, actually.

Read environment variables in Node.js

Why not use them in the Users directory in the .bash_profile file, so you don't have to push any files with your variables to production?

Create Directory if it doesn't exist with Ruby

Another simple way:

Dir.mkdir('tmp/excel') unless Dir.exist?('tmp/excel')

Convert dictionary to bytes and back again python?

If you need to convert the dictionary to binary, you need to convert it to a string (JSON) as described in the previous answer, then you can convert it to binary.

For example:

my_dict = {'key' : [1,2,3]}

import json
def dict_to_binary(the_dict):
    str = json.dumps(the_dict)
    binary = ' '.join(format(ord(letter), 'b') for letter in str)
    return binary


def binary_to_dict(the_binary):
    jsn = ''.join(chr(int(x, 2)) for x in the_binary.split())
    d = json.loads(jsn)  
    return d

bin = dict_to_binary(my_dict)
print bin

dct = binary_to_dict(bin)
print dct

will give the output

1111011 100010 1101011 100010 111010 100000 1011011 110001 101100 100000 110010 101100 100000 110011 1011101 1111101

{u'key': [1, 2, 3]}

Add new item in existing array in c#.net

So if you have a existing array, my quick fix will be

var tempList = originalArray.ToList();
tempList.Add(newitem);

Now just replace the original array with the new one

originalArray = tempList.ToArray();

Javascript : get <img> src and set as variable?

Use JQuery, its easy.

Include the JQuery library into your html file in the head as such:

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

(Make sure that this script tag goes before your other script tags in your html file)

Target your id in your JavaScript file as such:

<script>
var youtubeimcsrc = $('#youtubeimg').attr('src');

//your var will be the src string that you're looking for

</script>

I do not want to inherit the child opacity from the parent in CSS

A little trick if your parent is transparent and you would like your child to be the same, but defined exclusively (e.g. to overwrite the user agent styles of a select dropdown):

.parent {
     background-color: rgba(0,0,0,0.5);
}

.child {
     background-color: rgba(128,128,128,0);
}

How to undo a git pull?

Even though the above solutions do work,This answer is for you in case you want to reverse the clock instead of undoing a git pull.I mean if you want to get your exact repo the way it was X Mins back then run the command

git reset --hard branchName@{"X Minutes ago"}

Note: before you actually go ahead and run this command please only try this command if you are sure about the time you want to go back to and heres about my situation.

I was currently on a branch develop, I was supposed to checkout to a new branch and pull in another branch lets say Branch A but I accidentally ran git pull origin B before checking out.

so to undo this change I tried this command

git reset --hard develop@{"10 Minutes ago"}

if you are on windows cmd and get error: unknown switch `e

try adding quotes like this

git reset --hard 'develop@{"10 Minutes ago"}'

How do I remove all HTML tags from a string without knowing which tags are in it?

You can use a simple regex like this:

public static string StripHTML(string input)
{
   return Regex.Replace(input, "<.*?>", String.Empty);
}

Be aware that this solution has its own flaw. See Remove HTML tags in String for more information (especially the comments of @mehaase)

Another solution would be to use the HTML Agility Pack.
You can find an example using the library here: HTML agility pack - removing unwanted tags without removing content?

Getting the parent of a directory in Bash

if for whatever reason you are interested in navigating up a specific number of directories you could also do: nth_path=$(cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && cd ../../../ && pwd). This would give 3 parents directories up

Where can I find the API KEY for Firebase Cloud Messaging?

1.Create a Firebase project in the Firebase console, if you don't already have one. If you already have an existing Google project associated with your app, click Import Google Project. Otherwise, click Create New Project.

2.Click settings and select Permissions.

3.Select Service accounts from the menu on the left.

4.Click Create service account.

  • Enter a name for your service account.
  • You can optionally customize the ID from the one automatically generated from the name.
  • Select Furnish a new private key and leave the Key type as JSON.
  • Leave Enable Google Apps Domain-wide Delegation unselected.
  • Click Create.

This might be what you're looking for. This was in the tutorial on the site

Android Studio: Add jar as library?

I don' know why but my Android Studio 0.8.14 goes crazy when I try to implement these solutions using Gradle. I admit my poor knowledge of this great build tool but what does Studio mutilate my project for? I manage to get it working this way: put android-support-v13.jar into 'libs' directory, then F4 on my project and add File dependency where I pointed android-support-v13.jar.

How to close a web page on a button click, a hyperlink or a link button click?

double click the button and add write // this.close();

  private void buttonClick(object sender, EventArgs e)
{
    this.Close();
}

How can I get a favicon to show up in my django app?

One lightweight trick is to make a redirect in your urls.py file, e.g. add a view like so:

from django.views.generic.base import RedirectView

favicon_view = RedirectView.as_view(url='/static/favicon.ico', permanent=True)

urlpatterns = [
    ...
    re_path(r'^favicon\.ico$', favicon_view),
    ...
]

This works well as an easy trick for getting favicons working when you don't really have other static content to host.