Programs & Examples On #Superscript

A superscript is a number, figure, symbol, or indicator that is smaller than the normal line of type and is set slightly above the baseline.

HTML <sup /> tag affecting line height, how to make it consistent?

The reason why the <sup> tag is affecting the spacing between two lines has to do with a number of factors. The factors are: line height, size of the superscript in relation to the regular font, the line height of the superscript and last but not least what is the bottom of the superscript aligning with... If you set... the line height of regular text to be in a "tunnel band" (that's what I call it) of 135% then regular text (the 100%) gets white padded by 35% of more white. For a paragraph this looks like this:

 p
    {
            line-height: 135%;
    }

If you then do not white pad the superscript...(i.e. keep its line height to 0) the superscript only has the width of its own text... if you then ask the superscript to be a percentage of the regular font (for example 70%) and you align it with the middle of the regular text (text-middle), you can eliminate the problem and get a superscript that looks like a superscript. Here it is:

sup
{
    font-size: 70%;
    vertical-align: text-middle;
    line-height: 0;
}

JList add/remove Item

The best and easiest way to clear a JLIST is:

myJlist.setListData(new String[0]);

How to manage local vs production settings in Django?

My solution to that problem is also somewhat of a mix of some solutions already stated here:

  • I keep a file called local_settings.py that has the content USING_LOCAL = True in dev and USING_LOCAL = False in prod
  • In settings.py I do an import on that file to get the USING_LOCAL setting

I then base all my environment-dependent settings on that one:

DEBUG = USING_LOCAL
if USING_LOCAL:
    # dev database settings
else:
    # prod database settings

I prefer this to having two separate settings.py files that I need to maintain as I can keep my settings structured in a single file easier than having them spread across several files. Like this, when I update a setting I don't forget to do it for both environments.

Of course that every method has its disadvantages and this one is no exception. The problem here is that I can't overwrite the local_settings.py file whenever I push my changes into production, meaning I can't just copy all files blindly, but that's something I can live with.

How to build and use Google TensorFlow C++ api

If you don't want to build Tensorflow yourself and your operating system is Debian or Ubuntu, you can download prebuilt packages with the Tensorflow C/C++ libraries. This distribution can be used for C/C++ inference with CPU, GPU support is not included:

https://github.com/kecsap/tensorflow_cpp_packaging/releases

There are instructions written how to freeze a checkpoint in Tensorflow (TFLearn) and load this model for inference with the C/C++ API:

https://github.com/kecsap/tensorflow_cpp_packaging/blob/master/README.md

Beware: I am the developer of this Github project.

R: Comment out block of code

A sort of block comment uses an if statement:

if(FALSE) {
  all your code
}

It works, but I almost always use the block comment options of my editors (RStudio, Kate, Kwrite).

How to store a datetime in MySQL with timezone info

All the symptoms you describe suggest that you never tell MySQL what time zone to use so it defaults to system's zone. Think about it: if all it has is '2011-03-13 02:49:10', how can it guess that it's a local Tanzanian date?

As far as I know, MySQL doesn't provide any syntax to specify time zone information in dates. You have to change it a per-connection basis; something like:

SET time_zone = 'EAT';

If this doesn't work (to use named zones you need that the server has been configured to do so and it's often not the case) you can use UTC offsets because Tanzania does not observe daylight saving time at the time of writing but of course it isn't the best option:

SET time_zone = '+03:00';

Java - How to find the redirected url of a url?

I'd actually suggest using a solid open-source library as an http client. If you take a look at http client by ASF you'll find life a lot easier. It is an easy-to-use,scalable and robust client for http.

jquery validate check at least one checkbox

It's highly probable that you want to have a text next to the checkbox. In that case, you can put the checkbox inside a label like I do below:

<label style="width: 150px;"><input type="checkbox" name="damageTypeItems" value="72" aria-required="true" class="error"> All Over</label>
<label style="width: 150px;"><input type="checkbox" name="damageTypeItems" value="73" aria-required="true" class="error"> All Over X2</label>

The problem is that when the error message is displayed, it's going to be inserted after the checkbox but before the text, making it unreadable. In order to fix that, I changed the error placement function:

if (element.is(":checkbox")) {
    error.insertAfter(element.parent().parent());
}
else {
    error.insertAfter(element);
}

It depends on your layout but what I did is to have a special error placement for checkbox controls. I get the parent of the checkbox, which is a label, and then I get the parent of it, which is a div in my case. This way, the error is placed below the list of checkbox controls.

Java GC (Allocation Failure)

"Allocation Failure" is cause of GC to kick is not correct. It is an outcome of GC operation.

GC kicks in when there is no space to allocate( depending on region minor or major GC is performed). Once GC is performed if space is freed good enough, but if there is not enough size it fails. Allocation Failure is one such failure. Below document have good explanation https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/g1_gc.html

Substring in VBA

Test for ':' first, then take test string up to ':' or end, depending on if it was found

Dim strResult As String

' Position of :
intPos = InStr(1, strTest, ":")
If intPos > 0 Then
    ' : found, so take up to :
    strResult = Left(strTest, intPos - 1)
Else
    ' : not found, so take whole string
    strResult = strTest
End If

Markdown to create pages and table of contents?

There are 2 way to create your TOC (summary) in your markdown document.

1. Manually

# My Table of content
- [Section 1](#id-section1)
- [Section 2](#id-section2)

<div id='id-section1'/>
## Section 1
<div id='id-section2'/>
## Section 2

2. Programmatically

You can use for example a script that generate summary for you, take a look to my project on github - summarizeMD -

I've tried also other script/npm module (for example doctoc) but no one reproduce a TOC with working anchors.

How to find integer array size in java

public class Test {

    int[] array = { 1, 99, 10000, 84849, 111, 212, 314, 21, 442, 455, 244, 554,
            22, 22, 211 };

    public void Printrange() {

        for (int i = 0; i < array.length; i++) { // <-- use array.length 
            if (array[i] > 100 && array[i] < 500) {
                System.out.println("numbers with in range :" + array[i]);
            }
        }
    }
}

Exclude all transitive dependencies of a single dependency

Use the latest maven in your classpath.. It will remove the duplicate artifacts and keep the latest maven artifact..

Node.js Hostname/IP doesn't match certificate's altnames

I had the same issue using the request module to proxy POST request from somewhere else and it was because I left the host property in the header (I was copying the header from the original request).

AVD Manager - Cannot Create Android Virtual Device

I actually hit on this problem a week ago. The issue had to do with not using an updated Eclipse version of the Android SDK plugin with the latest version of the SDK. It was a fun problem overall, but it disappeared as soon as I updated it.

I had even updated the AVD images and no luck. Apparently the old plugin cannot see the new image layout or something. This is for version 22.3 of the SDK.

How to fix "could not find a base address that matches schema http"... in WCF

There should be a way to solve this pretty easily with external config sections and an extra deployment step that drops a deployment specific external .config file into a known location. We typically use this solution to handle the different server configurations for our different deployment environments (Staging, QA, production, etc) with our "dev box" being the default if no special copy occurs.

Linker Error C++ "undefined reference "

This error tells you everything:

undefined reference toHash::insert(int, char)

You're not linking with the implementations of functions defined in Hash.h. Don't you have a Hash.cpp to also compile and link?

how to realize countifs function (excel) in R

Easy peasy. Your data frame will look like this:

df <- data.frame(sex=c('M','F','M'),
                 occupation=c('Student','Analyst','Analyst'))

You can then do the equivalent of a COUNTIF by first specifying the IF part, like so:

df$sex == 'M'

This will give you a boolean vector, i.e. a vector of TRUE and FALSE. What you want is to count the observations for which the condition is TRUE. Since in R TRUE and FALSE double as 1 and 0 you can simply sum() over the boolean vector. The equivalent of COUNTIF(sex='M') is therefore

sum(df$sex == 'M')

Should there be rows in which the sex is not specified the above will give back NA. In that case, if you just want to ignore the missing observations use

sum(df$sex == 'M', na.rm=TRUE)

Changing Placeholder Text Color with Swift

Use like this in Swift,

 let placeHolderText = textField.placeholder ?? ""
 let str = NSAttributedString(string:placeHolderText!, attributes: [NSAttributedString.Key.foregroundColor :UIColor.lightGray])
 textField.attributedPlaceholder = str

In Objective C

NSString *placeHolder = [textField.placeholder length]>0 ? textField.placeholder: @"";
NSAttributedString *str = [[NSAttributedString alloc] initWithString:placeHolder attributes:@{ NSForegroundColorAttributeName : [UIColor lightGrayColor] }];
textField.attributedPlaceholder = str;

Base64 encoding in SQL Server 2005 T-SQL

I know this has already been answered, but I just spent more time than I care to admit coming up with single-line SQL statements to accomplish this, so I'll share them here in case anyone else needs to do the same:

-- Encode the string "TestData" in Base64 to get "VGVzdERhdGE="
SELECT
    CAST(N'' AS XML).value(
          'xs:base64Binary(xs:hexBinary(sql:column("bin")))'
        , 'VARCHAR(MAX)'
    )   Base64Encoding
FROM (
    SELECT CAST('TestData' AS VARBINARY(MAX)) AS bin
) AS bin_sql_server_temp;

-- Decode the Base64-encoded string "VGVzdERhdGE=" to get back "TestData"
SELECT 
    CAST(
        CAST(N'' AS XML).value(
            'xs:base64Binary("VGVzdERhdGE=")'
          , 'VARBINARY(MAX)'
        ) 
        AS VARCHAR(MAX)
    )   ASCIIEncoding
;

I had to use a subquery-generated table in the first (encoding) query because I couldn't find any way to convert the original value ("TestData") to its hex string representation ("5465737444617461") to include as the argument to xs:hexBinary() in the XQuery statement.

I hope this helps someone!

Default visibility for C# classes and members (fields, methods, etc.)?

All of the information you are looking for can be found here and here (thanks Reed Copsey):

From the first link:

Classes and structs that are declared directly within a namespace (in other words, that are not nested within other classes or structs) can be either public or internal. Internal is the default if no access modifier is specified.

...

The access level for class members and struct members, including nested classes and structs, is private by default.

...

interfaces default to internal access.

...

Delegates behave like classes and structs. By default, they have internal access when declared directly within a namespace, and private access when nested.


From the second link:

Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal.

And for nested types:

Members of    Default member accessibility
----------    ----------------------------
enum          public
class         private
interface     public
struct        private

PHP float with 2 decimal places: .00

A float isn't have 0 or 0.00 : those are different string representations of the internal (IEEE754) binary format but the float is the same.

If you want to express your float as "0.00", you need to format it in a string, using number_format :

$numberAsString = number_format($numberAsFloat, 2);

WPF Data Binding and Validation Rules Best Practices

I think the new preferred way might be to use IDataErrorInfo

Read more here

Get PostGIS version

Did you try using SELECT PostGIS_version();

What JSON library to use in Scala?

Maybe I've late a bit, but you really should try to use json library from play framework. You could look at documentation. In current 2.1.1 release you could not separately use it without whole play 2, so dependency will looks like this:

val typesaferepo  = "TypeSafe Repo" at "http://repo.typesafe.com/typesafe/releases"
val play2 = "play" %% "play" % "2.1.1"

It will bring you whole play framework with all stuff on board.

But as I know guys from Typesafe have a plan to separate it in 2.2 release. So, there is standalone play-json from 2.2-snapshot.

Can't concat bytes to str

f.write(plaintext)
f.write("\n".encode("utf-8"))

Word count from a txt file program

If you are using graphLab, you can use this function. It is really powerfull

products['word_count'] = graphlab.text_analytics.count_words(your_text)

Get the first element of each tuple in a list in Python

You can use list comprehension:

res_list = [i[0] for i in rows]

This should make the trick

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

You start a thread which runs the static method SumData. However, SumData calls SetTextboxText which isn't static. Thus you need an instance of your form to call SetTextboxText.

Difference between except: and except Exception as e: in Python

Another way to look at this. Check out the details of the exception:

In [49]: try: 
    ...:     open('file.DNE.txt') 
    ...: except Exception as  e: 
    ...:     print(dir(e)) 
    ...:                                                                                                                                    
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'characters_written', 'errno', 'filename', 'filename2', 'strerror', 'with_traceback']

There are lots of "things" to access using the 'as e' syntax.

This code was solely meant to show the details of this instance.

how to change listen port from default 7001 to something different?

The following lines are used to control the listen-port of a server, both are necessary:

    <listen-port>7002</listen-port>
    <listen-port-enabled>true</listen-port-enabled>

Debugging in Maven?

I found an easy way to do this -

Just enter a command like this -

>mvn -Dtest=TestClassName#methodname -Dmaven.surefire.debug test

It will start listening to 5005 port. Now just create a remote debugging in Eclipse through Debug Configurations for localhost(any host) and port 5005.

Source - https://doc.nuxeo.com/display/CORG/How+to+Debug+a+Test+Run+with+Maven

How do I call Objective-C code from Swift?

Quote from the documentation:

Any Objective-C framework (or C library) that’s accessible as a module can be imported directly into Swift. This includes all of the Objective-C system frameworks—such as Foundation, UIKit, and SpriteKit—as well as common C libraries supplied with the system. For example, to import Foundation, simply add this import statement to the top of the Swift file you’re working in:

import Foundation

This import makes all of the Foundation APIs—including NSDate, NSURL, NSMutableData, and all of their methods, properties, and categories—directly available in Swift.

How can I find the link URL by link text with XPath?

Think of the phrase in the square brackets as a WHERE clause in SQL.

So this query says, "select the "href" attribute (@) of an "a" tag that appears anywhere (//), but only where (the bracketed phrase) the textual contents of the "a" tag is equal to 'programming questions site'".

SQLException: No suitable Driver Found for jdbc:oracle:thin:@//localhost:1521/orcl

Sometimes it is the simple things. In my case, I had an invalid url. I had left out a colon before the at sign (@). I had "jdbc:oracle:thin@//localhost" instead of "jdbc:oracle:thin:@//localhost" Hope this helps someone else with this issue.

java: HashMap<String, int> not working

You cannot use primitive types in HashMap. int, or double don't work. You have to use its enclosing type. for an example

Map<String,Integer> m = new HashMap<String,Integer>();

Now both are objects, so this will work.

How do I install Java on Mac OSX allowing version switching?

With Homebrew and jenv:

Assumption: Mac machine and you already have installed homebrew.

Install cask:

$ brew tap caskroom/cask
$ brew tap caskroom/versions

To install latest java:

$ brew cask install java

To install java 8:

$ brew cask install java8

To install java 9:

$ brew cask install java9

If you want to install/manage multiple version then you can use 'jenv':

Install and configure jenv:

$ brew install jenv
$ echo 'export PATH="$HOME/.jenv/bin:$PATH"' >> ~/.bash_profile
$ echo 'eval "$(jenv init -)"' >> ~/.bash_profile
$ source ~/.bash_profile

Add the installed java to jenv:

$ jenv add /Library/Java/JavaVirtualMachines/jdk1.8.0_202.jdk/Contents/Home
$ jenv add /Library/Java/JavaVirtualMachines/jdk1.11.0_2.jdk/Contents/Home

To see all the installed java:

$ jenv versions

Above command will give the list of installed java:

* system (set by /Users/lyncean/.jenv/version)
1.8
1.8.0.202-ea
oracle64-1.8.0.202-ea

Configure the java version which you want to use:

$ jenv global oracle64-1.6.0.39

Initialize a Map containing arrays

Per Mozilla's Map documentation, you can initialize as follows:

private _gridOptions:Map<string, Array<string>> = 
    new Map([
        ["1", ["test"]],
        ["2", ["test2"]]
    ]);

Play audio as microphone input

Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.

I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.

If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.

Java: Enum parameter in method

This should do it:

private enum Alignment { LEFT, RIGHT };    
String drawCellValue (int maxCellLength, String cellValue, Alignment align){
  if (align == Alignment.LEFT)
  {
    //Process it...
  }
}

JavaScript hashmap equivalent

My 'Map' implementation, derived from Christoph's example:

Example usage:

var map = new Map();  // Creates an "in-memory" map
var map = new Map("storageId");  // Creates a map that is loaded/persisted using html5 storage

function Map(storageId) {
    this.current = undefined;
    this.size = 0;
    this.storageId = storageId;
    if (this.storageId) {
        this.keys = new Array();
        this.disableLinking();
    }
}

Map.noop = function() {
    return this;
};

Map.illegal = function() {
    throw new Error("illegal operation for maps without linking");
};

// Map initialisation from an existing object
// doesn't add inherited properties if not explicitly instructed to:
// omitting foreignKeys means foreignKeys === undefined, i.e. == false
// --> inherited properties won't be added
Map.from = function(obj, foreignKeys) {
    var map = new Map;
    for(var prop in obj) {
        if(foreignKeys || obj.hasOwnProperty(prop))
            map.put(prop, obj[prop]);
    }
    return map;
};

Map.prototype.disableLinking = function() {
    this.link = Map.noop;
    this.unlink = Map.noop;
    this.disableLinking = Map.noop;

    this.next = Map.illegal;
    this.key = Map.illegal;
    this.value = Map.illegal;
//    this.removeAll = Map.illegal;


    return this;
};

// Overwrite in Map instance if necessary
Map.prototype.hash = function(value) {
    return (typeof value) + ' ' + (value instanceof Object ?
        (value.__hash || (value.__hash = ++arguments.callee.current)) :
        value.toString());
};

Map.prototype.hash.current = 0;

// --- Mapping functions

Map.prototype.get = function(key) {
    var item = this[this.hash(key)];
    if (item === undefined) {
        if (this.storageId) {
            try {
                var itemStr = localStorage.getItem(this.storageId + key);
                if (itemStr && itemStr !== 'undefined') {
                    item = JSON.parse(itemStr);
                    this[this.hash(key)] = item;
                    this.keys.push(key);
                    ++this.size;
                }
            } catch (e) {
                console.log(e);
            }
        }
    }
    return item === undefined ? undefined : item.value;
};

Map.prototype.put = function(key, value) {
    var hash = this.hash(key);

    if(this[hash] === undefined) {
        var item = { key : key, value : value };
        this[hash] = item;

        this.link(item);
        ++this.size;
    }
    else this[hash].value = value;
    if (this.storageId) {
        this.keys.push(key);
        try {
            localStorage.setItem(this.storageId + key, JSON.stringify(this[hash]));
        } catch (e) {
            console.log(e);
        }
    }
    return this;
};

Map.prototype.remove = function(key) {
    var hash = this.hash(key);
    var item = this[hash];
    if(item !== undefined) {
        --this.size;
        this.unlink(item);

        delete this[hash];
    }
    if (this.storageId) {
        try {
            localStorage.setItem(this.storageId + key, undefined);
        } catch (e) {
            console.log(e);
        }
    }
    return this;
};

// Only works if linked
Map.prototype.removeAll = function() {
    if (this.storageId) {
        for (var i=0; i<this.keys.length; i++) {
            this.remove(this.keys[i]);
        }
        this.keys.length = 0;
    } else {
        while(this.size)
            this.remove(this.key());
    }
    return this;
};

// --- Linked list helper functions

Map.prototype.link = function(item) {
    if (this.storageId) {
        return;
    }
    if(this.size == 0) {
        item.prev = item;
        item.next = item;
        this.current = item;
    }
    else {
        item.prev = this.current.prev;
        item.prev.next = item;
        item.next = this.current;
        this.current.prev = item;
    }
};

Map.prototype.unlink = function(item) {
    if (this.storageId) {
        return;
    }
    if(this.size == 0)
        this.current = undefined;
    else {
        item.prev.next = item.next;
        item.next.prev = item.prev;
        if(item === this.current)
            this.current = item.next;
    }
};

// --- Iterator functions - only work if map is linked

Map.prototype.next = function() {
    this.current = this.current.next;
};

Map.prototype.key = function() {
    if (this.storageId) {
        return undefined;
    } else {
        return this.current.key;
    }
};

Map.prototype.value = function() {
    if (this.storageId) {
        return undefined;
    }
    return this.current.value;
};

Spring MVC @PathVariable with dot (.) is getting truncated

Finally I found solution in Spring Docs:

To completely disable the use of file extensions, you must set both of the following:

 useSuffixPatternMatching(false), see PathMatchConfigurer

 favorPathExtension(false), see ContentNegotiationConfigurer

Adding this to my WebMvcConfigurerAdapter implementation solved the problem:

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer.favorPathExtension(false);
}

@Override
public void configurePathMatch(PathMatchConfigurer matcher) {
    matcher.setUseSuffixPatternMatch(false);
}

List of foreign keys and the tables they reference in Oracle DB

The referenced primary key is described in the columns r_owner and r_constraint_name of the table ALL_CONSTRAINTS. This will give you the info you want:

SELECT a.table_name, a.column_name, a.constraint_name, c.owner, 
       -- referenced pk
       c.r_owner, c_pk.table_name r_table_name, c_pk.constraint_name r_pk
  FROM all_cons_columns a
  JOIN all_constraints c ON a.owner = c.owner
                        AND a.constraint_name = c.constraint_name
  JOIN all_constraints c_pk ON c.r_owner = c_pk.owner
                           AND c.r_constraint_name = c_pk.constraint_name
 WHERE c.constraint_type = 'R'
   AND a.table_name = :TableName

How to find index of an object by key and value in an javascript array

You can also make it a reusable method by expending JavaScript:

Array.prototype.findIndexBy = function(key, value) {
    return this.findIndex(item => item[key] === value)
}

const peoples = [{name: 'john'}]
const cats = [{id: 1, name: 'kitty'}]

peoples.findIndexBy('name', 'john')
cats.findIndexBy('id', 1)

How to convert from Hex to ASCII in JavaScript?

For completeness sake the reverse function:

function a2hex(str) {
  var arr = [];
  for (var i = 0, l = str.length; i < l; i ++) {
    var hex = Number(str.charCodeAt(i)).toString(16);
    arr.push(hex);
  }
  return arr.join('');
}
a2hex('2460'); //returns 32343630

How to duplicate sys.stdout to a log file?

As described elsewhere, perhaps the best solution is to use the logging module directly:

import logging

logging.basicConfig(level=logging.DEBUG, filename='mylog.log')
logging.info('this should to write to the log file')

However, there are some (rare) occasions where you really want to redirect stdout. I had this situation when I was extending django's runserver command which uses print: I didn't want to hack the django source but needed the print statements to go to a file.

This is a way of redirecting stdout and stderr away from the shell using the logging module:

import logging, sys

class LogFile(object):
    """File-like object to log text using the `logging` module."""

    def __init__(self, name=None):
        self.logger = logging.getLogger(name)

    def write(self, msg, level=logging.INFO):
        self.logger.log(level, msg)

    def flush(self):
        for handler in self.logger.handlers:
            handler.flush()

logging.basicConfig(level=logging.DEBUG, filename='mylog.log')

# Redirect stdout and stderr
sys.stdout = LogFile('stdout')
sys.stderr = LogFile('stderr')

print 'this should to write to the log file'

You should only use this LogFile implementation if you really cannot use the logging module directly.

How to trigger an event in input text after I stop typing/writing?

You should assign setTimeout to a variable and use clearTimeout to clear it on keypress.

var timer = '';

$('input#username').keypress(function() {
  clearTimeout(timer);
  timer = setTimeout(function() {
    //Your code here
  }, 3000); //Waits for 3 seconds after last keypress to execute the above lines of code
});

Fiddle

Hope this helps.

INSTALL_FAILED_DUPLICATE_PERMISSION... C2D_MESSAGE

In my case I was using a third party library (i.e. vendor) and the library comes with a sample app which I already had install on my device. So that sample app was now conflicting each time I try to install my own app implementing the library. So I just uninstalled the vendor's sample app and it works afterwards.

How can I get my webapp's base URL in ASP.NET MVC?

The trick with relying upon IIS is that IIS bindings can be different from your public URLs (WCF I'm looking at you), especially with multi-homed production machines. I tend to vector toward using configuration to explicitly define the "base" url for external purposes as that tends to be a bit more successful than extracting it from the Request object.

Capture key press (or keydown) event on DIV element

tabindex HTML attribute indicates if its element can be focused, and if/where it participates in sequential keyboard navigation (usually with the Tab key). Read MDN Web Docs for full reference.

Using Jquery

_x000D_
_x000D_
$( "#division" ).keydown(function(evt) {
    evt = evt || window.event;
    console.log("keydown: " + evt.keyCode);
});
_x000D_
#division {
  width: 90px;
  height: 30px;
  background: lightgrey;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="division" tabindex="0"></div>
_x000D_
_x000D_
_x000D_

Using JavaScript

_x000D_
_x000D_
var el = document.getElementById("division");

el.onkeydown = function(evt) {
    evt = evt || window.event;
    console.log("keydown: " + evt.keyCode);
};
_x000D_
#division {
  width: 90px;
  height: 30px;
  background: lightgrey;
}
_x000D_
<div id="division" tabindex="0"></div>
_x000D_
_x000D_
_x000D_

Scroll to element on click in Angular 4

There is actually a pure javascript way to accomplish this without using setTimeout or requestAnimationFrame or jQuery.

In short, find the element in the scrollView that you want to scroll to, and use scrollIntoView.

el.scrollIntoView({behavior:"smooth"});

Here is a plunkr.

Saving numpy array to txt file row wise

Very very easy: [1,2,3]

A list is like a column.

1
2
3

If you want a list like a row, double corchete:

[[1, 2, 3]]  --->    1, 2, 3

and

[[1, 2, 3], [4, 5, 6]]  ---> 1, 2, 3
                             4, 5, 6

Finally:

np.savetxt("file", [['r1c1', 'r1c2'], ['r2c1', 'r2c2']], delimiter=';', fmt='%s')

Note, the comma between square brackets, inner list are elements of the outer list

What's the difference between Visual Studio Community and other, paid versions?

There are 2 major differences.

  1. Technical
  2. Licensing

Technical, there are 3 major differences:

First and foremost, Community doesn't have TFS support.
You'll just have to use git (arguable whether this constitutes a disadvantage or whether this actually is a good thing).
Note: This is what MS wrote. Actually, you can check-in&out with TFS as normal, if you have a TFS server in the network. You just cannot use Visual Studio as TFS SERVER.

Second, VS Community is severely limited in its testing capability.
Only unit tests. No Performance tests, no load tests, no performance profiling.

Third, VS Community's ability to create Virtual Environments has been severely cut.

On the other hand, syntax highlighting, IntelliSense, Step-Through debugging, GoTo-Definition, Git-Integration and Build/Publish are really all the features I need, and I guess that applies to a lot of developers.

For all other things, there are tools that do the same job faster, better and cheaper.

If you, like me, anyway use git, do unit testing with NUnit, and use Java-Tools to do Load-Testing on Linux plus TeamCity for CI, VS Community is more than sufficient, technically speaking.

Licensing:

A) If you're an individual developer (no enterprise, no organization), no difference (AFAIK), you can use CommunityEdition like you'd use the paid edition (as long as you don't do subcontracting)
B) You can use CommunityEdition freely for OpenSource (OSI) projects
C) If you're an educational insitution, you can use CommunityEdition freely (for education/classroom use)
D) If you're an enterprise with 250 PCs or users or more than one million US dollars in revenue (including subsidiaries), you are NOT ALLOWED to use CommunityEdition.
E) If you're not an enterprise as defined above, and don't do OSI or education, but are an "enterprise"/organization, with 5 or less concurrent (VS) developers, you can use VS Community freely (but only if you're the owner of the software and sell it, not if you're a subcontractor creating software for a larger enterprise, software which in the end the enterprise will own), otherwise you need a paid edition.

The above does not consitute legal advise.
See also:
https://softwareengineering.stackexchange.com/questions/262916/understanding-visual-studio-community-edition-license

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?

  
from chromedriver_py import binary_path
 
 
chrome_options = webdriver.ChromeOptions()
   chrome_options.add_argument('--headless')
   chrome_options.add_argument('--no-sandbox')
   chrome_options.add_argument('--disable-gpu')
   chrome_options.add_argument('--window-size=1280x1696')
   chrome_options.add_argument('--user-data-dir=/tmp/user-data')
   chrome_options.add_argument('--hide-scrollbars')
   chrome_options.add_argument('--enable-logging')
   chrome_options.add_argument('--log-level=0')
   chrome_options.add_argument('--v=99')
   chrome_options.add_argument('--single-process')
   chrome_options.add_argument('--data-path=/tmp/data-path')
   chrome_options.add_argument('--ignore-certificate-errors')
   chrome_options.add_argument('--homedir=/tmp')
   chrome_options.add_argument('--disk-cache-dir=/tmp/cache-dir')
   chrome_options.add_argument('user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36')
   
  driver = webdriver.Chrome(executable_path = binary_path,options=chrome_options)

Clear data in MySQL table with PHP?

TRUNCATE TABLE table;

is the SQL command. In PHP, you'd use:

mysql_query('TRUNCATE TABLE table;');

Get jQuery version from inspecting the jQuery object

You can get the version of the jquery by simply printing object.jquery, the object can be any object created by you using $.

For example: if you have created a <div> element as following

var divObj = $("div");

then by printing divObj.jquery will show you the version like 1.7.1

Basically divObj inherits all the property of $() or jQuery() i.e if you try to print jQuery.fn.jquery will also print the same version like 1.7.1

How to format a number 0..9 to display with 2 digits (it's NOT a date)

You can use this:

NumberFormat formatter = new DecimalFormat("00");  
String s = formatter.format(1); // ----> 01

How to fix "'System.AggregateException' occurred in mscorlib.dll"

You could handle the exception directly so it would not crash your program (catching the AggregateException). You could also look at the Inner Exception, this will give you a more detailed explanation of what went wrong:

try {
    // your code 
} catch (AggregateException e) {

}

Angular checkbox and ng-click

cardeal's answer was really helpful. Took it a little further and figured it may help others some where down the line. Here is the fiddle:

https://jsfiddle.net/vtL5x0wh/

And the code:

<body ng-app="checkboxExample">
  <script>
  angular.module('checkboxExample', [])
    .controller('ExampleController', ['$scope', function($scope) {

    $scope.value0 = "none";
    $scope.value1 = "none";
    $scope.value2 = "none";
    $scope.value3 = "none";

    $scope.checkboxModel = {
        critical1: {selected: true, id: 'C1', error:'critical' , score:20},
        critical2: {selected: false, id: 'C2', error:'critical' , score:30},
        critical3: {selected: false, id: 'C3', error:'critical' , score:40},

       myClick : function($event) { 
          $scope.value0 = $event.selected;
          $scope.value1 = $event.id;
          $scope.value2 = $event.error;
          $scope.value3 = $event.score;
        }
    };

   }]);
</script>
<form name="myForm" ng-controller="ExampleController">
  <label>


    Value1:
    <input type="checkbox" ng-model="checkboxModel.critical1.selected" ng-change="checkboxModel.myClick(checkboxModel.critical1)">
  </label><br/>
  <label>Value2:
    <input type="checkbox" ng-model="checkboxModel.critical2.selected" ng-change="checkboxModel.myClick(checkboxModel.critical2)">
   </label><br/>
     <label>Value3:
    <input type="checkbox" ng-model="checkboxModel.critical3.selected" ng-change="checkboxModel.myClick(checkboxModel.critical3)">
   </label><br/><br/><br/><br/>
  <tt>selected = {{value0}}</tt><br/>
  <tt>id = {{value1}}</tt><br/>
  <tt>error = {{value2}}</tt><br/>
  <tt>score = {{value3}}</tt><br/>
 </form>

How to calculate Date difference in Hive

If you need the difference in seconds (i.e.: you're comparing dates with timestamps, and not whole days), you can simply convert two date or timestamp strings in the format 'YYYY-MM-DD HH:MM:SS' (or specify your string date format explicitly) using unix_timestamp(), and then subtract them from each other to get the difference in seconds. (And can then divide by 60.0 to get minutes, or by 3600.0 to get hours, etc.)

Example:

UNIX_TIMESTAMP('2017-12-05 10:01:30') - UNIX_TIMESTAMP('2017-12-05 10:00:00') AS time_diff -- This will return 90 (seconds). Unix_timestamp converts string dates into BIGINTs. 

More on what you can do with unix_timestamp() here, including how to convert strings with different date formatting: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions

Setting table row height

I found the best answer for my purposes was to use:

.topics tr { 
    overflow: hidden;
    height: 14px;
    white-space: nowrap;
}

The white-space: nowrap is important as it prevents your row's cells from breaking across multiple lines.

I personally like to add text-overflow: ellipsis to my th and td elements to make the overflowing text look nicer by adding the trailing fullstops, for example Too long gets dots...

Why use Gradle instead of Ant or Maven?

Gradle put the fun back into building/assembling software. I used ant to build software my entire career and I have always considered the actual "buildit" part of the dev work being a necessary evil. A few months back our company grew tired of not using a binary repo (aka checking in jars into the vcs) and I was given the task to investigate this. Started with ivy since it could be bolted on top of ant, didn't have much luck getting my built artifacts published like I wanted. I went for maven and hacked away with xml, worked splendid for some simple helper libs but I ran into serious problems trying to bundle applications ready for deploy. Hassled quite a while googling plugins and reading forums and wound up downloading trillions of support jars for various plugins which I had a hard time using. Finally I went for gradle (getting quite bitter at this point, and annoyed that "It shouldn't be THIS hard!")

But from day one my mood started to improve. I was getting somewhere. Took me like two hours to migrate my first ant module and the build file was basically nothing. Easily fitted one screen. The big "wow" was: build scripts in xml, how stupid is that? the fact that declaring one dependency takes ONE row is very appealing to me -> you can easily see all dependencies for a certain project on one page. From then on I been on a constant roll, for every problem I faced so far there is a simple and elegant solution. I think these are the reasons:

  • groovy is very intuitive for java developers
  • documentation is great to awesome
  • the flexibility is endless

Now I spend my days trying to think up new features to add to our build process. How sick is that?

Python: create dictionary using dict() with integer keys?

a = dict(one=1, two=2, three=3)

Providing keyword arguments as in this example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.

What is "android:allowBackup"?

It is privacy concern. It is recommended to disallow users to backup an app if it contains sensitive data. Having access to backup files (i.e. when android:allowBackup="true"), it is possible to modify/read the content of an app even on a non-rooted device.

Solution - use android:allowBackup="false" in the manifest file.

You can read this post to have more information: Hacking Android Apps Using Backup Techniques

Complex JSON nesting of objects and arrays

First, choosing a data structure(xml,json,yaml) usually includes only a readability/size problem. For example

Json is very compact, but no human being can read it easily, very hard do debug,

Xml is very large, but everyone can easily read/debug it,

Yaml is in between Xml and json.

But if you want to work with Javascript heavily and/or your software makes a lot of data transfer between browser-server, you should use Json, because it is pure javascript and very compact. But don't try to write it in a string, use libraries to generate the code you needed from an object.

Hope this helps.

How to programmatically send a 404 response with Express/Node?

IMO the nicest way is to use the next() function:

router.get('/', function(req, res, next) {
    var err = new Error('Not found');
    err.status = 404;
    return next(err);
}

Then the error is handled by your error handler and you can style the error nicely using HTML.

NSString with \n or line break

I found that when I was reading strings in from a .plist file, occurrences of "\n" were parsed as "\\n". The solution for me was to replace occurrences of "\\n" with "\n". For example, given an instance of NSString named myString read in from my .plist file, I had to call...

myString = [myString stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];

... before assigning it to my UILabel instance...

myLabel.text = myString;

How to insert double and float values to sqlite?

SQL Supports following types of affinities:

  • TEXT
  • NUMERIC
  • INTEGER
  • REAL
  • BLOB

If the declared type for a column contains any of these "REAL", "FLOAT", or "DOUBLE" then the column has 'REAL' affinity.

Remove warning messages in PHP

You really should fix whatever's causing the warning, but you can control visibility of errors with error_reporting(). To skip warning messages, you could use something like:

error_reporting(E_ERROR | E_PARSE);

What does .pack() do?

The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.

From Java tutorial

You should also refer to Javadocs any time you need additional information on any Java API

How to break out of while loop in Python?

Walrus operator (assignment expressions added to python 3.8) and while-loop-else-clause can do it more pythonic:

myScore = 0
while ans := input("Roll...").lower() == "r":
    # ... do something
else:
    print("Now I'll see if I can break your score...")

Select tableview row programmatically

UITableView's selectRowAtIndexPath:animated:scrollPosition: should do the trick.

Just pass UITableViewScrollPositionNone for scrollPosition and the user won't see any movement.


You should also be able to manually run the action:

[theTableView.delegate tableView:theTableView didSelectRowAtIndexPath:indexPath]

after you selectRowAtIndexPath:animated:scrollPosition: so the highlight happens as well as any associated logic.

how to run a command at terminal from java program?

I vote for Karthik T's answer. you don't need to open a terminal to run commands.

For example,

// file: RunShellCommandFromJava.java
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class RunShellCommandFromJava {

    public static void main(String[] args) {

        String command = "ping -c 3 www.google.com";

        Process proc = Runtime.getRuntime().exec(command);

        // Read the output

        BufferedReader reader =  
              new BufferedReader(new InputStreamReader(proc.getInputStream()));

        String line = "";
        while((line = reader.readLine()) != null) {
            System.out.print(line + "\n");
        }

        proc.waitFor();   

    }
} 

The output:

$ javac RunShellCommandFromJava.java
$ java RunShellCommandFromJava
PING http://google.com (123.125.81.12): 56 data bytes
64 bytes from 123.125.81.12: icmp_seq=0 ttl=59 time=108.771 ms
64 bytes from 123.125.81.12: icmp_seq=1 ttl=59 time=119.601 ms
64 bytes from 123.125.81.12: icmp_seq=2 ttl=59 time=11.004 ms

--- http://google.com ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 11.004/79.792/119.601/48.841 ms

sql delete statement where date is greater than 30 days

Although the DATEADD is probably the most transparrent way of doing this, it is worth noting that simply getdate()-30 will also suffice.

Also, are you looking for 30 days from now, i.e. including hours, minutes, seconds, etc? Or 30 days from midnight today (e.g. 12/06/2010 00:00:00.000). In which case, you might consider:

SELECT * 
FROM Results 
WHERE convert(varchar(8), [Date], 112) >= convert(varchar(8), getdate(), 112)

Wrap text in <td> tag

.tbl {
    table-layout:fixed;
    border-collapse: collapse;
    background: #fff;
 }

.tbl td {
    text-overflow:ellipsis;
    overflow:hidden;
    white-space:nowrap;
}

Credits to http://www.blakems.com/archives/000077.html

MySQL Creating tables with Foreign Keys giving errno: 150

I've found another reason this fails... case sensitive table names.

For this table definition

CREATE TABLE user (
  userId int PRIMARY KEY AUTO_INCREMENT,
  username varchar(30) NOT NULL
) ENGINE=InnoDB;

This table definition works

CREATE TABLE product (
  id int PRIMARY KEY AUTO_INCREMENT,
  userId int,
  FOREIGN KEY fkProductUser1(userId) REFERENCES **u**ser(userId)
) ENGINE=InnoDB;

whereas this one fails

CREATE TABLE product (
  id int PRIMARY KEY AUTO_INCREMENT,
  userId int,
  FOREIGN KEY fkProductUser1(userId) REFERENCES User(userId)
) ENGINE=InnoDB;

The fact that it worked on Windows and failed on Unix took me a couple of hours to figure out. Hope that helps someone else.

Resize jqGrid when browser is resized?

The main answer worked for me but made the app extremely unresponsive in IE, so I used a timer as suggested. Code looks something like this ($(#contentColumn) is the div that the JQGrid sits in):

  function resizeGrids() {
    var reportObjectsGrid = $("#ReportObjectsGrid");
    reportObjectsGrid.setGridWidth($("#contentColumn").width());
};

var resizeTimer;

$(window).bind('resize', function () {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(resizeGrids, 60);
});

How do I use arrays in C++?

Assignment

For no particular reason, arrays cannot be assigned to one another. Use std::copy instead:

#include <algorithm>

// ...

int a[8] = {2, 3, 5, 7, 11, 13, 17, 19};
int b[8];
std::copy(a + 0, a + 8, b);

This is more flexible than what true array assignment could provide because it is possible to copy slices of larger arrays into smaller arrays. std::copy is usually specialized for primitive types to give maximum performance. It is unlikely that std::memcpy performs better. If in doubt, measure.

Although you cannot assign arrays directly, you can assign structs and classes which contain array members. That is because array members are copied memberwise by the assignment operator which is provided as a default by the compiler. If you define the assignment operator manually for your own struct or class types, you must fall back to manual copying for the array members.

Parameter passing

Arrays cannot be passed by value. You can either pass them by pointer or by reference.

Pass by pointer

Since arrays themselves cannot be passed by value, usually a pointer to their first element is passed by value instead. This is often called "pass by pointer". Since the size of the array is not retrievable via that pointer, you have to pass a second parameter indicating the size of the array (the classic C solution) or a second pointer pointing after the last element of the array (the C++ iterator solution):

#include <numeric>
#include <cstddef>

int sum(const int* p, std::size_t n)
{
    return std::accumulate(p, p + n, 0);
}

int sum(const int* p, const int* q)
{
    return std::accumulate(p, q, 0);
}

As a syntactic alternative, you can also declare parameters as T p[], and it means the exact same thing as T* p in the context of parameter lists only:

int sum(const int p[], std::size_t n)
{
    return std::accumulate(p, p + n, 0);
}

You can think of the compiler as rewriting T p[] to T *p in the context of parameter lists only. This special rule is partly responsible for the whole confusion about arrays and pointers. In every other context, declaring something as an array or as a pointer makes a huge difference.

Unfortunately, you can also provide a size in an array parameter which is silently ignored by the compiler. That is, the following three signatures are exactly equivalent, as indicated by the compiler errors:

int sum(const int* p, std::size_t n)

// error: redefinition of 'int sum(const int*, size_t)'
int sum(const int p[], std::size_t n)

// error: redefinition of 'int sum(const int*, size_t)'
int sum(const int p[8], std::size_t n)   // the 8 has no meaning here

Pass by reference

Arrays can also be passed by reference:

int sum(const int (&a)[8])
{
    return std::accumulate(a + 0, a + 8, 0);
}

In this case, the array size is significant. Since writing a function that only accepts arrays of exactly 8 elements is of little use, programmers usually write such functions as templates:

template <std::size_t n>
int sum(const int (&a)[n])
{
    return std::accumulate(a + 0, a + n, 0);
}

Note that you can only call such a function template with an actual array of integers, not with a pointer to an integer. The size of the array is automatically inferred, and for every size n, a different function is instantiated from the template. You can also write quite useful function templates that abstract from both the element type and from the size.

CSS Circular Cropping of Rectangle Image

Try this:

img {
    height: auto;
    width: 100%;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    -ms-border-radius: 50%;
    -o-border-radius: 50%;
    border-radius: 50%;
}

DEMO here.

OR:

.rounded {
    height: 100px;
    width: 100px;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    -ms-border-radius: 50%;
    -o-border-radius: 50%;
    border-radius: 50%;
    background:url("http://www.electricvelocity.com.au/Upload/Blogs/smart-e-bike-side_2.jpg") center no-repeat;
    background-size:cover;
}

DEMO here.

How to select rows that have current day's timestamp?

Or you could use the CURRENT_DATE alternative, with the same result:

SELECT * FROM yourtable WHERE created >= CURRENT_DATE

Examples from database.guide

How do I count cells that are between two numbers in Excel?

=COUNTIFS(H5:H21000,">=100", H5:H21000,"<999")

Python NameError: name is not defined

You must define the class before creating an instance of the class. Move the invocation of Something to the end of the script.

You can try to put the cart before the horse and invoke procedures before they are defined, but it will be an ugly hack and you will have to roll your own as defined here:

Make function definition in a python file order independent

jQuery - simple input validation - "empty" and "not empty"

    jQuery("#input").live('change', function() {
        // since we check more than once against the value, place it in a var.
        var inputvalue = $("#input").attr("value");

        // if it's value **IS NOT** ""
        if(inputvalue !== "") {
            jQuery(this).css('outline', 'solid 1px red'); 
        }   

        // else if it's value **IS** ""
        else if(inputvalue === "") {
            alert('empty'); 
        }

    });

Purpose of __repr__ method?

__repr__ is used by the standalone Python interpreter to display a class in printable format. Example:

~> python3.5
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  5 2015, 21:12:44) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class StackOverflowDemo:
...     def __init__(self):
...         pass
...     def __repr__(self):
...         return '<StackOverflow demo object __repr__>'
... 
>>> demo = StackOverflowDemo()
>>> demo
<StackOverflow demo object __repr__>

In cases where a __str__ method is not defined in the class, it will call the __repr__ function in an attempt to create a printable representation.

>>> str(demo)
'<StackOverflow demo object __repr__>'

Additionally, print()ing the class will call __str__ by default.


Documentation, if you please

Proper way to assert type of variable in Python

Doing type('') is effectively equivalent to str and types.StringType

so type('') == str == types.StringType will evaluate to "True"

Note that Unicode strings which only contain ASCII will fail if checking types in this way, so you may want to do something like assert type(s) in (str, unicode) or assert isinstance(obj, basestring), the latter of which was suggested in the comments by 007Brendan and is probably preferred.

isinstance() is useful if you want to ask whether an object is an instance of a class, e.g:

class MyClass: pass

print isinstance(MyClass(), MyClass) # -> True
print isinstance(MyClass, MyClass()) # -> TypeError exception

But for basic types, e.g. str, unicode, int, float, long etc asking type(var) == TYPE will work OK.

Format string to a 3 digit number

It's called Padding:

myString.PadLeft(3, '0')

HTML -- two tables side by side

<div style="float: left;margin-right:10px">
  <table>
    <tr>
      <td>..</td>
    </tr>
  </table>
</div>
<div style="float: left">
  <table>
    <tr>
      <td>..</td>
    </tr>
  </table>
</div>

Using iFrames In ASP.NET

Another option is to use placeholders.

Html:

<body>
   <div id="root">
      <asp:PlaceHolder ID="iframeDiv" runat="server"/>
   </div>
</body>

C#:

iframeDiv.Controls.Add(new LiteralControl("<iframe src=\"" + whatever.com + "\"></iframe><br />"));

Preserve line breaks in angularjs

Yes, I would either use the <pre> tag or use ng-bind-html-unsafe http://docs-angularjs-org-dev.appspot.com/api/ng.directive:ngBindHtmlUnsafe (use ng-bind-html if you are using 1.2+) after using .replace() to change /n to <br />

Add column with number of days between dates in DataFrame pandas

How about this:

times['days_since'] = max(list(df.index.values))  
times['days_since'] = times['days_since'] - times['months']  
times

How to style an asp.net menu with CSS

Just want to throw something in to help people still having this problem. (for me at least) the css is showing that it puts default classes of level1, level2, and level3 on each piece of the menu(level 1 being the menu, level2 being the first dropdown, level3 being the third popout). Setting the padding in css

.level2
{
padding: 2px 2px 2px 2px;
}

does work for adding the padding to each li in the first dropdown.

MySQL string replace

You can simply use replace() function,

with where clause-

update tabelName set columnName=REPLACE(columnName,'from','to') where condition;

without where clause-

update tabelName set columnName=REPLACE(columnName,'from','to');

Note: The above query if for update records directly in table, if you want on select query and the data should not be affected in table then can use the following query-

select REPLACE(columnName,'from','to') as updateRecord;

Import a file from a subdirectory?

Try import .lib.BoxTime. For more information read about relative import in PEP 328.

How to change the window title of a MATLAB plotting figure?

It can also be done this way:

figure(xx);
set(gcf, 'name', 'Name goes here')

gcf gets the current figure handle.

Wampserver icon not going green fully, mysql services not starting up?

  1. Click on wamp (Yellow) icon

  2. Go Apache-> Service-> Test port 80. If port is available to use then go to Apache->Service-> Install Service

  3. then click on Restart All Services.

Warning about SSL connection when connecting to MySQL database

you need to user your mysql path like this:

<property name="url" value="jdbc:mysql://localhost:3306/world?useSSL=true"/>

Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style

If you are using WebStorm and you are on Windows i would recommend you to click settings/editor/code style/general tab and select "windows(\r\n) from the dropdown menu.These steps will also apply for Rider.

enter image description here

jQuery make global variable

Your code looks fine except the possibility that if the variable declaration is inside a dom read handler then it will not be a global variable... it will be a closure variable

jQuery(function(){
    //here it is a closure variable
    var a_href;
    $('sth a').on('click', function(e){
        a_href = $(this).attr('href');

          console.log(a_href);  
         //output is "home"

        e.preventDefault();
    }
})

To make the variable global, one solution is to declare the variable in global scope

var a_href;
jQuery(function(){
    $('sth a').on('click', function(e){
        a_href = $(this).attr('href');

          console.log(a_href);  
         //output is "home"

        e.preventDefault();
    }
})

another is to set the variable as a property of the window object

window.a_href = $(this).attr('href')

Why console printing undefined

You are getting the output as undefined because even though the variable is declared, you have not initialized it with a value, the value of the variable is set only after the a element is clicked till that time the variable will have the value undefined. If you are not declaring the variable it will throw a ReferenceError

What causes a SIGSEGV

Wikipedia has the answer, along with a number of other sources.

A segfault basically means you did something bad with pointers. This is probably a segfault:

char *c = NULL;
...
*c; // dereferencing a NULL pointer

Or this:

char *c = "Hello";
...
c[10] = 'z'; // out of bounds, or in this case, writing into read-only memory

Or maybe this:

char *c = new char[10];
...
delete [] c;
...
c[2] = 'z'; // accessing freed memory

Same basic principle in each case - you're doing something with memory that isn't yours.

Ellipsis for overflow text in dropdown boxes

You can use this jQuery function instead of plus Bootstrap tooltip

function DDLSToolTipping(ddlsArray) {
    $(ddlsArray).each(function (index, ddl) {
        DDLToolTipping(ddl)
    });
}

function DDLToolTipping(ddlID, maxLength, allowDots) {
    if (maxLength == null) { maxLength = 12 }
    if (allowDots == null) { allowDots = true }

    var selectedOption = $(ddlID).find('option:selected').text();

    if (selectedOption.length > maxLength) {
        $(ddlID).attr('data-toggle', "tooltip")
                .attr('title', selectedOption);

        if (allowDots) {
            $(ddlID).prev('sup').remove();
            $(ddlID).before(
            "<sup style='font-size: 9.5pt;position: relative;top: -1px;left: -17px;z-index: 1000;background-color: #f7f7f7;border-radius: 229px;font-weight: bold;color: #666;'>...</sup>"
               )
        }
    }

    else if ($(ddlID).attr('title') != null) {
        $(ddlID).removeAttr('data-toggle')
                .removeAttr('title');
    }
}

What is SaaS, PaaS and IaaS? With examples

IaaS (Infra as a Service)

IaaS provides the infrastructure such as virtual machines and other resources like virtual-machine disk image library, block and file-based storage, firewalls, load balancers, IP addresses, virtual local area networks etc. Infrastructure as service or IaaS is the basic layer in cloud computing model.

Common examples: DigitalOcean, Linode, Rackspace, Amazon Web Services (AWS), Cisco Metapod, Microsoft Azure, Google Compute Engine (GCE) are some popular examples of Iaas.

PaaS (Platform as a Service)

PaaS or platform as a service model provides you computing platforms which typically includes an operating system, programming language execution environment, database, web server. technically It is a layer on top of IaaS as the second thing you demand after Infrastructure is a platform.

Common examples: AWS Elastic Beanstalk, Windows Azure, Heroku, Force.com, Google App Engine, Apache Stratos.

SaaS (Software as a Service)

In a SaaS, you are provided access to application services installed at a server. You don’t have to worry about installation, maintenance or coding of that software. You can access and operate the software with just your browser. You don’t have to download or install any kind of setup or OS, the software is just available for you to access and operate. The software maintenance or setup or help will be provided by SaaS provider company and you will only have to pay for your usage.

Common examples: Google Apps, Microsoft office365, Google docs, Gmail, WHMCS billing software

Basic difference between IaaS, PaaS & SaaS enter image description here enter image description here

Copy table without copying data

Try:

CREATE TABLE foo SELECT * FROM bar LIMIT 0

Or:

CREATE TABLE foo SELECT * FROM bar WHERE 1=0

Pull request vs Merge request

GitLab's "merge request" feature is equivalent to GitHub's "pull request" feature. Both are means of pulling changes from another branch or fork into your branch and merging the changes with your existing code. They are useful tools for code review and change management.

An article from GitLab discusses the differences in naming the feature:

Merge or pull requests are created in a git management application and ask an assigned person to merge two branches. Tools such as GitHub and Bitbucket choose the name pull request since the first manual action would be to pull the feature branch. Tools such as GitLab and Gitorious choose the name merge request since that is the final action that is requested of the assignee. In this article we'll refer to them as merge requests.

A "merge request" should not be confused with the git merge command. Neither should a "pull request" be confused with the git pull command. Both git commands are used behind the scenes in both pull requests and merge requests, but a merge/pull request refers to a much broader topic than just these two commands.

Git, fatal: The remote end hung up unexpectedly

Seems like it can be one of a thousand things.

For me, I was initially pushing master and develop (master had no changes) via SourceTree. Changing this to develop only worked.

How to embed PDF file with responsive width

Simply do this:

<object data="resume.pdf" type="application/pdf" width="100%" height="800px"> 
  <p>It appears you don't have a PDF plugin for this browser.
   No biggie... you can <a href="resume.pdf">click here to
  download the PDF file.</a></p>  
</object>

include external .js file in node.js app

To place an emphasis on what everyone else has been saying var foo in top level does not create a global variable. If you want a global variable then write global.foo. but we all know globals are evil.

If you are someone who uses globals like that in a node.js project I was on I would refactor them away for as there are just so few use cases for this (There are a few exceptions but this isn't one).

// Declare application
var app = require('express').createServer();

// Declare usefull stuff for DB purposes
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

require('./models/car.js').make(Schema, mongoose);

in car.js

function make(Schema, mongoose) {
    // Define Car model
    CarSchema = new Schema({
      brand        : String,
      type : String
    });
    mongoose.model('Car', CarSchema);
}

module.exports.make = make;

IE Enable/Disable Proxy Settings via Registry

I know this is an old question, however here is a simple one-liner to switch it on or off depending on its current state:

set-itemproperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'  -name ProxyEnable -value (-not ([bool](get-itemproperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'  -name ProxyEnable).proxyenable))

How to access Spring MVC model object in javascript file?

This way works and with this structure you can create your own framework and do it with less boilerplate.

Sorry if some error is present, I'm writing this handly with my cellphone

Maven dependency:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>1.7.1</version>
</dependency>

Java:

Person.java (Person Object Class)

Class Person {

    private String name;

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

PersonController.java (Person Controller)

@RestController
public class PersonController implements Controller {

    @RequestMapping("/person")
    public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
        Person person = new Person();
        person.setName("Person's name");
        Gson gson = new Gson();

        ModelAndView modelAndView = new ModelAndView("person");
        modelAndView.addObject("person", gson.toJson(person));

        return modelAndView;
    }
}

View:

person.jsp

<html>
    <head>
        <title>Person Example</title>
        <script src="jquery-1.11.3.min.js"></script>
        <script type="text/javascript" src="personScript.js"></script>
    </head>
    <body>
        <h1>Person/h1>
        <input type="hidden" id="person" value="${person}">     
    </body>
</html>

Javascript:

personScript.js

function parseJSON(data) {
    return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))(); 
}

$(document).ready(function() {
    var personJson = $('#person');
    person = parseJSON(personJson.val());
    alert(person.name);
});

how to calculate percentage in python

I guess you're learning how to Python. The other answers are right. But I am going to answer your main question: "how to calculate percentage in python"

Although it works the way you did it, it doesn´t look very pythonic. Also, what happens if you need to add a new subject? You'll have to add another variable, use another input, etc. I guess you want the average of all marks, so you will also have to modify the count of the subjects everytime you add a new one! Seems a mess...

I´ll throw a piece of code where the only thing you'll have to do is to add the name of the new subject in a list. If you try to understand this simple piece of code, your Python coding skills will experiment a little bump.

#!/usr/local/bin/python2.7

marks = {} #a dictionary, it's a list of (key : value) pairs (eg. "Maths" : 34)
subjects = ["Tamil","English","Maths","Science","Social"] # this is a list

#here we populate the dictionary with the marks for every subject
for subject in subjects:
   marks[subject] = input("Enter the " + subject + " marks: ")

#and finally the calculation of the total and the average
total = sum(marks.itervalues())
average = float(total) / len(marks)

print ("The total is " + str(total) + " and the average is " + str(average))

Here you can test the code and experiment with it.

How can I implement the Iterable interface?

First off:

public class ProfileCollection implements Iterable<Profile> {

Second:

return m_Profiles.get(m_ActiveProfile);

Add image to left of text via css

.create
{
background-image: url('somewhere.jpg');
background-repeat: no-repeat;
padding-left: 30px;  /* width of the image plus a little extra padding */
display: block;  /* may not need this, but I've found I do */
}

Play around with padding and possibly margin until you get your desired result. You can also play with the position of the background image (*nod to Tom Wright) with "background-position" or doing a completely definition of "background" (link to w3).

How can I read numeric strings in Excel cells as string (not numbers)?

cast to an int then do a .toString(). It is ugly but it works.

CSS Layout - Dynamic width DIV

This will do what you want. Fixed sides with 50px-width, and the content fills the remaining area.

<div style="width:100%;">
    <div style="width: 50px; float: left;">Left Side</div>
    <div style="width: 50px; float: right;">Right Side</div>
    <div style="margin-left: 50px; margin-right: 50px;">Content Goes Here</div>
</div>

Java Pass Method as Parameter

I'm not a java expert but I solve your problem like this:

@FunctionalInterface
public interface AutoCompleteCallable<T> {
  String call(T model) throws Exception;
}

I define the parameter in my special Interface

public <T> void initialize(List<T> entries, AutoCompleteCallable getSearchText) {.......
//call here
String value = getSearchText.call(item);
...
}

Finally, I implement getSearchText method while calling initialize method.

initialize(getMessageContactModelList(), new AutoCompleteCallable() {
          @Override
          public String call(Object model) throws Exception {
            return "custom string" + ((xxxModel)model.getTitle());
          }
        })

Best practice to call ConfigureAwait for all server-side code

Brief answer to your question: No. You shouldn't call ConfigureAwait(false) at the application level like that.

TL;DR version of the long answer: If you are writing a library where you don't know your consumer and don't need a synchronization context (which you shouldn't in a library I believe), you should always use ConfigureAwait(false). Otherwise, the consumers of your library may face deadlocks by consuming your asynchronous methods in a blocking fashion. This depends on the situation.

Here is a bit more detailed explanation on the importance of ConfigureAwait method (a quote from my blog post):

When you are awaiting on a method with await keyword, compiler generates bunch of code in behalf of you. One of the purposes of this action is to handle synchronization with the UI (or main) thread. The key component of this feature is the SynchronizationContext.Current which gets the synchronization context for the current thread. SynchronizationContext.Current is populated depending on the environment you are in. The GetAwaiter method of Task looks up for SynchronizationContext.Current. If current synchronization context is not null, the continuation that gets passed to that awaiter will get posted back to that synchronization context.

When consuming a method, which uses the new asynchronous language features, in a blocking fashion, you will end up with a deadlock if you have an available SynchronizationContext. When you are consuming such methods in a blocking fashion (waiting on the Task with Wait method or taking the result directly from the Result property of the Task), you will block the main thread at the same time. When eventually the Task completes inside that method in the threadpool, it is going to invoke the continuation to post back to the main thread because SynchronizationContext.Current is available and captured. But there is a problem here: the UI thread is blocked and you have a deadlock!

Also, here are two great articles for you which are exactly for your question:

Finally, there is a great short video from Lucian Wischik exactly on this topic: Async library methods should consider using Task.ConfigureAwait(false).

Hope this helps.

How to determine if a string is a number with C++?

After consulting the documentation a bit more, I came up with an answer that supports my needs, but probably won't be as helpful for others. Here it is (without the annoying return true and return false statements :-) )

bool isNumber(string line) 
{
    return (atoi(line.c_str())); 
}

XPath to select element based on childs child value

Almost there. In your predicate, you want a relative path, so change

./book[/author/name = 'John'] 

to either

./book[author/name = 'John'] 

or

./book[./author/name = 'John'] 

and you will match your element. Your current predicate goes back to the root of the document to look for an author.

Android device does not show up in adb list

just try adb kill-server then

adb devices

SQL Query - how do filter by null or not null

How about statusid = statusid. Null is never equal to null.

Android: show/hide status bar/power bar

Reference - https://developer.android.com/training/system-ui/immersive.html

// This snippet shows the system bars. It does this by removing all the flags
// except for the ones that make the content appear under the system bars.
private void showSystemUI() {
    mDecorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}

How to check if Location Services are enabled?

i use first code begin create method isLocationEnabled

 private LocationManager locationManager ;

protected boolean isLocationEnabled(){
        String le = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) getSystemService(le);
        if(!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
            return false;
        } else {
            return true;
        }
    }

and i check Condition if ture Open the map and false give intent ACTION_LOCATION_SOURCE_SETTINGS

    if (isLocationEnabled()) {
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        locationClient = getFusedLocationProviderClient(this);
        locationClient.getLastLocation()
                .addOnSuccessListener(new OnSuccessListener<Location>() {
                    @Override
                    public void onSuccess(Location location) {
                        // GPS location can be null if GPS is switched off
                        if (location != null) {
                            onLocationChanged(location);

                            Log.e("location", String.valueOf(location.getLongitude()));
                        }
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.e("MapDemoActivity", e.toString());
                        e.printStackTrace();
                    }
                });


        startLocationUpdates();

    }
    else {
        new AlertDialog.Builder(this)
                .setTitle("Please activate location")
                .setMessage("Click ok to goto settings else exit.")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(intent);
                    }
                })
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        System.exit(0);
                    }
                })
                .show();
    }

enter image description here

Set folder for classpath

Use the command as

java -classpath ".;C:\MyLibs\a\*;D:\MyLibs\b\*" <your-class-name>

The above command will set the mentioned paths to classpath only once for executing the class named TestClass.

If you want to execute more then one classes, then you can follow this

set classpath=".;C:\MyLibs\a\*;D:\MyLibs\b\*"

After this you can execute as many classes as you want just by simply typing

java <your-class-name>

The above command will work till you close the command prompt. But after closing the command prompt, if you will reopen the command prompt and try to execute some classes, then you have to again set the classpath with the help of any of the above two mentioned methods.(First method for executing one class and second one for executing more classes)

If you want to set the classpth only once so that it could work for everytime, then do as follows

1. Right click on "My Computer" icon
2. Go to the "properties"
3. Go to the "Advanced System Settings" or "Advance Settings"
4. Go to the "Environment Variable"
5. Create a new variable at the user variable by giving the information as below
    a.  Variable Name-     classpath
    b.  Variable Value-    .;C:\program files\jdk 1.6.0\bin;C:\MyLibs\a\';C:\MyLibs\b\*
6.Apply this and you are done.

Remember this will work every time. You don't need to explicitly set the classpath again and again.

NOTE: If you want to add some other libs after some day, then don't forget to add a semi-colon at the end of the "variable-value" of the "Environment Variable" and then type the path of your new libs after the semi-colon. Because semi-colon separates the paths of different directories.

Hope this will help you.

Call PHP function from jQuery?

Thanks all. I took bits of each of your solutions and made my own.

The final working solution is:

<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            url: '<?php bloginfo('template_url'); ?>/functions/twitter.php',
            data: "tweets=<?php echo $ct_tweets; ?>&account=<?php echo $ct_twitter; ?>",
            success: function(data) {
                $('#twitter-loader').remove();
                $('#twitter-container').html(data);
            }
        });
   });
</script>

how to fix the issue "Command /bin/sh failed with exit code 1" in iphone

I tried restarting Xcode (7) and nothing (the have you tried switching it off and on again of iOS development for me :-)). I then tried by restarting my box and that worked.

In my case the script was failing when copying a file from a location to another one. I think it could have been related to Finder screwing with writing rights over certain folders.

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

The above options works for Google big query file also. I exported a table data to goodle cloud storage and downloaded from there. While loading the same to sql server was facing this issue and could successfully load the file after specifying the row delimiter as

ROWTERMINATOR = '0x0a' 

Pay attention to header record as well and specify

FIRSTROW = 2

My final block for data file export from google bigquery looks like this.

BULK INSERT TABLENAME
        FROM 'C:\ETL\Data\BigQuery\In\FILENAME.csv'
        WITH
        (
         FIRSTROW = 2,
         FIELDTERMINATOR = ',',  --CSV field delimiter
         ROWTERMINATOR = '0x0a',--Files are generated with this row terminator in Google Bigquery
         TABLOCK
        )

How can I strip first and last double quotes?

If string is always as you show:

string[1:-1]

List of phone number country codes

Because nikolaDev's answer appeared to be useful, but incomplete and with some possible formatting errors, I put this list together using this Wikipedia page as the source for the data.

Wikipedia: https://en.wikipedia.org/wiki/List_of_mobile_telephone_prefixes_by_country

Full json file: List of mobile telephone prefixes by country (JSON formatted)

Extract a single (unsigned) integer from a string

If you just want to filter everything other than the numbers out, the easiest is to use filter_var:

$str = 'In My Cart : 11 items';
$int = (int) filter_var($str, FILTER_SANITIZE_NUMBER_INT);

What is the difference between a generative and a discriminative algorithm?

In practice, the models are used as follows.

In discriminative models, to predict the label y from the training example x, you must evaluate:

enter image description here

which merely chooses what is the most likely class y considering x. It's like we were trying to model the decision boundary between the classes. This behavior is very clear in neural networks, where the computed weights can be seen as a complexly shaped curve isolating the elements of a class in the space.

Now, using Bayes' rule, let's replace the enter image description here in the equation by enter image description here. Since you are just interested in the arg max, you can wipe out the denominator, that will be the same for every y. So, you are left with

enter image description here

which is the equation you use in generative models.

While in the first case you had the conditional probability distribution p(y|x), which modeled the boundary between classes, in the second you had the joint probability distribution p(x, y), since p(x | y) p(y) = p(x, y), which explicitly models the actual distribution of each class.

With the joint probability distribution function, given a y, you can calculate ("generate") its respective x. For this reason, they are called "generative" models.

Getting Integer value from a String using javascript/jquery

Is this logically possible??.. I guess the approach that you must take is this way :

Str1 ="test123.00"
Str2 ="yes50.00"

This will be impossible to tackle unless you have delimiter in between test and 123.00

eg: Str1 = "test-123.00" 

Then you can split this way

Str2 = Str1.split("-"); 

This will return you an array of words split with "-"

Then you can do parseFloat(Str2[1]) to get the floating value i.e 123.00

What is the difference between screenX/Y, clientX/Y and pageX/Y?

In JavaScript:

pageX, pageY, screenX, screenY, clientX, and clientY returns a number which indicates the number of physical “CSS pixels” a point is from the reference point. The event point is where the user clicked, the reference point is a point in the upper left. These properties return the horizontal and vertical distance from that reference point.

pageX and pageY:
Relative to the top left of the fully rendered content area in the browser. This reference point is below the URL bar and back button in the upper left. This point could be anywhere in the browser window and can actually change location if there are embedded scrollable pages embedded within pages and the user moves a scrollbar.

screenX and screenY:
Relative to the top left of the physical screen/monitor, this reference point only moves if you increase or decrease the number of monitors or the monitor resolution.

clientX and clientY:
Relative to the upper left edge of the content area (the viewport) of the browser window. This point does not move even if the user moves a scrollbar from within the browser.

For a visual on which browsers support which properties:

http://www.quirksmode.org/dom/w3c_cssom.html#t03

w3schools has an online Javascript interpreter and editor so you can see what each does

http://www.w3schools.com/jsref/tryit.asp?filename=try_dom_event_clientxy

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script>_x000D_
function show_coords(event)_x000D_
{_x000D_
  var x=event.clientX;_x000D_
  var y=event.clientY;_x000D_
  alert("X coords: " + x + ", Y coords: " + y);_x000D_
}_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<p onmousedown="show_coords(event)">Click this paragraph, _x000D_
and an alert box will alert the x and y coordinates _x000D_
of the mouse pointer.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

What is the meaning of git reset --hard origin/master?

git reset --hard origin/master

says: throw away all my staged and unstaged changes, forget everything on my current local branch and make it exactly the same as origin/master.

You probably wanted to ask this before you ran the command. The destructive nature is hinted at by using the same words as in "hard reset".

How to pass arguments to a Button command in Tkinter?

JasonPy - a few things...

if you stick a button in a loop it will be created over and over and over again... which is probably not what you want. (maybe it is)...

The reason it always gets the last index is lambda events run when you click them - not when the program starts. I'm not sure 100% what you are doing but maybe try storing the value when it's made then call it later with the lambda button.

eg: (don't use this code, just an example)

for entry in stuff_that_is_happening:
    value_store[entry] = stuff_that_is_happening

then you can say....

button... command: lambda: value_store[1]

hope this helps!

GitHub relative link in Markdown file

Update 30th, January 2013, 16 months later:

GitHub Blog Post Relative links in markup files:

Starting today, GitHub supports relative links in markup files.
Now you can link directly between different documentation files, whether you view the documentation on GitHub itself, or locally, using a different markup renderer.

You want examples of link definitions and how they work? Here's some Markdown for you.
Instead of an absolute link:

[a link](https://github.com/user/repo/blob/branch/other_file.md)

…you can use a relative link:

[a relative link](other_file.md)

and we'll make sure it gets linked to user/repo/blob/branch/other_file.md.

If you were using a workaround like [a workaround link](repo/blob/master/other_file.md), you'll have to update your documentation to use the new syntax.

This also means your documentation can now easily stand on its own, without always pointing to GitHub.


Update December 20th, 2011:

The GitHub markup issue 84 is currently closed by technoweenie, with the comment:

We tried adding a <base> tag for this, but it causes problems with other relative links on the site.


October 12th, 2011:

If you look at the raw source of the README.md of Markdown itself(!), relative paths don't seem to be supported.
You will find references like:

[r2h]: http://github.com/github/markup/tree/master/lib/github/commands/rest2html
[r2hc]: http://github.com/github/markup/tree/master/lib/github/markups.rb#L13

How can I make window.showmodaldialog work in chrome 37?

I wouldn't try to temporarily enable a deprecated feature. According to the MDN documentation for showModalDialog, there's already a polyfill available on Github.

I just used that to add windows.showModalDialog to a legacy enterprise application as a userscript, but you can obviously also add it in the head of the HTML if you have access to the source.

Initial size for the ArrayList

If you want to add the elements with index, you could instead use an array.

    String [] test = new String[length];
    test[0] = "add";

Set the location in iPhone Simulator

in iOS Simulator menu, go to Debug -> Location -> Custom Location. There you can set the latitude and longitude and test the app accordingly. This works with mapkit and also with CLLocationManager.

Alternative to header("Content-type: text/xml");

No. You can't send headers after they were sent. Try to use hooks in wordpress

How to get data from observable in angular2

this.myService.getConfig().subscribe(
  (res) => console.log(res),
  (err) => console.log(err),
  () => console.log('done!')
);

Maximum and Minimum values for ints

If you just need a number that's bigger than all others, you can use

float('inf')

in similar fashion, a number smaller than all others:

float('-inf')

This works in both python 2 and 3.

SSIS Text was truncated with status value 4

I've had this problem before, you can go to "advanced" tab of "choose a data source" page and click on "suggested types" button, and set the "number of rows" as much as you want. after that, the type and text qualified are set to the true values.

i applied the above solution and can convert my data to SQL.

Detect Safari using jQuery

Using a mix of feature detection and Useragent string:

    var is_opera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
    var is_Edge = navigator.userAgent.indexOf("Edge") > -1;
    var is_chrome = !!window.chrome && !is_opera && !is_Edge;
    var is_explorer= typeof document !== 'undefined' && !!document.documentMode && !is_Edge;
    var is_firefox = typeof window.InstallTrigger !== 'undefined';
    var is_safari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

Usage:
if (is_safari) alert('Safari');

Or for Safari only, use this :

if ( /^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {alert('Its Safari');}

How do I run a Python script on my web server?

Very simply, you can rename your Python script to "pythonscript.cgi". Post that in your cgi-bin directory, add the appropriate permissions and browse to it.

This is a great link you can start with.

Here's another good one.

Hope that helps.


EDIT (09/12/2015): The second link has long been removed. Replaced it with one that provides information referenced from the original.

A component is changing an uncontrolled input of type text to be controlled error in ReactJS

Changing value to defaultValue will resolve it.

Note:

defaultValue is only for the initial load. If you want to initialize the input then you should use defaultValue, but if you want to use state to change the value then you need to use value. Read this for more.

I used value={this.state.input ||""} in input to get rid of that warning.

Firebase FCM force onTokenRefresh() to be called

Try to implement FirebaseInstanceIdService to get refresh token.

Access the registration token:

You can access the token's value by extending FirebaseInstanceIdService. Make sure you have added the service to your manifest, then call getToken in the context of onTokenRefresh, and log the value as shown:

     @Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);

    // TODO: Implement this method to send any registration to your app's servers.
    sendRegistrationToServer(refreshedToken);
}

Full Code:

   import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;


public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";

    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. Note that this is called when the InstanceID token
     * is initially generated so this is where you would retrieve the token.
     */
    // [START refresh_token]
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // TODO: Implement this method to send any registration to your app's servers.
        sendRegistrationToServer(refreshedToken);
    }
    // [END refresh_token]

    /**
     * Persist token to third-party servers.
     *
     * Modify this method to associate the user's FCM InstanceID token with any server-side account
     * maintained by your application.
     *
     * @param token The new token.
     */
    private void sendRegistrationToServer(String token) {
        // Add custom implementation, as needed.
    }
}

See my answer here.

EDITS:

You shouldn't be starting a FirebaseInstanceIdService yourself.

It will Called when the system determines that the tokens need to be refreshed. The application should call getToken() and send the tokens to all application servers.

This will not be called very frequently, it is needed for key rotation and to handle Instance ID changes due to:

  • App deletes Instance ID
  • App is restored on a new device User
  • uninstalls/reinstall the app
  • User clears app data

The system will throttle the refresh event across all devices to avoid overloading application servers with token updates.

Try below way:

you'd call FirebaseInstanceID.getToken() anywhere off your main thread (whether it is a service, AsyncTask, etc), store the returned token locally and send it to your server. Then whenever onTokenRefresh() is called, you'd call FirebaseInstanceID.getToken() again, get a new token, and send that up to the server (probably including the old token as well so your server can remove it, replacing it with the new one).

Best way to track onchange as-you-type in input type="text"?

I think in 2018 it's better to use the input event.

-

As the WHATWG Spec describes (https://html.spec.whatwg.org/multipage/indices.html#event-input-input):

Fired at controls when the user changes the value (see also the change event)

-

Here's an example of how to use it:

<input type="text" oninput="handleValueChange()">

How to skip "are you sure Y/N" when deleting files in batch files

Use del /F /Q to force deletion of read-only files (/F) and directories and not ask to confirm (/Q) when deleting via wildcard.

Align nav-items to right side in bootstrap-4

In my case, I was looking for a solution that allows one of the navbar items to be right aligned. In order to do this, you must add style="width:100%;" to the <ul class="navbar-nav"> and then add the ml-auto class to your navbar item.

Disable eslint rules for folder

The previous answers were in the right track, but the complete answer for this is going to Disabling rules only for a group of files, there you'll find the documentation needed to disable/enable rules for certain folders (Because in some cases you don't want to ignore the whole thing, only disable certain rules). Example:

{
    "env": {},
    "extends": [],
    "parser": "",
    "plugins": [],
    "rules": {},
    "overrides": [
      {
        "files": ["test/*.spec.js"], // Or *.test.js
        "rules": {
          "require-jsdoc": "off"
        }
      }
    ],
    "settings": {}
}

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

You can use String.split(String regex):

String input = "aabbab";
String[] parts = input.split("(?!^)");

How do I disable log messages from the Requests library?

Setting the logger name as requests or requests.urllib3 did not work for me. I had to specify the exact logger name to change the logging level.

First See which loggers you have defined, to see which ones you want to remove

print(logging.Logger.manager.loggerDict)

And you will see something like this:

{...'urllib3.poolmanager': <logging.Logger object at 0x1070a6e10>, 'django.request': <logging.Logger object at 0x106d61290>, 'django.template': <logging.Logger object at 0x10630dcd0>, 'django.server': <logging.Logger object at 0x106dd6a50>, 'urllib3.connection': <logging.Logger object at 0x10710a350>,'urllib3.connectionpool': <logging.Logger object at 0x106e09690> ...}

Then configure the level for the exact logger:

   'loggers': {
    '': {
        'handlers': ['default'],
        'level': 'DEBUG',
        'propagate': True
    },
    'urllib3.connectionpool': {
        'handlers': ['default'],
        'level': 'WARNING',
        'propagate' : False
    },

Escape double quote character in XML

You can try using the a backslash followed by a "u" and then the unicode value for the character, for example the unicode value of the double quote is

" -> U+0022

Therefore if you were setting it as part of text in XML in android it would look something like this,

<TextView
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:text=" \u0022 Showing double quotes \u0022 "/>

This would produce a text in the TextView roughly something like this

" Showing double quotes "

You can find unicode of most symbols and characters here www.unicode-table.com/en

How to redirect to Index from another controller?

Complete answer (.Net Core 3.1)

Most answers here are correct but taken a bit out of context, so I will provide a full-fledged answer which works for Asp.Net Core 3.1. For completeness' sake:

[Route("health")]
[ApiController]
public class HealthController : Controller
{
    [HttpGet("some_health_url")]
    public ActionResult SomeHealthMethod() {}
}

[Route("v2")]
[ApiController]
public class V2Controller : Controller
{
    [HttpGet("some_url")]
    public ActionResult SomeV2Method()
    {
        return RedirectToAction("SomeHealthMethod", "Health"); // omit "Controller"
    }
}

If you try to use any of the url-specific strings, e.g. "some_health_url", it will not work!

Best practice for partial updates in a RESTful service

Regarding your Update.

The concept of CRUD I believe has caused some confusion regarding API design. CRUD is a general low level concept for basic operations to perform on data, and HTTP verbs are just request methods (created 21 years ago) that may or may not map to a CRUD operation. In fact, try to find the presence of the CRUD acronym in the HTTP 1.0/1.1 specification.

A very well explained guide that applies a pragmatic convention can be found in the Google cloud platform API documentation. It describes the concepts behind the creation of a resource based API, one that emphasizes a big amount of resources over operations, and includes the use cases that you are describing. Although is a just a convention design for their product, I think it makes a lot of sense.

The base concept here (and one that produces a lot of confusion) is the mapping between "methods" and HTTP verbs. One thing is to define what "operations" (methods) your API will do over which types of resources (for example, get a list of customers, or send an email), and another are the HTTP verbs. There must be a definition of both, the methods and the verbs that you plan to use and a mapping between them.

It also says that, when an operation does not map exactly with a standard method (List, Get, Create, Update, Delete in this case), one may use "Custom methods", like BatchGet, which retrieves several objects based on several object id input, or SendEmail.

How to fix Invalid AES key length?

Things to know in general:

  1. Key != Password
    • SecretKeySpec expects a key, not a password. See below
  2. It might be due to a policy restriction that prevents using 32 byte keys. See other answer on that

In your case

The problem is number 1: you are passing the password instead of the key.

AES only supports key sizes of 16, 24 or 32 bytes. You either need to provide exactly that amount or you derive the key from what you type in.

There are different ways to derive the key from a passphrase. Java provides a PBKDF2 implementation for such a purpose.

I used erickson's answer to paint a complete picture (only encryption, since the decryption is similar, but includes splitting the ciphertext):

SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);

KeySpec spec = new PBEKeySpec("password".toCharArray(), salt, 65536, 256); // AES-256
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] key = f.generateSecret(spec).getEncoded();
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");

byte[] ivBytes = new byte[16];
random.nextBytes(ivBytes);
IvParameterSpec iv = new IvParameterSpec(ivBytes);

Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, keySpec, iv);
byte[] encValue = c.doFinal(valueToEnc.getBytes());

byte[] finalCiphertext = new byte[encValue.length+2*16];
System.arraycopy(ivBytes, 0, finalCiphertext, 0, 16);
System.arraycopy(salt, 0, finalCiphertext, 16, 16);
System.arraycopy(encValue, 0, finalCiphertext, 32, encValue.length);

return finalCiphertext;

Other things to keep in mind:

  • Always use a fully qualified Cipher name. AES is not appropriate in such a case, because different JVMs/JCE providers may use different defaults for mode of operation and padding. Use AES/CBC/PKCS5Padding. Don't use ECB mode, because it is not semantically secure.
  • If you don't use ECB mode then you need to send the IV along with the ciphertext. This is usually done by prefixing the IV to the ciphertext byte array. The IV is automatically created for you and you can get it through cipherInstance.getIV().
  • Whenever you send something, you need to be sure that it wasn't altered along the way. It is hard to implement a encryption with MAC correctly. I recommend you to use an authenticated mode like CCM or GCM.

How to convert LINQ query result to List?

No need to do so much works..

var query = from c in obj.tbCourses
        where ...
        select c;

Then you can use:

List<course> list_course= query.ToList<course>();

It works fine for me.

How can you print a variable name in python?

For the revised question of how to read in configuration parameters, I'd strongly recommend saving yourself some time and effort and use ConfigParser or (my preferred tool) ConfigObj.

They can do everything you need, they're easy to use, and someone else has already worried about how to get them to work properly!

How to automatically start a service when running a docker container?

The following documentation from the Docker website shows how to implement an SSH service in a docker container. It should be easily adaptable for your service:

A variation on this question has also been asked here:

Install MySQL on Ubuntu without a password prompt

sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server

For specific versions, such as mysql-server-5.6, you'll need to specify the version in like this:

sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server-5.6

For mysql-community-server, the keys are slightly different:

sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/root-pass password your_password'
sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/re-root-pass password your_password'
sudo apt-get -y install mysql-community-server

Replace your_password with the desired root password. (it seems your_password can also be left blank for a blank root password.)

If your shell doesn't support here-strings (zsh, ksh93 and bash support them), use:

echo ... | sudo debconf-set-selections 

Why can't I push to this bare repository?

git push --all

is the canonical way to push everything to a new bare repository.

Another way to do the same thing is to create your new, non-bare repository and then make a bare clone with

git clone --bare

then use

git remote add origin <new-remote-repo>

in the original (non-bare) repository.

Git: Remove committed file after push

If you want to remove the file from the remote repo, first remove it from your project with --cache option and then push it:

git rm --cache /path/to/file
git commit -am "Remove file"
git push

(This works even if the file was added to the remote repo some commits ago) Remember to add to .gitignore the file extensions that you don't want to push.

How can I make setInterval also work when a tab is inactive in Chrome?

I think that a best understanding about this problem is in this example: http://jsfiddle.net/TAHDb/

I am doing a simple thing here:

Have a interval of 1 sec and each time hide the first span and move it to last, and show the 2nd span.

If you stay on page it works as it is supposed. But if you hide the tab for some seconds, when you get back you will see a weired thing.

Its like all events that didn't ucur during the time you were inactive now will ocur all in 1 time. so for some few seconds you will get like X events. they are so quick that its possible to see all 6 spans at once.

So it seams chrome only delays the events, so when you get back all events will occur but all at once...

A pratical application were this ocur iss for a simple slideshow. Imagine the numbers being Images, and if user stay with tab hidden when he came back he will see all imgs floating, Totally mesed.

To fix this use the stop(true,true) like pimvdb told. THis will clear the event queue.

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

If the 2nd company is happy for you to access their content in an IFrame then they need to take the restriction off - they can do this fairly easily in the IIS config.

There's nothing you can do to circumvent it and anything that does work should get patched quickly in a security hotfix. You can't tell the browser to just render the frame if the source content header says not allowed in frames. That would make it easier for session hijacking.

If the content is GET only you don't post data back then you could get the page server side and proxy the content without the header, but then any post back should get invalidated.

python date of the previous month

from datetime import date, timedelta

first_day_of_current_month = date.today().replace(day=1)
last_day_of_previous_month = first_day_of_current_month - timedelta(days=1)

print "Previous month:", last_day_of_previous_month.month

Or:

from datetime import date, timedelta

prev = date.today().replace(day=1) - timedelta(days=1)
print prev.month

How to upgrade PowerShell version from 2.0 to 3.0

The latest PowerShell version as of Aug 2016 is PowerShell 5.1. It's bundled with Windows Management Framework 5.1.

Here's the download page for PowerShell 5.1 for all versions of Windows, including Windows 7 x64 and x86.

It is worth noting that PowerShell 5.1 is the first version available in two editions of "Desktop" and "Core". Powershell Core 6.x is cross-platform, its latest version for Jan 2019 is 6.1.2. It also works on Windows 7 SP1.

SQL Server 2005 Using DateAdd to add a day to a date

The following query i have used in sql-server 2008, it may be help you.

For add day  DATEADD(DAY,20,GETDATE())

*20 is the day quantity

Change Volley timeout duration

Just to contribute with my approach. As already answered, RetryPolicy is the way to go. But if you need a policy different the than default for all your requests, you can set it in a base Request class, so you don't need to set the policy for all the instances of your requests.

Something like this:

public class BaseRequest<T> extends Request<T> {

    public BaseRequest(int method, String url, Response.ErrorListener listener) {
        super(method, url, listener);
        setRetryPolicy(getMyOwnDefaultRetryPolicy());
    }
}

In my case I have a GsonRequest which extends from this BaseRequest, so I don't run the risk of forgetting to set the policy for an specific request and you can still override it if some specific request requires to.

How to redirect to an external URL in Angular2?

In your component.ts

import { Component } from '@angular/core';

@Component({
  ...
})
export class AppComponent {
  ...
  goToSpecificUrl(url): void {
    window.location.href=url;
  }

  gotoGoogle() : void {
    window.location.href='https://www.google.com';
  }
}

In your component.html

<button type="button" (click)="goToSpecificUrl('http://stackoverflow.com/')">Open URL</button>
<button type="button" (click)="gotoGoogle()">Open Google</button>

<li *ngFor="item of itemList" (click)="goToSpecificUrl(item.link)"> // (click) don't enable pointer when we hover so we should enable it by using css like: **cursor: pointer;**

What GRANT USAGE ON SCHEMA exactly do?

Well, this is my final solution for a simple db, for Linux:

# Read this before!
#
# * roles in postgres are users, and can be used also as group of users
# * $ROLE_LOCAL will be the user that access the db for maintenance and
#   administration. $ROLE_REMOTE will be the user that access the db from the webapp
# * you have to change '$ROLE_LOCAL', '$ROLE_REMOTE' and '$DB'
#   strings with your desired names
# * it's preferable that $ROLE_LOCAL == $DB

#-------------------------------------------------------------------------------

//----------- SKIP THIS PART UNTIL POSTGRES JDBC ADDS SCRAM - START ----------//

cd /etc/postgresql/$VERSION/main
sudo cp pg_hba.conf pg_hba.conf_bak
sudo -e pg_hba.conf

# change all `md5` with `scram-sha-256`
# save and exit

//------------ SKIP THIS PART UNTIL POSTGRES JDBC ADDS SCRAM - END -----------//

sudo -u postgres psql

# in psql:
create role $ROLE_LOCAL login createdb;
\password $ROLE_LOCAL
create role $ROLE_REMOTE login;
\password $ROLE_REMOTE

create database $DB owner $ROLE_LOCAL encoding "utf8";
\connect $DB $ROLE_LOCAL

# Create all tables and objects, and after that:

\connect $DB postgres

revoke connect on database $DB from public;
revoke all on schema public from public;
revoke all on all tables in schema public from public;

grant connect on database $DB to $ROLE_LOCAL;
grant all on schema public to $ROLE_LOCAL;
grant all on all tables in schema public to $ROLE_LOCAL;
grant all on all sequences in schema public to $ROLE_LOCAL;
grant all on all functions in schema public to $ROLE_LOCAL;

grant connect on database $DB to $ROLE_REMOTE;
grant usage on schema public to $ROLE_REMOTE;
grant select, insert, update, delete on all tables in schema public to $ROLE_REMOTE;
grant usage, select on all sequences in schema public to $ROLE_REMOTE;
grant execute on all functions in schema public to $ROLE_REMOTE;

alter default privileges for role $ROLE_LOCAL in schema public
    grant all on tables to $ROLE_LOCAL;

alter default privileges for role $ROLE_LOCAL in schema public
    grant all on sequences to $ROLE_LOCAL;

alter default privileges for role $ROLE_LOCAL in schema public
    grant all on functions to $ROLE_LOCAL;

alter default privileges for role $ROLE_REMOTE in schema public
    grant select, insert, update, delete on tables to $ROLE_REMOTE;

alter default privileges for role $ROLE_REMOTE in schema public
    grant usage, select on sequences to $ROLE_REMOTE;

alter default privileges for role $ROLE_REMOTE in schema public
    grant execute on functions to $ROLE_REMOTE;

# CTRL+D

How to set Spinner Default by its Value instead of Position?

If the list you use for the spinner is an object then you can find its position like this

private int selectSpinnerValue( List<Object> ListSpinner,String myString) 
{
    int index = 0;
    for(int i = 0; i < ListSpinner.size(); i++){
      if(ListSpinner.get(i).getValueEquals().equals(myString)){
          index=i;
          break;
      }
    }
    return index;
}

using:

 int index=selectSpinnerValue(ListOfSpinner,StringEquals);
    spinner.setSelection(index,true);

How to include a font .ttf using CSS?

I know this is an old post but this solved my problem.

_x000D_
_x000D_
@font-face{_x000D_
  font-family: "Font Name";_x000D_
  src: url("../fonts/font-name.ttf") format("truetype");_x000D_
}
_x000D_
_x000D_
_x000D_

notice src:url("../fonts/font-name.ttf"); we use two periods to go back to the root directory and then into the fonts folder or wherever your file is located.

hope this helps someone down the line:) happy coding

How can I pass arguments to anonymous functions in JavaScript?

What you have done is created a new anonymous function that takes a single parameter which then gets assigned to the local variable myMessage inside the function. Since no arguments are actually passed, and arguments which aren't passed a value become null, your function just does alert(null).

Aborting a stash pop in Git

Some ideas:

  • Use git mergetool to split the merge files into original and new parts. Hopefully one of those is the file with your non-stash changes in it.

  • Apply the diff of the stash in reverse, to undo just those changes. You'll probably have to manually split out the files with the merge conflicts (which hopefully the above trick will work for).

I didn't test either of these, so I don't know for sure of they will work.

Setting background color for a JFrame

To set the background color for JFrame:

getContentPane().setBackground(Color.YELLOW);  //Whatever color

Getting last day of the month in a given string date

You can make use of the plusMonths and minusDays methods in Java 8:

// Parse your date into a LocalDate
LocalDate parsed = LocalDate.parse("1/13/2012", DateTimeFormatter.ofPattern("M/d/yyyy"));

// We only care about its year and month, set the date to first date of that month
LocalDate localDate = LocalDate.of(parsed.getYear(), parsed.getMonth(), 1);

// Add one month, subtract one day 
System.out.println(localDate.plusMonths(1).minusDays(1)); // 2012-01-31

How do I wrap text in a pre tag?

I suggest forget the pre and just put it in a textarea.

Your indenting will remain and your code wont get word-wrapped in the middle of a path or something.

Easier to select text range in a text area too if you want to copy to clipboard.

The following is a php excerpt so if your not in php then the way you pack the html special chars will vary.

<textarea style="font-family:monospace;" onfocus="copyClipboard(this);"><?=htmlspecialchars($codeBlock);?></textarea>

For info on how to copy text to the clipboard in js see: How do I copy to the clipboard in JavaScript? .

However...

I just inspected the stackoverflow code blocks and they wrap in a <code> tag wrapped in <pre> tag with css ...

code {
  background-color: #EEEEEE;
  font-family: Consolas,Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,serif;
}
pre {
  background-color: #EEEEEE;
  font-family: Consolas,Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,serif;
  margin-bottom: 10px;
  max-height: 600px;
  overflow: auto;
  padding: 5px;
  width: auto;
}

Also the content of the stackoverflow code blocks is syntax highlighted using (I think) http://code.google.com/p/google-code-prettify/ .

Its a nice setup but Im just going with textareas for now.

How can I recursively find all files in current and subfolders based on wildcard matching?

find <directory_path>  -type f -name "<wildcard-match>"

In the wildcard-match you can provide the string you wish to match e.g. *.c (for all c files)

Using HTTPS with REST in Java

When you say "is there an easier way to... trust this cert", that's exactly what you're doing by adding the cert to your Java trust store. And this is very, very easy to do, and there's nothing you need to do within your client app to get that trust store recognized or utilized.

On your client machine, find where your cacerts file is (that's your default Java trust store, and is, by default, located at <java-home>/lib/security/certs/cacerts.

Then, type the following:

keytool -import -alias <Name for the cert> -file <the .cer file> -keystore <path to cacerts>

That will import the cert into your trust store, and after this, your client app will be able to connect to your Grizzly HTTPS server without issue.

If you don't want to import the cert into your default trust store -- i.e., you just want it to be available to this one client app, but not to anything else you run on your JVM on that machine -- then you can create a new trust store just for your app. Instead of passing keytool the path to the existing, default cacerts file, pass keytool the path to your new trust store file:

keytool -import -alias <Name for the cert> -file <the .cer file> -keystore <path to new trust store>

You'll be asked to set and verify a new password for the trust store file. Then, when you start your client app, start it with the following parameters:

java -Djavax.net.ssl.trustStore=<path to new trust store> -Djavax.net.ssl.trustStorePassword=<trust store password>

Easy cheesy, really.

Iterating through a variable length array

Arrays have an implicit member variable holding the length:

for(int i=0; i<myArray.length; i++) {
    System.out.println(myArray[i]);
}

Alternatively if using >=java5, use a for each loop:

for(Object o : myArray) {
    System.out.println(o);
}

How to show imageView full screen on imageView click?

Actually there are three ways to enable full screnn, visit : https://developer.android.com/training/system-ui/immersive

but if you wanna get full screen when the activity is opened, just put this code in your_activity.java

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        hideSystemUI();
    }
}

private void hideSystemUI() {
    // Enables regular immersive mode.
    // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.
    // Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY
    View decorView = getWindow().getDecorView();
    decorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_IMMERSIVE
            // Set the content to appear under the system bars so that the
            // content doesn't resize when the system bars hide and show.
            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            // Hide the nav bar and status bar
            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_FULLSCREEN);
}

// Shows the system bars by removing all the flags
// except for the ones that make the content appear under the system bars.
private void showSystemUI() {
    View decorView = getWindow().getDecorView();
    decorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}

How to strip HTML tags from string in JavaScript?

Using the browser's parser is the probably the best bet in current browsers. The following will work, with the following caveats:

  • Your HTML is valid within a <div> element. HTML contained within <body> or <html> or <head> tags is not valid within a <div> and may therefore not be parsed correctly.
  • textContent (the DOM standard property) and innerText (non-standard) properties are not identical. For example, textContent will include text within a <script> element while innerText will not (in most browsers). This only affects IE <=8, which is the only major browser not to support textContent.
  • The HTML does not contain <script> elements.
  • The HTML is not null
  • The HTML comes from a trusted source. Using this with arbitrary HTML allows arbitrary untrusted JavaScript to be executed. This example is from a comment by Mike Samuel on the duplicate question: <img onerror='alert(\"could run arbitrary JS here\")' src=bogus>

Code:

var html = "<p>Some HTML</p>";
var div = document.createElement("div");
div.innerHTML = html;
var text = div.textContent || div.innerText || "";

Replace Div Content onclick

Here's an approach:

HTML:

<div id="1">
    My Content 1
</div>

<div id="2" style="display:none;">
    My Dynamic Content
</div>
<button id="btnClick">Click me!</button>

jQuery:

$('#btnClick').on('click',function(){
    if($('#1').css('display')!='none'){
    $('#2').html('Here is my dynamic content').show().siblings('div').hide();
    }else if($('#2').css('display')!='none'){
        $('#1').show().siblings('div').hide();
    }
});


JsFiddle:
http://jsfiddle.net/ha6qp7w4/
http://jsfiddle.net/ha6qp7w4/4 <--- Commented

Import error No module named skimage

You can use pip install scikit-image.

Also see the recommended procedure.

Syncing Android Studio project with Gradle files

EDIT

Starting with Android Studio 3.1, you should go to:

File -> Sync Project with Gradle Files


OLD

Clicking the button 'Sync Project With Gradle Files' should do the trick:

Tools -> Android -> Sync Project with Gradle Files

If that fails, try running 'Rebuild project':

Build -> Rebuild Project

Understanding the main method of python

In Python, execution does NOT have to begin at main. The first line of "executable code" is executed first.

def main():
    print("main code")

def meth1():
    print("meth1")

meth1()
if __name__ == "__main__":main() ## with if

Output -

meth1
main code

More on main() - http://ibiblio.org/g2swap/byteofpython/read/module-name.html

A module's __name__

Every module has a name and statements in a module can find out the name of its module. This is especially handy in one particular situation - As mentioned previously, when a module is imported for the first time, the main block in that module is run. What if we want to run the block only if the program was used by itself and not when it was imported from another module? This can be achieved using the name attribute of the module.

Using a module's __name__

#!/usr/bin/python
# Filename: using_name.py

if __name__ == '__main__':
    print 'This program is being run by itself'
else:
    print 'I am being imported from another module'

Output -

$ python using_name.py
This program is being run by itself
$ python
>>> import using_name
I am being imported from another module
>>>

How It Works -

Every Python module has it's __name__ defined and if this is __main__, it implies that the module is being run standalone by the user and we can do corresponding appropriate actions.

Facebook login "given URL not allowed by application configuration"

You can set up a developer application and set the url to localhost.com:port Make sure to map localhost.com to localhost on your hosts file

Works for me

How to detect Safari, Chrome, IE, Firefox and Opera browser?

const isChrome = /Chrome/.test(navigator.userAgent)
const isFirefox = /Firefox/.test(navigator.userAgent)

Aggregate a dataframe on a given column and display another column

Here is a solution using the plyr package.

The following line of code essentially tells ddply to first group your data by Group, and then within each group returns a subset where the Score equals the maximum score in that group.

library(plyr)
ddply(data, .(Group), function(x)x[x$Score==max(x$Score), ])

  Group Score Info
1     1     3    c
2     2     4    d

And, as @SachaEpskamp points out, this can be further simplified to:

ddply(df, .(Group), function(x)x[which.max(x$Score), ])

(which also has the advantage that which.max will return multiple max lines, if there are any).

installing JDK8 on Windows XP - advapi32.dll error

With JRE 8 on XP there is another way - to use MSI to deploy package.

  • Install JRE 8 x86 on a PC with supported OS
  • Copy c:\Users[USER]\AppData\LocalLow\Sun\Java\jre1.8.0\jre1.8.0.msi and Data1.cab to XP PC and run jre1.8.0.msi

or (silent way, usable in batch file etc..)

for %%I in ("*.msi") do if exist "%%I" msiexec.exe /i %%I /qn EULA=0 SKIPLICENSE=1 PROG=0 ENDDIALOG=0

Android: findviewbyid: finding view by id when view is not on the same layout invoked by setContentView

Thanks for commenting, I understand what you mean but I didn't want to check old values. I just wanted to get a pointer to that view.

Looking at someone else's code I have just found a workaround, you can access the root of a layout using LayoutInflater.

The code is the following, where this is an Activity:

final LayoutInflater factory = getLayoutInflater();

final View textEntryView = factory.inflate(R.layout.landmark_new_dialog, null);

landmarkEditNameView = (EditText) textEntryView.findViewById(R.id.landmark_name_dialog_edit);

You need to get the inflater for this context, access the root view through the inflate method and finally call findViewById on the root view of the layout.

Hope this is useful for someone! Bye

What is offsetHeight, clientHeight, scrollHeight?

Offset Means "the amount or distance by which something is out of line". Margin or Borders are something which makes the actual height or width of an HTML element "out of line". It will help you to remember that :

  • offsetHeight is a measurement in pixels of the element's CSS height, including border, padding and the element's horizontal scrollbar.

On the other hand, clientHeight is something which is you can say kind of the opposite of OffsetHeight. It doesn't include the border or margins. It does include the padding because it is something that resides inside of the HTML container, so it doesn't count as extra measurements like margin or border. So :

  • clientHeight property returns the viewable height of an element in pixels, including padding, but not the border, scrollbar or margin.

ScrollHeight is all the scrollable area, so your scroll will never run over your margin or border, so that's why scrollHeight doesn't include margin or borders but yeah padding does. So:

  • scrollHeight value is equal to the minimum height the element would require in order to fit all the content in the viewport without using a vertical scrollbar. The height is measured in the same way as clientHeight: it includes the element's padding, but not its border, margin or horizontal scrollbar.

What's the strangest corner case you've seen in C# or .NET?

I think the answer to the question is because .net uses string interning something that might cause equal strings to point to the same object (since a strings are mutable this is not a problem)

(I'm not talking about the overridden equality operator on the string class)

Permissions error when connecting to EC2 via SSH on Mac OSx

The key for me to be able to connect was to use the "ec2-user" user rather than root. I.e.:

ssh -i [full path to keypair file] ec2-user@[EC2 instance hostname or IP address]

TypeError: Invalid dimensions for image data when plotting array with imshow()

There is a (somewhat) related question on StackOverflow:

Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeezed or sliced into a 2D array.

More generally, the reason for the Exception

TypeError: Invalid dimensions for image data

is shown here: matplotlib.pyplot.imshow() needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!

You can easily check this with (these checks are done by imshow, this function is only meant to give a more specific message in case it's not a valid input):

from __future__ import print_function
import numpy as np

def valid_imshow_data(data):
    data = np.asarray(data)
    if data.ndim == 2:
        return True
    elif data.ndim == 3:
        if 3 <= data.shape[2] <= 4:
            return True
        else:
            print('The "data" has 3 dimensions but the last dimension '
                  'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
                  ''.format(data.shape[2]))
            return False
    else:
        print('To visualize an image the data must be 2 dimensional or '
              '3 dimensional, not "{}".'
              ''.format(data.ndim))
        return False

In your case:

>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False

The np.asarray is what is done internally by matplotlib.pyplot.imshow so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list) it's necessary.


In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()

import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0)  # or axis=1
plt.imshow(a)
plt.show()

enter image description here

or just use something that accepts 1D arrays like plot:

a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()

enter image description here

Primary key or Unique index?

There are some disadvantages of CLUSTERED INDEXES vs UNIQUE INDEXES.

As already stated, a CLUSTERED INDEX physically orders the data in the table.

This mean that when you have a lot if inserts or deletes on a table containing a clustered index, everytime (well, almost, depending on your fill factor) you change the data, the physical table needs to be updated to stay sorted.

In relative small tables, this is fine, but when getting to tables that have GB's worth of data, and insertrs/deletes affect the sorting, you will run into problems.

Catching nullpointerexception in Java

I think your problem is inside CheckCircular, in the while condition:

Assume you have 2 nodes, first N1 and N2 point to the same node, then N1 points to the second node (last) and N2 points to null (because it's N2.next.next). In the next loop, you try to call the 'next' method on N2, but N2 is null. There you have it, NullPointerException

How to make child divs always fit inside parent div?

If you want the child divs to fit the parent size, you should put a margin at least of the size of the child borders on the child divs (child.margin >= child.bordersize).

For this example, just remove the width:100%; and the height:100% in #one and remove the width:100% in #two. It should be something like this:

html, body {width:100%; height:100%; margin:0; padding:0;}    
.border {border:1px solid black;}   
.margin {margin:5px;}  
\#one {}   
\#two {height:50px;}    
\#three {width:100px; height:100%;}

ImportError: cannot import name

Instead of using local imports, you may import the entire module instead of the particular object. Then, in your app module, call mod_login.mod_login

app.py

from flask import Flask
import mod_login

# ...

do_stuff_with(mod_login.mod_login)

mod_login.py

from app import app

mod_login = something