Programs & Examples On #Osgeo

How to fix symbol lookup error: undefined symbol errors in a cluster environment

yum update

helped me out. After I had

wget: symbol lookup error: wget: undefined symbol: psl_latest

"if not exist" command in batch file

When testing for directories remember that every directory contains two special files.

One is called '.' and the other '..'

. is the directory's own name while .. is the name of it's parent directory.

To avoid trailing backslash problems just test to see if the directory knows it's own name.

eg:

if not exist %temp%\buffer\. mkdir %temp%\buffer

Getting SyntaxError for print with keyword argument end=' '

Compatible with both Python 2 & 3:

sys.stdout.write('mytext')

Compatible with only Python 2

print 'mytext',

Compatible with only Python 3

print('mytext', end='')

What is the maximum value for an int32?

max_signed_32_bit_num = 1 << 31 - 1;  // alternatively ~(1 << 31)

A compiler should optimize it anyway.

I prefer 1 << 31 - 1 over

0x7fffffff because you don't need count fs

unsigned( pow( 2, 31 ) ) - 1 because you don't need <math.h>

Make ABC Ordered List Items Have Bold Style

You could do something like this also:

<ol type="A" style="font-weight: bold;">

<li style="padding-bottom: 8px;">****</li>

It is simple code for the beginners.

This code is been tested in "Mozilla, chrome and edge..

Writing to CSV with Python adds blank lines

import csv

hello = [['Me','You'],['293', '219'],['13','15']]
length = len(hello[0])

with open('test1.csv', 'wb') as testfile:
    csv_writer = csv.writer(testfile)
    for y in range(length):
        csv_writer.writerow([x[y] for x in hello])

will produce an output like this

Me You
293 219
13 15

Hope this helps

Matplotlib transparent line plots

Plain and simple:

plt.plot(x, y, 'r-', alpha=0.7)

(I know I add nothing new, but the straightforward answer should be visible).

No value accessor for form control with name: 'recipient'

You should add the ngDefaultControl attribute to your input like this:

<md-input
    [(ngModel)]="recipient"
    name="recipient"
    placeholder="Name"
    class="col-sm-4"
    (blur)="addRecipient(recipient)"
    ngDefaultControl>
</md-input>

Taken from comments in this post:

angular2 rc.5 custom input, No value accessor for form control with unspecified name

Note: For later versions of @angular/material:

Nowadays you should instead write:

<md-input-container>
    <input
        mdInput
        [(ngModel)]="recipient"
        name="recipient"
        placeholder="Name"
        (blur)="addRecipient(recipient)">
</md-input-container>

See https://material.angular.io/components/input/overview

How to set ID using javascript?

Do you mean like this?

var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);

To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll() to accomplish this:

HTML

<div class="abc"></div>
<div class="abc"></div>

JS

var abcElements = document.querySelectorAll('.abc');

// Set their ids
for (var i = 0; i < abcElements.length; i++)
    abcElements[i].id = 'abc-' + i;

This will assign the ID 'abc-<index number>' to each element. So it would come out like this:

<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>

To create an element and assign an id we can use document.createElement() and then appendChild().

var div = document.createElement('div');
div.id = 'hello1';

var body = document.querySelector('body');
body.appendChild(div);

Update

You can set the id on your element like this if your script is in your HTML file.

<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">

<script type="text/javascript">
    var s = document.getElementsByClassName('assign-me')[0];
    s.id = btoa({{str(produit["avt"]["fto"])}});
</script>

Your requirements still aren't 100% clear though.

Set the location in iPhone Simulator

Where you want to set your location? you can use mapkit api to show u location's. see icodeblog.com for more detail on how to use mapkit. Also you can store your desired cordinates just create an object CLLocation2D *location; location.longitude=your desired longitude value; location.latitude=your desired latitude value;

How to install an npm package from GitHub directly?

UPDATE now you can do: npm install git://github.com/foo/bar.git
or in package.json:

"dependencies": {
  "bar": "git://github.com/foo/bar.git"
}

How to send push notification to web browser?

May I redefine you question as below

Can we have our own back-end to send push notification to Chrome, Firefox, Opera & Safari?

Yes. By today (2017/05), you can use same client and server side implementation to handle Chrome, Firefox and Opera (no Safari). Because they have implemented web push notifications in a same way. That is Push API protocol by W3C. But Safari have their own old architecture. So we have to maintain Safari separately.

Refer browser-push repo for guide lines to implement web push notification for your web-app with your own back-end. It explains with examples how you can add web push notification support for your web application without any third party services.

Spring Bean Scopes

Also websocket scope is added:

Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

As the per the content of the documentation, there is also thread scope, that is not registered by default.

Fatal Error :1:1: Content is not allowed in prolog

I'm turning my comment to an answer, so it can be accepted and this question no longer remains unanswered.

The most likely cause of this is a malformed response, which includes characters before the initial <?xml …>. So please have a look at the document as transferred over HTTP, and fix this on the server side.

filtering NSArray into a new NSArray in Objective-C

Another category method you could use:

- (NSArray *) filteredArrayUsingBlock:(BOOL (^)(id obj))block {
    NSIndexSet *const filteredIndexes = [self indexesOfObjectsPassingTest:^BOOL (id _Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
                                       return block(obj);
                                   }];

    return [self objectsAtIndexes:filteredIndexes];
}

CSS rotation cross browser with jquery.animate()

this is my solution:

var matrixRegex = /(?:matrix\(|\s*,\s*)([-+]?[0-9]*\.?[0-9]+(?:[e][-+]?[0-9]+)?)/gi;

var getMatches = function(string, regex) {
    regex || (regex = matrixRegex);
    var matches = [];
    var match;
    while (match = regex.exec(string)) {
        matches.push(match[1]);
    }
    return matches;
};

$.cssHooks['rotation'] = {
    get: function(elem) {
        var $elem = $(elem);
        var matrix = getMatches($elem.css('transform'));
        if (matrix.length != 6) {
            return 0;
        }
        return Math.atan2(parseFloat(matrix[1]), parseFloat(matrix[0])) * (180/Math.PI);
    }, 
    set: function(elem, val){
        var $elem = $(elem);
        var deg = parseFloat(val);
        if (!isNaN(deg)) {
            $elem.css({ transform: 'rotate(' + deg + 'deg)' });
        }
    }
};
$.cssNumber.rotation = true;
$.fx.step.rotation = function(fx) {
    $.cssHooks.rotation.set(fx.elem, fx.now + fx.unit);
};

then you can use it in the default animate fkt:

//rotate to 90 deg cw
$('selector').animate({ rotation: 90 });

//rotate to -90 deg ccw
$('selector').animate({ rotation: -90 });

//rotate 90 deg cw from current rotation
$('selector').animate({ rotation: '+=90' });

//rotate 90 deg ccw from current rotation
$('selector').animate({ rotation: '-=90' });

How do I check if a number is a palindrome?

I always use this python solution due to its compactness.

def isPalindrome(number):
    return int(str(number)[::-1])==number

How do I install a NuGet package .nupkg file locally?

Menu Tools ? Options ? Package Manager

Enter image description here

Give a name and folder location. Click OK. Drop your NuGet package files in that folder.

Go to your Project, right click and select "Manage NuGet Packages" and select your new package source.

Enter image description here

Here is the documentation.

Stop fixed position at footer

If your elements are glitching this is probably because when you change the position to relative the Y position of the footer increases which tries to send the item back to fixed which creates a loop. You can avoid this by setting two different cases when scrolling up and down. You don't even need to reference the fixed element, just the footer, and window size.

const footer = document.querySelector('footer');
document.addEventListener("scroll", checkScroll);

let prevY = window.scrollY + window.innerHeight;
function checkScroll() {
  let footerTop = getRectTop(footer) + window.scrollY;
  let windowBottomY = window.scrollY + window.innerHeight;
  if (prevY < windowBottomY) {  // Scroll Down
    if (windowBottomY > footerTop)
      setScrolledToFooter(true) // using React state. Change class or change style in JS.
  } else { // Scroll Up
    if (windowBottomY <= footerTop)
      setScrolledToFooter(false)
  }
  prevY = windowBottomY
};

function getRectTop(el) {
  var rect = el.getBoundingClientRect();
  return rect.top;
}

and the position of the element in the style object as follows:

position: scrolledToFooter ? 'relative' : 'fixed'

Environ Function code samples for VBA

Environ() gets you the value of any environment variable. These can be found by doing the following command in the Command Prompt:

set

If you wanted to get the username, you would do:

Environ("username")

If you wanted to get the fully qualified name, you would do:

Environ("userdomain") & "\" & Environ("username")

References

How can I switch language in google play?

Answer below the dotted line below is the original that's now outdated.

Here is the latest information ( Thank you @deadfish ):

add &hl=<language> like &hl=pl or &hl=en

example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl

All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en

......................................................................

To change the actual local market:

Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html

To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720

Class 'ViewController' has no initializers in swift

The error could be improved, but the problem with your first version is you have a member variable, delegate, that does not have a default value. All variables in Swift must always have a value. That means that you have to set it up in an initializer which you do not have or you could provide it a default value in-line.

When you make it optional, you allow it to be nil by default, removing the need to explicitly give it a value or initialize it.

Make an image width 100% of parent div, but not bigger than its own width

If the image is smaller than parent...

.img_100 {
  width: 100%;
}

scroll up and down a div on button click using jquery

To solve your other problem, where you need to set scrolled if the user scrolls manually, you'd have to attach a handler to the window scroll event. Generally this is a bad idea as the handler will fire a lot, a common technique is to set a timeout, like so:

var timer = 0;
$(window).scroll(function() {
  if (timer) {
    clearTimeout(timer);
  }
  timer = setTimeout(function() {
    scrolled = $(window).scrollTop();
  }, 250);
});

Declaring static constants in ES6 classes?

It is also possible to use Object.freeze on you class(es6)/constructor function(es5) object to make it immutable:

class MyConstants {}
MyConstants.staticValue = 3;
MyConstants.staticMethod = function() {
  return 4;
}
Object.freeze(MyConstants);
// after the freeze, any attempts of altering the MyConstants class will have no result
// (either trying to alter, add or delete a property)
MyConstants.staticValue === 3; // true
MyConstants.staticValue = 55; // will have no effect
MyConstants.staticValue === 3; // true

MyConstants.otherStaticValue = "other" // will have no effect
MyConstants.otherStaticValue === undefined // true

delete MyConstants.staticMethod // false
typeof(MyConstants.staticMethod) === "function" // true

Trying to alter the class will give you a soft-fail (won't throw any errors, it will simply have no effect).

Python Matplotlib Y-Axis ticks on Right Side of Plot

joaquin's answer works, but has the side effect of removing ticks from the left side of the axes. To fix this, follow up tick_right() with a call to set_ticks_position('both'). A revised example:

from matplotlib import pyplot as plt

f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
ax.yaxis.set_ticks_position('both')
plt.plot([2,3,4,5])
plt.show()

The result is a plot with ticks on both sides, but tick labels on the right.

enter image description here

Python 3: UnboundLocalError: local variable referenced before assignment

This is because, even though Var1 exists, you're also using an assignment statement on the name Var1 inside of the function (Var1 -= 1 at the bottom line). Naturally, this creates a variable inside the function's scope called Var1 (truthfully, a -= or += will only update (reassign) an existing variable, but for reasons unknown (likely consistency in this context), Python treats it as an assignment). The Python interpreter sees this at module load time and decides (correctly so) that the global scope's Var1 should not be used inside the local scope, which leads to a problem when you try to reference the variable before it is locally assigned.

Using global variables, outside of necessity, is usually frowned upon by Python developers, because it leads to confusing and problematic code. However, if you'd like to use them to accomplish what your code is implying, you can simply add:

global Var1, Var2

inside the top of your function. This will tell Python that you don't intend to define a Var1 or Var2 variable inside the function's local scope. The Python interpreter sees this at module load time and decides (correctly so) to look up any references to the aforementioned variables in the global scope.

Some Resources

  • the Python website has a great explanation for this common issue.
  • Python 3 offers a related nonlocal statement - check that out as well.

Regular Expression to select everything before and up to a particular text

((\n.*){0,3})(.*)\W*\.txt

This will select all the content before the particular word ".txt" including any context in different lines up to 3 lines

Placeholder in IE9

I know I'm late but I found a solution inserting in the head the tag:

_x000D_
_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge"/> <!--FIX jQuery INTERNET EXPLORER-->
_x000D_
_x000D_
_x000D_

What's the difference between a single precision and double precision floating point operation?

As to the question "Can the ps3 and xbxo 360 pull off double precision floating point operations or only single precision and in generel use is the double precision capabilities made use of (if they exist?)."

I believe that both platforms are incapable of double floating point. The original Cell processor only had 32 bit floats, same with the ATI hardware which the XBox 360 is based on (R600). The Cell got double floating point support later on, but I'm pretty sure the PS3 doesn't use that chippery.

TextView bold via xml file?

Example:

use: android:textStyle="bold"

 <TextView
    android:id="@+id/txtVelocidade"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/txtlatitude"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="34dp"
    android:textStyle="bold"
    android:text="Aguardando GPS"
    android:textAppearance="?android:attr/textAppearanceLarge" />

How to include SCSS file in HTML

You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...

For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.

Importing a GitHub project into Eclipse

It can be done in two ways:

1.Use clone Git

2.You can set it up manually by rearranging folders given in it. make a two separate folder 'src' and 'res' and place appropriate classes and xml file given by library. and then import project from eclipse and make it as library, that's it.

Unable to make the session state request to the session state server

I recently ran into this issue and none of the solutions proposed fixed it. The issue turned out to be an excessive use of datasets stored in the session. There was a flaw in the code that results in the session size to increase 10x.

There is an article on the msdn blog that also talks about this. http://blogs.msdn.com/b/johan/archive/2006/11/20/sessionstate-performance.aspx

I used a function to write custom trace messages to measure the size of the session data on the live site.

rbind error: "names do not match previous names"

easy enough to use the unname() function:

data.frame <- unname(data.frame)

Maximum length of the textual representation of an IPv6 address?

Answered my own question:

IPv6 addresses are normally written as eight groups of four hexadecimal digits, where each group is separated by a colon (:).

So that's 39 characters max.

Add ArrayList to another ArrayList in java

Wouldn't it just be a case of:

ArrayList<ArrayList<String>> outer = new ArrayList<ArrayList<String>>();
ArrayList<String> nodeList = new ArrayList<String>();

// Fill in nodeList here...

outer.add(nodeList);

Repeat as necesary.

This should return you a list in the format you specified.

How to open standard Google Map application from my application?

Using String format will help but you must be care full with the locale. In germany float will be separates with in comma instead an point.

Using String.format("geo:%f,%f",5.1,2.1); on locale english the result will be "geo:5.1,2.1" but with locale german you will get "geo:5,1,2,1"

You should use the English locale to prevent this behavior.

String uri = String.format(Locale.ENGLISH, "geo:%f,%f", latitude, longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);

To set an label to the geo point you can extend your geo uri by using:

!!! but be carefull with this the geo-uri is still under develoment http://tools.ietf.org/html/draft-mayrhofer-geo-uri-00

String uri = String.format(Locale.ENGLISH, "geo:%f,%f?z=%d&q=%f,%f (%s)", 
                           latitude, longitude, zoom, latitude, longitude, label);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);

Converting string to double in C#

private double ConvertToDouble(string s)
    {
        char systemSeparator = Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator[0];
        double result = 0;
        try
        {
            if (s != null)
                if (!s.Contains(","))
                    result = double.Parse(s, CultureInfo.InvariantCulture);
                else
                    result = Convert.ToDouble(s.Replace(".", systemSeparator.ToString()).Replace(",", systemSeparator.ToString()));
        }
        catch (Exception e)
        {
            try
            {
                result = Convert.ToDouble(s);
            }
            catch
            {
                try
                {
                    result = Convert.ToDouble(s.Replace(",", ";").Replace(".", ",").Replace(";", "."));
                }
                catch {
                    throw new Exception("Wrong string-to-double format");
                }
            }
        }
        return result;
    }

and successfully passed tests are:

        Debug.Assert(ConvertToDouble("1.000.007") == 1000007.00);
        Debug.Assert(ConvertToDouble("1.000.007,00") == 1000007.00);
        Debug.Assert(ConvertToDouble("1.000,07") == 1000.07);
        Debug.Assert(ConvertToDouble("1,000,007") == 1000007.00);
        Debug.Assert(ConvertToDouble("1,000,000.07") == 1000000.07);
        Debug.Assert(ConvertToDouble("1,007") == 1.007);
        Debug.Assert(ConvertToDouble("1.07") == 1.07);
        Debug.Assert(ConvertToDouble("1.007") == 1007.00);
        Debug.Assert(ConvertToDouble("1.000.007E-08") == 0.07);
        Debug.Assert(ConvertToDouble("1,000,007E-08") == 0.07);

Is there a better jQuery solution to this.form.submit();?

<form method="get">
   <p><label>Field Label
      <select onchange="this.form.submit();">
         <option value="blah">Blah</option>
            ....
     </select>
     </label>
   </p>
    **<!-- <input name="submit" type="submit" /> // name="submit_new_name" -->**
  </form>

<!-- 

   this.form.submit == this.form.elements['submit'];

-->

Counting number of characters in a file through shell script

To get exact character count of string, use printf, as opposed to echo, cat, or running wc -c directly on a file, because using echo, cat, etc will count a newline character, which will give you the amount of characters including the newline character. So a file with the text 'hello' will print 6 if you use echo etc, but if you use printf it will return the exact 5, because theres no newline element to count.

How to use printf for counting characters within strings:

$printf '6chars' | wc -m
6

To turn this into a script you can run on a text file to count characters, save the following in a file called print-character-amount.sh:

#!/bin/bash
characters=$(cat "$1")
printf "$characters" | wc -m

chmod +x on file print-character-amount.sh containing above text, place the file in your PATH (i.e. /usr/bin/ or any directory exported as PATH in your .bashrc file) then to run script on text file type:

print-character-amount.sh file-to-count-characters-of.txt

What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?

All the answers provide sufficient details to the question. However, let me add something more.

Why are we using these Interfaces:

  • They allow Spring to find your repository interfaces and create proxy objects for them.
  • It provides you with methods that allow you to perform some common operations (you can also define your custom method as well). I love this feature because creating a method (and defining query and prepared statements and then execute the query with connection object) to do a simple operation really sucks !

Which interface does what:

  • CrudRepository: provides CRUD functions
  • PagingAndSortingRepository: provides methods to do pagination and sort records
  • JpaRepository: provides JPA related methods such as flushing the persistence context and delete records in a batch

When to use which interface:

According to http://jtuts.com/2014/08/26/difference-between-crudrepository-and-jparepository-in-spring-data-jpa/

Generally the best idea is to use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.

The JpaRepository should be avoided if possible, because it ties you repositories to the JPA persistence technology, and in most cases you probably wouldn’t even use the extra methods provided by it.

how to access downloads folder in android?

You should add next permission:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

And then here is usages in code:

val externalFilesDir = context.getExternalFilesDir(DIRECTORY_DOWNLOADS)

Java, How do I get current index/key in "for each" loop

In Java, you can't, as foreach was meant to hide the iterator. You must do the normal For loop in order to get the current iteration.

How to check if an option is selected?

If you only want to check if an option is selected, then you do not need to iterate through all options. Just do

if($('#mySelectBox').val()){
    // do something
} else {
    // do something else
}

Note: If you have an option with value=0 that you want to be selectable, you need to change the if-condition to $('#mySelectBox').val() != null

I cannot access tomcat admin console?

For me, it just was that service console restart didn't work after tomcat ran into an error. Only stop/start brought it back.

ssh script returns 255 error

This error will also occur when using pdsh to hosts which are not contained in your "known_hosts" file.

I was able to correct this by SSH'ing into each host manually and accepting the question "Do you want to add this to known hosts".

How do I call a non-static method from a static method in C#?

Perhaps what you are looking for is the Singleton pattern?

public class Singleton
{
    private Singleton() {}

    public void DoWork()
    { 
        // do something
    }

    // You can call this static method which calls the singleton instance method.
    public static void DoSomeWork()
    { 
        Instance.DoWork();
    }

    public static Singleton Instance
    {
        get { return instance; } 
    }

    private static Singleton instance = new Singleton();
}

You still have to create an instance of the class but you ensure there is only one instance.

Laravel Eloquent update just if changes have been made

You're already doing it!

save() will check if something in the model has changed. If it hasn't it won't run a db query.

Here's the relevant part of code in Illuminate\Database\Eloquent\Model@performUpdate:

protected function performUpdate(Builder $query, array $options = [])
{
    $dirty = $this->getDirty();

    if (count($dirty) > 0)
    {
        // runs update query
    }

    return true;
}

The getDirty() method simply compares the current attributes with a copy saved in original when the model is created. This is done in the syncOriginal() method:

public function __construct(array $attributes = array())
{
    $this->bootIfNotBooted();

    $this->syncOriginal();

    $this->fill($attributes);
}

public function syncOriginal()
{
    $this->original = $this->attributes;

    return $this;
}

If you want to check if the model is dirty just call isDirty():

if($product->isDirty()){
    // changes have been made
}

Or if you want to check a certain attribute:

if($product->isDirty('price')){
    // price has changed
}

PHP json_decode() returns NULL with valid JSON?

For me, I had to turn off the error_reporting, to get json_decode() working correctly. It sounds weird, but true in my case. Because there is some notice printed between the JSON string that I am trying to decode.

How do I set the time zone of MySQL?

You can do this easily by changing the OS time zone if match your scenario.

In Ubuntu, to list time zones, run this command

sudo timedatectl list-timezones

To change the OS time zone, run this command with your timezone

timedatectl set-timezone America/New_York

Check The OS time zone, run

date

Then restart the MySQL

sudo service mysql restart

To Chek time zone in MySQL, login and run

SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP);

How do I set up Vim autoindentation properly for editing Python files?

I use this on my macbook:

" configure expanding of tabs for various file types
au BufRead,BufNewFile *.py set expandtab
au BufRead,BufNewFile *.c set expandtab
au BufRead,BufNewFile *.h set expandtab
au BufRead,BufNewFile Makefile* set noexpandtab

" --------------------------------------------------------------------------------
" configure editor with tabs and nice stuff...
" --------------------------------------------------------------------------------
set expandtab           " enter spaces when tab is pressed
set textwidth=120       " break lines when line length increases
set tabstop=4           " use 4 spaces to represent tab
set softtabstop=4
set shiftwidth=4        " number of spaces to use for auto indent
set autoindent          " copy indent from current line when starting a new line

" make backspaces more powerfull
set backspace=indent,eol,start

set ruler                           " show line and column number
syntax on               " syntax highlighting
set showcmd             " show (partial) command in status line

(edited to only show stuff related to indent / tabs)

Syntax for a single-line Bash infinite while loop

For simple process watching use watch instead

How to find a value in an array and remove it by using PHP array functions?

To search an element in an array, you can use array_search function and to remove an element from an array you can use unset function. Ex:

<?php
$hackers = array ('Alan Kay', 'Peter Norvig', 'Linus Trovalds', 'Larry Page');

print_r($hackers);

// Search
$pos = array_search('Linus Trovalds', $hackers);

echo 'Linus Trovalds found at: ' . $pos;

// Remove from array
unset($hackers[$pos]);

print_r($hackers);

You can refer: https://www.php.net/manual/en/ref.array.php for more array related functions.

Convert any object to a byte[]

checkout this article :http://www.morgantechspace.com/2013/08/convert-object-to-byte-array-and-vice.html

Use the below code

// Convert an object to a byte array
private byte[] ObjectToByteArray(Object obj)
{
    if(obj == null)
        return null;

    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms = new MemoryStream();
    bf.Serialize(ms, obj);

    return ms.ToArray();
}

// Convert a byte array to an Object
private Object ByteArrayToObject(byte[] arrBytes)
{
    MemoryStream memStream = new MemoryStream();
    BinaryFormatter binForm = new BinaryFormatter();
    memStream.Write(arrBytes, 0, arrBytes.Length);
    memStream.Seek(0, SeekOrigin.Begin);
    Object obj = (Object) binForm.Deserialize(memStream);

    return obj;
}

Can I use a min-height for table, tr or td?

The solution without div is used a pseudo element like ::after into first td in row with min-height. Save your HTML clean.

table tr td:first-child::after {
   content: "";
   display: inline-block;
   vertical-align: top;
   min-height: 60px;
}

Setting environment variables in Linux using Bash

export VAR=value will set VAR to value. Enclose it in single quotes if you want spaces, like export VAR='my val'. If you want the variable to be interpolated, use double quotes, like export VAR="$MY_OTHER_VAR".

In a Dockerfile, How to update PATH environment variable?

You can use Environment Replacement in your Dockerfile as follows:

ENV PATH="/opt/gtk/bin:${PATH}"

Cannot create a connection to data source Error (rsErrorOpeningConnection) in SSRS

First thing I would try is to get a bit more information on the error - that's a pretty generic message.

You could enable remote errors as per the error message and replicate the error for more information:

Enable remote errors.

Or check the Report Server error logs to see what error was logged.

%programfiles%\Microsoft SQL Server\<SQL Server Instance>\Reporting Services\LogFiles\

The next step would be to connect as the Data Source user to the database, run any code/stored procedures that the report is using with the same parameters you're using when running the report, and see if any errors occur.

How exactly to use Notification.Builder

in addition to the selected answer here is some sample code for the NotificationCompat.Builder class from Source Tricks :

// Add app running notification  

    private void addNotification() {



    NotificationCompat.Builder builder =  
            new NotificationCompat.Builder(this)  
            .setSmallIcon(R.drawable.ic_launcher)  
            .setContentTitle("Notifications Example")  
            .setContentText("This is a test notification");  

    Intent notificationIntent = new Intent(this, MainActivity.class);  
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,   
            PendingIntent.FLAG_UPDATE_CURRENT);  
    builder.setContentIntent(contentIntent);  

    // Add as notification  
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
    manager.notify(FM_NOTIFICATION_ID, builder.build());  
}  

// Remove notification  
private void removeNotification() {  
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
    manager.cancel(FM_NOTIFICATION_ID);  
}  

Store output of sed into a variable

Use command substitution like this:

line=$(sed -n '2p' myfile)
echo "$line"

Also note that there is no space around the = sign.

How to change the value of ${user} variable used in Eclipse templates

edit the file /etc/eclipse.ini, so as to contain entry as;

-Duser.name=myname

Restart the "eclipse" and now, on creation of any new file, with wizard (c/c++/java), it will use "myname" in place of ${user}.

Python subprocess/Popen with a modified environment

The env parameter accepts a dictionary. You can simply take os.environ, add a key (your desired variable) (to a copy of the dict if you must) to that and use it as a parameter to Popen.

Delete all items from a c++ std::vector

If you keep pointers in container and don't want to bother with manually destroying of them, then use boost shared_ptr. Here is sample for std::vector, but you can use it for any other STL container (set, map, queue, ...)

#include <iostream>
#include <vector>
#include <boost/shared_ptr.hpp>

struct foo
{
    foo( const int i_x ) : d_x( i_x )
    {
        std::cout << "foo::foo " << d_x << std::endl;
    }

    ~foo()
    {
        std::cout << "foo::~foo " << d_x << std::endl;
    }

    int d_x;
};

typedef boost::shared_ptr< foo > smart_foo_t;

int main()
{
    std::vector< smart_foo_t > foos;
    for ( int i = 0; i < 10; ++i )
    {
        smart_foo_t f( new foo( i ) );
        foos.push_back( f );
    }

    foos.clear();

    return 0;
}

How do I use modulus for float/double?

Unlike C, Java allows using the % for both integer and floating point and (unlike C89 and C++) it is well-defined for all inputs (including negatives):

From JLS §15.17.3:

The result of a floating-point remainder operation is determined by the rules of IEEE arithmetic:

  • If either operand is NaN, the result is NaN.
  • If the result is not NaN, the sign of the result equals the sign of the dividend.
  • If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.
  • If the dividend is finite and the divisor is an infinity, the result equals the dividend.
  • If the dividend is a zero and the divisor is finite, the result equals the dividend.
  • In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the floating-point remainder r from the division of a dividend n by a divisor d is defined by the mathematical relation r=n-(d·q) where q is an integer that is negative only if n/d is negative and positive only if n/d is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of n and d.

So for your example, 0.5/0.3 = 1.6... . q has the same sign (positive) as 0.5 (the dividend), and the magnitude is 1 (integer with largest magnitude not exceeding magnitude of 1.6...), and r = 0.5 - (0.3 * 1) = 0.2

Ruby's File.open gives "No such file or directory - text.txt (Errno::ENOENT)" error

Please use chomp() or chomp() with STDIN

i.e. test1.rb

print 'Enter File name: '

fname = STDIN.gets.chomp()  # or fname = gets.chomp()


fname_read = File.open(fname)

puts fname_read.read()

MS Access DB Engine (32-bit) with Office 64-bit

I had a more specifc error message that stated to remove 'Office 16 Click-to-Run Extensibility Component'

I fixed it by following the steps in https://www.tecklyfe.com/fix-for-microsoft-office-setup-error-please-uninstall-all-32-bit-office-programs-office-15-click-to-run-extensibility-component/

  • Go to Start > Run (or Winkey + R)
  • Type “installer” (that opens the %windir%installer folder), make sure all files are visible in Windows (Folder Settings)
  • Add the column “Subject” (and make it at least 400 pixels wide) – Right click on the column headers, click More, then find Subject
  • Sort on the Subject column and scroll down until you locate the name mentioned in your error screen (“Office 16 Click-to-Run Extensibility Component”)
  • Right click the MSI and choose uninstall

Settings to Windows Firewall to allow Docker for Windows to share drive

  1. open the windows defender firewall settings on windows.
  2. open the link "windows defender firewall properties"
  3. select private profile tab
  4. press customize button of "protected network connections"
  5. uncheck "vEthernet (DockerNAT)"
  6. go back to dockers desktop and apply the share

Step by step instructions image

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

With Java 8 you can use the new removeIf method. Applied to your example:

Collection<Integer> coll = new ArrayList<>();
//populate

coll.removeIf(i -> i == 5);

Setting transparent images background in IrfanView

You were on the right track. IrfanView sets the background for transparency the same as the viewing color around the image.

You just need to re-open the image with IrfanView after changing the view color to white.

To change the viewing color in Irfanview go to:

Options > Properties/Settings > Viewing > Main window color

Change directory command in Docker?

To change into another directory use WORKDIR. All the RUN, CMD and ENTRYPOINT commands after WORKDIR will be executed from that directory.

RUN git clone XYZ 
WORKDIR "/XYZ"
RUN make

How to set css style to asp.net button?

nobody wants to go to the clutter of using a class, try this:

<asp:button Style="margin:0px" runat="server" />

Intellisense won't suggest it but it will get the job done without throwing errors, warnings, or messages. Don't forget the capital S in Style

TCPDF ERROR: Some data has already been output, can't send PDF file

I had this but unlike the OP I couldn't see any output before the TCPDF error message.

Turns out there was a UTF8 BOM (byte-order-mark) at the very start of my script, before the <?php tag so before I had any chance to call ob_start(). And there was also a UTF8 BOM before the TCPDF error message.

How does Tomcat find the HOME PAGE of my Web App?

I already had index.html in the WebContent folder but it was not showing up , finally i added the following piece of code in my projects web.xml and it started showing up

  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping> 

What is the 'override' keyword in C++ used for?

And as an addendum to all answers, FYI: override is not a keyword, but a special kind of identifier! It has meaning only in the context of declaring/defining virtual functions, in other contexts it's just an ordinary identifier. For details read 2.11.2 of The Standard.

#include <iostream>

struct base
{
    virtual void foo() = 0;
};

struct derived : base
{
    virtual void foo() override
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }
};

int main()
{
    base* override = new derived();
    override->foo();
    return 0;
}

Output:

zaufi@gentop /work/tests $ g++ -std=c++11 -o override-test override-test.cc
zaufi@gentop /work/tests $ ./override-test
virtual void derived::foo()

How to iterate object keys using *ngFor

i would do this:

<li *ngFor="let item of data" (click)='onclick(item)'>{{item.picture.url}}</li>

How do I parse a URL query parameters, in Javascript?

You could get a JavaScript object containing the parameters with something like this:

var regex = /[?&]([^=#]+)=([^&#]*)/g,
    url = window.location.href,
    params = {},
    match;
while(match = regex.exec(url)) {
    params[match[1]] = match[2];
}

The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by = characters, and pairs themselves separated by & characters (or an = character for the first one). For your example, the above would result in:

{v: "123", p: "hello"}

Here's a working example.

Append values to a set in Python

The way I like to do this is to convert both the original set and the values I'd like to add into lists, add them, and then convert them back into a set, like this:

setMenu = {"Eggs", "Bacon"}
print(setMenu)
> {'Bacon', 'Eggs'}
setMenu = set(list(setMenu) + list({"Spam"}))
print(setMenu)
> {'Bacon', 'Spam', 'Eggs'}
setAdditions = {"Lobster", "Sausage"}
setMenu = set(list(setMenu) + list(setAdditions))
print(setMenu)
> {'Lobster', 'Spam', 'Eggs', 'Sausage', 'Bacon'}

This way I can also easily add multiple sets using the same logic, which gets me an TypeError: unhashable type: 'set' if I try doing it with the .update() method.

Is there a way to disable initial sorting for jquery DataTables?

As per latest api docs:

$(document).ready(function() {
    $('#example').dataTable({
        "order": []
    });
});

More Info

How to read file with async/await properly?

Since Node v11.0.0 fs promises are available natively without promisify:

const fs = require('fs').promises;
async function loadMonoCounter() {
    const data = await fs.readFile("monolitic.txt", "binary");
    return new Buffer(data);
}

Class constants in python

class Animal:
    HUGE = "Huge"
    BIG = "Big"

class Horse:
    def printSize(self):
        print(Animal.HUGE)

Can you animate a height change on a UITableViewCell when selected?

Instead of beginUpdates()/endUpdates(), the recommended call is now:

tableView.performBatchUpdates(nil, completion: nil)

Apple says, regarding beginUpdates/endUpdates: "Use the performBatchUpdates(_:completion:) method instead of this one whenever possible."

See: https://developer.apple.com/documentation/uikit/uitableview/1614908-beginupdates

Duplicate keys in .NET dictionaries?

When using the List<KeyValuePair<string, object>> option, you could use LINQ to do the search:

List<KeyValuePair<string, object>> myList = new List<KeyValuePair<string, object>>();
//fill it here
var q = from a in myList Where a.Key.Equals("somevalue") Select a.Value
if(q.Count() > 0){ //you've got your value }

Rename package in Android Studio

ctrl + Shift + R has always worked for me. Simply replace all and choose All Files.

Difference between numpy.array shape (R, 1) and (R,)

The data structure of shape (n,) is called a rank 1 array. It doesn't behave consistently as a row vector or a column vector which makes some of its operations and effects non intuitive. If you take the transpose of this (n,) data structure, it'll look exactly same and the dot product will give you a number and not a matrix. The vectors of shape (n,1) or (1,n) row or column vectors are much more intuitive and consistent.

How to send a JSON object over Request with Android?

HttpPost is deprecated by Android Api Level 22. So, Use HttpUrlConnection for further.

public static String makeRequest(String uri, String json) {
    HttpURLConnection urlConnection;
    String url;
    String data = json;
    String result = null;
    try {
        //Connect 
        urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestMethod("POST");
        urlConnection.connect();

        //Write
        OutputStream outputStream = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(data);
        writer.close();
        outputStream.close();

        //Read
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));

        String line = null;
        StringBuilder sb = new StringBuilder();

        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }

        bufferedReader.close();
        result = sb.toString();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

Extracting Ajax return data in jQuery

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

SSLHandshakeException: No subject alternative names present

Thanks,Bruno for giving me heads up on Common Name and Subject Alternative Name. As we figured out certificate was generated with CN with DNS name of network and asked for regeneration of new certificate with Subject Alternative Name entry i.e. san=ip:10.0.0.1. which is the actual solution.

But, we managed to find out a workaround with which we can able to run on development phase. Just add a static block in the class from which we are making ssl connection.

static {
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
        {
            public boolean verify(String hostname, SSLSession session)
            {
                // ip address of the service URL(like.23.28.244.244)
                if (hostname.equals("23.28.244.244"))
                    return true;
                return false;
            }
        });
}

If you happen to be using Java 8, there is a much slicker way of achieving the same result:

static {
    HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> hostname.equals("127.0.0.1"));
}

Error in your SQL syntax; check the manual that corresponds to your MySQL server version

Use ` backticks for MYSQL reserved words...

table name "table" is reserved word for MYSQL...

so your query should be as follows...

$sql="INSERT INTO `table` (`username`, `password`)
VALUES
('$_POST[username]','$_POST[password]')";

Split a large pandas dataframe

You can use groupby, assuming you have an integer enumerated index:

import math
df = pd.DataFrame(dict(sample=np.arange(99)))
rows_per_subframe = math.ceil(len(df) / 4.)

subframes = [i[1] for i in df.groupby(np.arange(len(df))//rows_per_subframe)]

Note: groupby returns a tuple in which the 2nd element is the dataframe, thus the slightly complicated extraction.

>>> len(subframes), [len(i) for i in subframes]
(4, [25, 25, 25, 24])

Remove blank values from array using C#

If you are using .NET 3.5+ you could use LINQ (Language INtegrated Query).

test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();

MySQL wait_timeout Variable - GLOBAL vs SESSION

Your session status are set once you start a session, and by default, take the current GLOBAL value.

If you disconnected after you did SET @@GLOBAL.wait_timeout=300, then subsequently reconnected, you'd see

SHOW SESSION VARIABLES LIKE "%wait%";

Result: 300

Similarly, at any time, if you did

mysql> SET session wait_timeout=300;

You'd get

mysql> SHOW SESSION VARIABLES LIKE 'wait_timeout';

+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| wait_timeout  | 300   |
+---------------+-------+

Which characters are valid/invalid in a JSON key name?

It is worth mentioning that while starting the keys with numbers is valid, it could cause some unintended issues.

Example:

var testObject = {
    "1tile": "test value"
};
console.log(testObject.1tile); // fails, invalid syntax
console.log(testObject["1tile"]; // workaround

Object of class stdClass could not be converted to string - laravel

This is easy all you need to do is something like this Grab your contents like this

  $result->get(filed1) = 'some modification';
  $result->get(filed2) = 'some modification2';

Convert int (number) to string with leading zeros? (4 digits)

Use the formatting options available to you, use the Decimal format string. It is far more flexible and requires little to no maintenance compared to direct string manipulation.

To get the string representation using at least 4 digits:

int length = 4;
int number = 50;
string asString = number.ToString("D" + length); //"0050"

jQuery access input hidden value

Most universal way is to take value by name. It doesn't matter if its input or select form element type.

var value = $('[name="foo"]');

Deploying Java webapp to Tomcat 8 running in Docker container

There's a oneliner for this one.

You can simply run,

docker run -v /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war:/usr/local/tomcat/webapps/myapp.war -it -p 8080:8080 tomcat

This will copy the war file to webapps directory and get your app running in no time.

How to install bcmath module?

I found that the repo that had the package was not enabled. On OEL7,

$ vi /etc/yum.repos.d/ULN-Base.repo
Set enabled to 1 for ol7_optional_latest

$ yum install php-bcmath

and that worked...

I used the following command to find where the package was

$ yum --noplugins --showduplicates --enablerepo \* --disablerepo \*-source --disablerepo C5.\*,c5-media,\*debug\*,\*-source list \*bcmath

How to store custom objects in NSUserDefaults

I create a library RMMapper (https://github.com/roomorama/RMMapper) to help save custom object into NSUserDefaults easier and more convenient, because implementing encodeWithCoder and initWithCoder is super boring!

To mark a class as archivable, just use: #import "NSObject+RMArchivable.h"

To save a custom object into NSUserDefaults:

#import "NSUserDefaults+RMSaveCustomObject.h"
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults rm_setCustomObject:user forKey:@"SAVED_DATA"];

To get custom obj from NSUserDefaults:

user = [defaults rm_customObjectForKey:@"SAVED_DATA"]; 

How can I generate a 6 digit unique number?

There are some great answers, but many use functions that are flagged as not cryptographically secure. If you want a random 6 digit number that is cryptographically secure you can use something like this:

$key = random_int(0, 9999999);
$key = str_pad($key, 6, 0, STR_PAD_LEFT);
return $key;

This will also include numbers like 000182 and others that would otherwise be excluded from the other examples.

How to remove all CSS classes using jQuery/JavaScript?

$('#elm').removeAttr('class');

no longer class attr wil be present in "elm".

PSQLException: current transaction is aborted, commands ignored until end of transaction block

Try this COMMIT;

I run that in pgadmin4. It may help. It has to do with the previous command stopping prematurely

Exporting PDF with jspdf not rendering CSS

Slight change to @rejesh-yadav wonderful answer.

html2canvas now returns a promise.

html2canvas(document.body).then(function (canvas) {
    var img = canvas.toDataURL("image/png");
    var doc = new jsPDF();
    doc.addImage(img, 'JPEG', 10, 10);
    doc.save('test.pdf');        
});

Hope this helps some!

android get all contacts

Get all contacts in less than a second and without any load in your activity. Follow my steps works like a charm.

ArrayList<Contact> contactList = new ArrayList<>();

private static final String[] PROJECTION = new String[]{
        ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
        ContactsContract.Contacts.DISPLAY_NAME,
        ContactsContract.CommonDataKinds.Phone.NUMBER
};

private void getContactList() {
    ContentResolver cr = getContentResolver();

    Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
    if (cursor != null) {
        HashSet<String> mobileNoSet = new HashSet<String>();
        try {
            final int nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            final int numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

            String name, number;
            while (cursor.moveToNext()) {
                name = cursor.getString(nameIndex);
                number = cursor.getString(numberIndex);
                number = number.replace(" ", "");
                if (!mobileNoSet.contains(number)) {
                    contactList.add(new Contact(name, number));
                    mobileNoSet.add(number);
                    Log.d("hvy", "onCreaterrView  Phone Number: name = " + name
                            + " No = " + number);
                }
            }
        } finally {
            cursor.close();
        }
    }
}

Contacts


public class Contact {
public String name;
public String phoneNumber;

public Contact() {
}

public Contact(String name, String phoneNumber ) {
    this.name = name;
    this.phoneNumber = phoneNumber;
}

public String getName() {
    return name;
}

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

public String getPhoneNumber() {
    return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
    this.phoneNumber = phoneNumber;
}

}

Benefits

  • less than a second
  • without load
  • ascending order
  • without duplicate contacts

How to parse a CSV in a Bash script?

index=1
value=2
awk -F"," -v i=$index -v v=$value '$(i)==v' file

Best equivalent VisualStudio IDE for Mac to program .NET/C#

The question is quite old so I feel like I need to give a more up to date response to this question.

Based on MonoDevelop, the best IDE for building C# applications on the Mac, for pretty much any platform is http://xamarin.com/

How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

date -j -f "%Y-%m-%d" "2010-10-02" "+%s"

Curl: Fix CURL (51) SSL error: no alternative certificate subject name matches

It usually happens when the certificate does not match with the host name.

The solution would be to contact the host and ask it to fix its certificate.
Otherwise you can turn off cURL's verification of the certificate, use the -k (or --insecure) option.
Please note that as the option said, it is insecure. You shouldn't use this option because it allows man-in-the-middle attacks and defeats the purpose of HTTPS.

More can be found in here: http://curl.haxx.se/docs/sslcerts.html

selenium - chromedriver executable needs to be in PATH

Another way is download and unzip chromedriver and put 'chromedriver.exe' in C:\Python27\Scripts and then you need not to provide the path of driver, just

driver= webdriver.Chrome()

will work

Can testify that this also works for Python3.7.

How do I install boto?

  1. install pip: https://pip.pypa.io/en/latest/installing.html

  2. insatll boto: https://github.com/boto/boto

    $ git clone git://github.com/boto/boto.git
    $ cd boto
    $ python setup.py install

How do I pause my shell script for a second before continuing?

You can make it wait using $RANDOM, a default random number generator. In the below I am using 240 seconds. Hope that helps @

> WAIT_FOR_SECONDS=`/usr/bin/expr $RANDOM % 240` /bin/sleep
> $WAIT_FOR_SECONDS

how to download file in react js

You can use FileSaver.js to achieve this goal:

const saveFile = () => {
fileSaver.saveAs(
  process.env.REACT_APP_CLIENT_URL + "/resources/cv.pdf",
  "MyCV.pdf"
);

};

<button className="cv" onClick={saveFile}>
    Download File
</button>

Angular directives - when and how to use compile, controller, pre-link and post-link

Pre-link function

Each directive's pre-link function is called whenever a new related element is instantiated.

As seen previously in the compilation order section, pre-link functions are called parent-then-child, whereas post-link functions are called child-then-parent.

The pre-link function is rarely used, but can be useful in special scenarios; for example, when a child controller registers itself with the parent controller, but the registration has to be in a parent-then-child fashion (ngModelController does things this way).

Do not:

  • Inspect child elements (they may not be rendered yet, bound to scope, etc.).

How do I fix MSB3073 error in my post-build event?

In my case, the dll I was creating by building the project was still in use in the background. I killed the application and then xcopy worked fine as expected.

git ignore vim temporary files

Here is the actual VIM code that generates the swap file extensions:

/* 
 * Change the ".swp" extension to find another file that can be used. 
 * First decrement the last char: ".swo", ".swn", etc. 
 * If that still isn't enough decrement the last but one char: ".svz" 
 * Can happen when editing many "No Name" buffers. 
 */
if (fname[n - 1] == 'a')        /* ".s?a" */
{   
    if (fname[n - 2] == 'a')    /* ".saa": tried enough, give up */
    {   
        EMSG(_("E326: Too many swap files found"));
        vim_free(fname);
        fname = NULL;
        break;  
    }
    --fname[n - 2];             /* ".svz", ".suz", etc. */
    fname[n - 1] = 'z' + 1;
}
--fname[n - 1];                 /* ".swo", ".swn", etc. */

This will generate swap files of the format:

[._]*.s[a-v][a-z]
[._]*.sw[a-p]
[._]s[a-v][a-z]
[._]sw[a-p]

Which is pretty much what is included in github's own gitignore file for VIM.

As others have correctly noted, this .gitignore will also ignore .svg image files and .swf adobe flash files.

Server configuration by allow_url_fopen=0 in

If you do not have the ability to modify your php.ini file, use cURL: PHP Curl And Cookies

Here is an example function I created:

function get_web_page( $url, $cookiesIn = '' ){
        $options = array(
            CURLOPT_RETURNTRANSFER => true,     // return web page
            CURLOPT_HEADER         => true,     //return headers in addition to content
            CURLOPT_FOLLOWLOCATION => true,     // follow redirects
            CURLOPT_ENCODING       => "",       // handle all encodings
            CURLOPT_AUTOREFERER    => true,     // set referer on redirect
            CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
            CURLOPT_TIMEOUT        => 120,      // timeout on response
            CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
            CURLINFO_HEADER_OUT    => true,
            CURLOPT_SSL_VERIFYPEER => true,     // Validate SSL Cert
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
            CURLOPT_COOKIE         => $cookiesIn
        );

        $ch      = curl_init( $url );
        curl_setopt_array( $ch, $options );
        $rough_content = curl_exec( $ch );
        $err     = curl_errno( $ch );
        $errmsg  = curl_error( $ch );
        $header  = curl_getinfo( $ch );
        curl_close( $ch );

        $header_content = substr($rough_content, 0, $header['header_size']);
        $body_content = trim(str_replace($header_content, '', $rough_content));
        $pattern = "#Set-Cookie:\\s+(?<cookie>[^=]+=[^;]+)#m"; 
        preg_match_all($pattern, $header_content, $matches); 
        $cookiesOut = implode("; ", $matches['cookie']);

        $header['errno']   = $err;
        $header['errmsg']  = $errmsg;
        $header['headers']  = $header_content;
        $header['content'] = $body_content;
        $header['cookies'] = $cookiesOut;
    return $header;
}

NOTE: In revisiting this function I noticed that I had disabled SSL checks in this code. That is generally a BAD thing even though in my particular case the site I was using it on was local and was safe. As a result I've modified this code to have SSL checks on by default. If for some reason you need to change that, you can simply update the value for CURLOPT_SSL_VERIFYPEER, but I wanted the code to be secure by default if someone uses this.

downcast and upcast

Answer 1 : Yes it called upcasting but the way you do it is not modern way. Upcasting can be performed implicitly you don't need any conversion. So just writing Employee emp = mgr; is enough for upcasting.

Answer 2 : If you create object of Manager class we can say that manager is an employee. Because class Manager : Employee depicts Is-A relationship between Employee Class and Manager Class. So we can say that every manager is an employee.

But if we create object of Employee class we can not say that this employee is manager because class Employee is a class which is not inheriting any other class. So you can not directly downcast that Employee Class object to Manager Class object.

So answer is, if you want to downcast from Employee Class object to Manager Class object, first you must have object of Manager Class first then you can upcast it and then you can downcast it.

Dynamically add properties to a existing object

If you can't use the dynamic type with ExpandoObject, then you could use a 'Property Bag' mechanism, where, using a dictionary (or some other key / value collection type) you store string key's that name the properties and values of the required type.

See here for an example implementation.

Check if returned value is not null and if so assign it, in one line, with one method call

Using Java 1.8 you can use Optional

public class Main  {

    public static void main(String[] args) {

        //example call, the methods are just dumb templates, note they are static
        FutureMeal meal = getChicken().orElse(getFreeRangeChicken());

        //another possible way to call this having static methods is
        FutureMeal meal = getChicken().orElseGet(Main::getFreeRangeChicken); //method reference

        //or if you would use a Instance of Main and call getChicken and getFreeRangeChicken
        // as nonstatic methods (assume static would be replaced with public for this)
        Main m = new Main();
        FutureMeal meal = m.getChicken().orElseGet(m::getFreeRangeChicken); //method reference

        //or
        FutureMeal meal = m.getChicken().orElse(m.getFreeRangeChicken()); //method call


    }

    static Optional<FutureMeal> getChicken(){

        //instead of returning null, you would return Optional.empty() 
        //here I just return it to demonstrate
        return Optional.empty();

        //if you would return a valid object the following comment would be the code
        //FutureMeal ret = new FutureMeal(); //your return object
        //return Optional.of(ret);            

    }

    static FutureMeal getFreeRangeChicken(){
        return new FutureMeal();
    }
}

You would implement a logic for getChicken to return either Optional.empty() instead of null, or Optional.of(myReturnObject), where myReturnObject is your chicken.

Then you can call getChicken() and if it would return Optional.empty() the orElse(fallback) would give you whatever the fallback would be, in your case the second method.

yii2 hidden input value

<?= $form->field($model, 'hidden_Input')->hiddenInput(['id'=>'hidden_Input','class'=>'form-control','value'=>$token_name])->label(false)?>

or

<input type="hidden" name="test" value="1" />

Use This.

How do I divide so I get a decimal value?

I mean it's quite simple. Set it as a double. So lets say

double answer = 3.0/2.0;
System.out.print(answer);

Get counts of all tables in a schema

This can be done with a single statement and some XML magic:

select table_name, 
       to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from '||owner||'.'||table_name)),'/ROWSET/ROW/C')) as count
from all_tables
where owner = 'FOOBAR'

Can we pass parameters to a view in SQL?

I realized this task for my needs as follows

set nocount on;

  declare @ToDate date = dateadd(month,datediff(month,0,getdate())-1,0)

declare @year varchar(4)  = year(@ToDate)
declare @month varchar(2) = month(@ToDate)

declare @sql nvarchar(max)
set @sql = N'
    create or alter view dbo.wTempLogs
    as
    select * from dbo.y2019
    where
        year(LogDate) = ''_year_''
        and 
        month(LogDate) = ''_month_''    '

select @sql = replace(replace(@sql,'_year_',@year),'_month_',@month)

execute sp_executesql @sql

declare @errmsg nvarchar(max)
    set @errMsg = @sql
    raiserror (@errMsg, 0,1) with nowait

SQL Server 2008 can't login with newly created user

If you haven't restarted your SQL database Server after you make login changes, then make sure you do that. Start->Programs->Microsoft SQL Server -> Configuration tools -> SQL Server configuration manager -> Restart Server.

It looks like you only added the user to the server. You need to add them to the database too. Either open the database/Security/User/Add New User or open the server/Security/Logins/Properties/User Mapping.

Select DataFrame rows between two dates

Inspired by unutbu

print(df.dtypes)                                 #Make sure the format is 'object'. Rerunning this after index will not show values.
columnName = 'YourColumnName'
df[columnName+'index'] = df[columnName]          #Create a new column for index
df.set_index(columnName+'index', inplace=True)   #To build index on the timestamp/dates
df.loc['2020-09-03 01:00':'2020-09-06']          #Select range from the index. This is your new Dataframe.

VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range

You may receive a "Run-time error 1004" error message when you programmatically set a large array string to a range in Excel 2003

In Office Excel 2003, when you programmatically set a range value with an array containing a large string, you may receive an error message similar to the following:

Run-time error '1004'. Application-defined or operation-defined error.

This issue may occur if one or more of the cells in an array (range of cells) contain a character string that is set to contain more than 911 characters.

To work around this issue, edit the script so that no cells in the array contain a character string that holds more than 911 characters.

For example, the following line of code from the example code block below defines a character string that contains 912 characters:

Sub XLTest()
Dim aValues(4)

  aValues(0) = "Test1"
  aValues(1) = "Test2"
  aValues(2) = "Test3"

  MsgBox "First the Good range set."
  aValues(3) = String(911, 65)

  Range("A1:D1").Value = aValues

  MsgBox "Now the bad range set."
  aValues(3) = String(912, 66)
  Range("A2:D2").Value = aValues

End Sub

Other versions of Excel or free alternatives like Calc should work as well.

Put search icon near textbox using bootstrap

Adding a class with a width of 90% to your input element and adding the following input-icon class to your span would achieve what you want I think.

.input { width: 90%; }
.input-icon {
    display: inline-block;
    height: 22px;
    width: 22px;
    line-height: 22px;
    text-align: center;
    color: #000;
    font-size: 12px;
    font-weight: bold;
    margin-left: 4px;
}

EDIT Per dan's suggestion, it would not be wise to use .input as the class name, some more specific would be advised. I was simply using .input as a generic placeholder for your css

How to sort an STL vector?

Overload less than operator, then sort. This is an example I found off the web...

class MyData
{
public:
  int m_iData;
  string m_strSomeOtherData;
  bool operator<(const MyData &rhs) const { return m_iData < rhs.m_iData; }
};

std::sort(myvector.begin(), myvector.end());

Source: here

How to dynamically change the color of the selected menu item of a web page?

There is a pure CSS solution I'm currently using.

Add a body ID (or class) identifying your pages and your menu items, then use something like:

HTML:

<html>
    <body id="body_questions">
        <ul class="menu">
            <li id="questions">Question</li>
            <li id="tags">Tags</li>
            <li id="users">Users</li>
        </ul>
        ...
    </body>
</html>

CSS:

.menu li:hover,
#body_questions #questions,
#body_tags      #tags,
#body_users     #users {
    background-color: #f90;
}

How to change screen resolution of Raspberry Pi

After uncommenting disable_overscan=1 follow my lead. In the link, http://elinux.org/RPiconfig when you search for Video options, you'll also get hdmi_group and hdmi_mode. For, hdmi_group choose 1 if you're using you TV as an video output or choose 2 for monitors. Then in hdmi_mode, you can select the resolution you want from the list. I chose :- hdmi_group=2 hdmi_mode=23 And it worked.enter image description here

Why do Twitter Bootstrap tables always have 100% width?

<table style="width: auto;" ... works fine. Tested in Chrome 38 , IE 11 and Firefox 34.

jsfiddle : http://jsfiddle.net/rpaul/taqodr8o/

How to install Selenium WebDriver on Mac OS

Mac already has Python and a package manager called easy_install, so open Terminal and type

sudo easy_install selenium

Paste a multi-line Java String in Eclipse

See: Multiple-line-syntax

It also support variables in multiline string, for example:

String name="zzg";
String lines = ""/**~!{
    SELECT * 
        FROM user
        WHERE name="$name"
}*/;
System.out.println(lines);

Output:

SELECT * 
    FROM user
    WHERE name="zzg"

Google Maps: Set Center, Set Center Point and Set more points

Try using this code for v3:

gMap = new google.maps.Map(document.getElementById('map')); 
gMap.setZoom(13);      // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);

Javascript How to define multiple variables on a single line?

Specifically to what the OP has asked, if you want to initialize N variables with the same value (e.g. 0), you can use array destructuring and Array.fill to assign to the variables an array of N 0s:

_x000D_
_x000D_
let [a, b, c, d] = Array(4).fill(0);_x000D_
_x000D_
console.log(a, b, c, d);
_x000D_
_x000D_
_x000D_

Apply global variable to Vuejs

If the global variable should not be written to by anything, including Vuejs, you can use Object.freeze to freeze your object. Adding it to Vue's viewmodel won't unfreeze it. Another option is to provide Vuejs with a frozen copy of the object, if the object is intended to be written globally but just not by Vue: var frozenCopy = Object.freeze(Object.assign({}, globalObject))

Verify External Script Is Loaded

If the script creates any variables or functions in the global space you can check for their existance:

External JS (in global scope) --

var myCustomFlag = true;

And to check if this has run:

if (typeof window.myCustomFlag == 'undefined') {
    //the flag was not found, so the code has not run
    $.getScript('<external JS>');
}

Update

You can check for the existence of the <script> tag in question by selecting all of the <script> elements and checking their src attributes:

//get the number of `<script>` elements that have the correct `src` attribute
var len = $('script').filter(function () {
    return ($(this).attr('src') == '<external JS>');
}).length;

//if there are no scripts that match, the load it
if (len === 0) {
    $.getScript('<external JS>');
}

Or you can just bake this .filter() functionality right into the selector:

var len = $('script[src="<external JS>"]').length;

Sending and receiving data over a network using TcpClient

First, I recommend that you use WCF, .NET Remoting, or some other higher-level communication abstraction. The learning curve for "simple" sockets is nearly as high as WCF, because there are so many non-obvious pitfalls when using TCP/IP directly.

If you decide to continue down the TCP/IP path, then review my .NET TCP/IP FAQ, particularly the sections on message framing and application protocol specifications.

Also, use asynchronous socket APIs. The synchronous APIs do not scale and in some error situations may cause deadlocks. The synchronous APIs make for pretty little example code, but real-world production-quality code uses the asynchronous APIs.

Authenticate Jenkins CI for Github private repository

Another option is to use GitHub personal access tokens:

  • Go to https://github.com/settings/tokens/new
  • Add repo scope
  • In Jenkins, add a GitHub source
  • Use Repository HTTPS URL
  • Add the HTTPS URL of the git repo (not the SSH one, eg. https://github.com/my-username/my-project.git)
  • Add credential
    • Kind: Username with Password
    • Username: the GitHub username
    • Password: the personal access token you created on GitHub
    • ID: something like github-token-for-my-username

I tested this on Jenkins ver. 2.222.1 and Jenkins GitHub plugin 1.29.5 with a private GitHub repo.

What is the SQL command to return the field names of a table?

MySQL 3 and 4 (and 5):

desc tablename

which is an alias for

show fields from tablename

SQL Server (from 2000) and MySQL 5:

select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS 
where TABLE_NAME = 'tablename'

Completing the answer: like people below have said, in SQL Server you can also use the stored procedure sp_help

exec sp_help 'tablename'

Javascript: best Singleton pattern

(1) UPDATE 2019: ES7 Version

class Singleton {
    static instance;

    constructor() {
        if (instance) {
            return instance;
        }

        this.instance = this;
    }

    foo() {
        // ...
    }
}

console.log(new Singleton() === new Singleton());

(2) ES6 Version

class Singleton {
    constructor() {
        const instance = this.constructor.instance;
        if (instance) {
            return instance;
        }

        this.constructor.instance = this;
    }

    foo() {
        // ...
    }
}

console.log(new Singleton() === new Singleton());

Best solution found: http://code.google.com/p/jslibs/wiki/JavascriptTips#Singleton_pattern

function MySingletonClass () {

  if (arguments.callee._singletonInstance) {
    return arguments.callee._singletonInstance;
  }

  arguments.callee._singletonInstance = this;

  this.Foo = function () {
    // ...
  };
}

var a = new MySingletonClass();
var b = MySingletonClass();
console.log( a === b ); // prints: true

For those who want the strict version:

(function (global) {
  "use strict";
  var MySingletonClass = function () {

    if (MySingletonClass.prototype._singletonInstance) {
      return MySingletonClass.prototype._singletonInstance;
    }

    MySingletonClass.prototype._singletonInstance = this;

    this.Foo = function() {
      // ...
    };
  };

var a = new MySingletonClass();
var b = MySingletonClass();
global.result = a === b;

} (window));

console.log(result);

How do I make a simple crawler in PHP?

I created a small class to grab data from the provided url, then extract html elements of your choice. The class makes use of CURL and DOMDocument.

php class:

class crawler {


   public static $timeout = 2;
   public static $agent   = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)';


   public static function http_request($url) {
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL,            $url);
      curl_setopt($ch, CURLOPT_USERAGENT,      self::$agent);
      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::$timeout);
      curl_setopt($ch, CURLOPT_TIMEOUT,        self::$timeout);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      $response = curl_exec($ch);
      curl_close($ch);
      return $response;
   }


   public static function strip_whitespace($data) {
      $data = preg_replace('/\s+/', ' ', $data);
      return trim($data);
   }


   public static function extract_elements($tag, $data) {
      $response = array();
      $dom      = new DOMDocument;
      @$dom->loadHTML($data);
      foreach ( $dom->getElementsByTagName($tag) as $index => $element ) {
         $response[$index]['text'] = self::strip_whitespace($element->nodeValue);
         foreach ( $element->attributes as $attribute ) {
            $response[$index]['attributes'][strtolower($attribute->nodeName)] = self::strip_whitespace($attribute->nodeValue);
         }
      }
      return $response;
   }


}

example usage:

$data  = crawler::http_request('https://stackoverflow.com/questions/2313107/how-do-i-make-a-simple-crawler-in-php');
$links = crawler::extract_elements('a', $data);
if ( count($links) > 0 ) {
   file_put_contents('links.json', json_encode($links, JSON_PRETTY_PRINT));
}

example response:

[
    {
        "text": "Stack Overflow",
        "attributes": {
            "href": "https:\/\/stackoverflow.com",
            "class": "-logo js-gps-track",
            "data-gps-track": "top_nav.click({is_current:false, location:2, destination:8})"
        }
    },
    {
        "text": "Questions",
        "attributes": {
            "id": "nav-questions",
            "href": "\/questions",
            "class": "-link js-gps-track",
            "data-gps-track": "top_nav.click({is_current:true, location:2, destination:1})"
        }
    },
    {
        "text": "Developer Jobs",
        "attributes": {
            "id": "nav-jobs",
            "href": "\/jobs?med=site-ui&ref=jobs-tab",
            "class": "-link js-gps-track",
            "data-gps-track": "top_nav.click({is_current:false, location:2, destination:6})"
        }
    }
]

Avoid trailing zeroes in printf()

This can't be done with the normal printf format specifiers. The closest you could get would be:

printf("%.6g", 359.013); // 359.013
printf("%.6g", 359.01);  // 359.01

but the ".6" is the total numeric width so

printf("%.6g", 3.01357); // 3.01357

breaks it.

What you can do is to sprintf("%.20g") the number to a string buffer then manipulate the string to only have N characters past the decimal point.

Assuming your number is in the variable num, the following function will remove all but the first N decimals, then strip off the trailing zeros (and decimal point if they were all zeros).

char str[50];
sprintf (str,"%.20g",num);  // Make the number.
morphNumericString (str, 3);
:    :
void morphNumericString (char *s, int n) {
    char *p;
    int count;

    p = strchr (s,'.');         // Find decimal point, if any.
    if (p != NULL) {
        count = n;              // Adjust for more or less decimals.
        while (count >= 0) {    // Maximum decimals allowed.
             count--;
             if (*p == '\0')    // If there's less than desired.
                 break;
             p++;               // Next character.
        }

        *p-- = '\0';            // Truncate string.
        while (*p == '0')       // Remove trailing zeros.
            *p-- = '\0';

        if (*p == '.') {        // If all decimals were zeros, remove ".".
            *p = '\0';
        }
    }
}

If you're not happy with the truncation aspect (which would turn 0.12399 into 0.123 rather than rounding it to 0.124), you can actually use the rounding facilities already provided by printf. You just need to analyse the number before-hand to dynamically create the widths, then use those to turn the number into a string:

#include <stdio.h>

void nDecimals (char *s, double d, int n) {
    int sz; double d2;

    // Allow for negative.

    d2 = (d >= 0) ? d : -d;
    sz = (d >= 0) ? 0 : 1;

    // Add one for each whole digit (0.xx special case).

    if (d2 < 1) sz++;
    while (d2 >= 1) { d2 /= 10.0; sz++; }

    // Adjust for decimal point and fractionals.

    sz += 1 + n;

    // Create format string then use it.

    sprintf (s, "%*.*f", sz, n, d);
}

int main (void) {
    char str[50];
    double num[] = { 40, 359.01335, -359.00999,
        359.01, 3.01357, 0.111111111, 1.1223344 };
    for (int i = 0; i < sizeof(num)/sizeof(*num); i++) {
        nDecimals (str, num[i], 3);
        printf ("%30.20f -> %s\n", num[i], str);
    }
    return 0;
}

The whole point of nDecimals() in this case is to correctly work out the field widths, then format the number using a format string based on that. The test harness main() shows this in action:

  40.00000000000000000000 -> 40.000
 359.01335000000000263753 -> 359.013
-359.00999000000001615263 -> -359.010
 359.00999999999999090505 -> 359.010
   3.01357000000000008200 -> 3.014
   0.11111111099999999852 -> 0.111
   1.12233439999999995429 -> 1.122

Once you have the correctly rounded value, you can once again pass that to morphNumericString() to remove trailing zeros by simply changing:

nDecimals (str, num[i], 3);

into:

nDecimals (str, num[i], 3);
morphNumericString (str, 3);

(or calling morphNumericString at the end of nDecimals but, in that case, I'd probably just combine the two into one function), and you end up with:

  40.00000000000000000000 -> 40
 359.01335000000000263753 -> 359.013
-359.00999000000001615263 -> -359.01
 359.00999999999999090505 -> 359.01
   3.01357000000000008200 -> 3.014
   0.11111111099999999852 -> 0.111
   1.12233439999999995429 -> 1.122

jQuery SVG, why can't I addClass?

jQuery 3 does not have this problem

One of the changes listed on the jQuery 3.0 revisions is:

add SVG class manipulation (#2199, 20aaed3)

One solution for this issue would be to upgrade to jQuery 3. It works great:

_x000D_
_x000D_
var flip = true;
setInterval(function() {
    // Could use toggleClass, but demonstrating addClass.
    if (flip) {
        $('svg circle').addClass('green');
    }
    else {
        $('svg circle').removeClass('green');
    }
    flip = !flip;
}, 1000);
_x000D_
svg circle {
    fill: red;
    stroke: black;
    stroke-width: 5;
}
svg circle.green {
    fill: green;
}
_x000D_
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>

<svg>
    <circle cx="50" cy="50" r="25" />
</svg>
_x000D_
_x000D_
_x000D_


The Problem:

The reason the jQuery class manipulation functions do not work with the SVG elements is because jQuery versions prior to 3.0 use the className property for these functions.

Excerpt from jQuery attributes/classes.js:

cur = elem.nodeType === 1 && ( elem.className ?
    ( " " + elem.className + " " ).replace( rclass, " " ) :
    " "
);

This behaves as expected for HTML elements, but for SVG elements className is a little different. For an SVG element, className is not a string, but an instance of SVGAnimatedString.

Consider the following code:

_x000D_
_x000D_
var test_div = document.getElementById('test-div');
var test_svg = document.getElementById('test-svg');
console.log(test_div.className);
console.log(test_svg.className);
_x000D_
#test-div {
    width: 200px;
    height: 50px;
    background: blue;
}
_x000D_
<div class="test div" id="test-div"></div>

<svg width="200" height="50" viewBox="0 0 200 50">
  <rect width="200" height="50" fill="green" class="test svg" id="test-svg" />
</svg>
_x000D_
_x000D_
_x000D_

If you run this code you will see something like the following in your developer console.

test div
SVGAnimatedString { baseVal="test svg",  animVal="test svg"}

If we were to cast that SVGAnimatedString object to a string as jQuery does, we would have [object SVGAnimatedString], which is where jQuery fails.

How the jQuery SVG plugin handles this:

The jQuery SVG plugin works around this by patching the relevant functions to add SVG support.

Excerpt from jQuery SVG jquery.svgdom.js:

function getClassNames(elem) {
    return (!$.svg.isSVGElem(elem) ? elem.className :
        (elem.className ? elem.className.baseVal : elem.getAttribute('class'))) || '';
}

This function will detect if an element is an SVG element, and if it is it will use the baseVal property of the SVGAnimatedString object if available, before falling back on the class attribute.

jQuery's historical stance on the issue:

jQuery currently lists this issue on their Won’t Fix page. Here is the relevant parts.

SVG/VML or Namespaced Elements Bugs

jQuery is primarily a library for the HTML DOM, so most problems related to SVG/VML documents or namespaced elements are out of scope. We do try to address problems that "bleed through" to HTML documents, such as events that bubble out of SVG.

Evidently jQuery considered full SVG support outside the scope of the jQuery core, and better suited for plugins.

Apache Name Virtual Host with SSL

It sounds like Apache is warning you that you have multiple <VirtualHost> sections with the same IP address and port... as far as getting it to work without warnings, I think you would need to use something like Server Name Indication (SNI), a way of identifying the hostname requested as part of the SSL handshake. Basically it lets you do name-based virtual hosting over SSL, but I'm not sure how well it's supported by browsers. Other than something like SNI, you're basically limited to one SSL-enabled domain name for each IP address you expose to the public internet.

Of course, if you are able to access the websites properly, you'll probably be fine ignoring the warnings. These particular ones aren't very serious - they're mainly an indication of what to look at if you are experiencing problems

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

i too faced the same problem.... and resolved by following the below steps:

RC(right click on web project) --> properties --> Deployment Assembly --> Add --> Java Build Path Entries --> Next --> select jar files which are missing --> next --> finish

Application is running successfully...

Trim Whitespaces (New Line and Tab space) in a String in Oracle

If you have Oracle 10g, REGEXP_REPLACE is pretty flexible.

Using the following string as a test:

chr(9) || 'Q   qwer' || chr(9) || chr(10) ||
chr(13) || 'qwerqwer     qwerty' || chr(9) || 
chr(10) || chr(13)

The [[:space:]] will remove all whitespace, and the ([[:cntrl:]])|(^\t) regexp will remove non-printing characters and tabs.

select
    tester,
    regexp_replace(tester, '(^[[:space:]]+)|([[:space:]]+$)',null)
            regexp_tester_1,
    regexp_replace(tester, '(^[[:cntrl:]^\t]+)|([[:cntrl:]^\t]+$)',null) 
            regexp_tester_2
from
    (
    select
        chr(9) || 'Q   qwer' || chr(9) || chr(10) ||
                chr(13) || 'qwerqwer     qwerty' || chr(9) || 
                chr(10) || chr(13) tester 
    from 
        dual
    )

Returning:

  • REGEXP_TESTER_1: "Qqwerqwerqwerqwerty"
  • REGEXP_TESTER_2: "Q qwerqwerqwer qwerty"

Hope this is of some use.

ssh : Permission denied (publickey,gssapi-with-mic)

And I think this will clearify the cause of posted problem, actualy this is bug of pssh itself (contains inside "askpass-client.py"). It is pssh's lib file. And there is documented issue for -A case: https://code.google.com/archive/p/parallel-ssh/issues/80 There are two possible resolutions to use version of pssh containing this bug in case you forced to use passphrase for private key access:

  1. Correct your "askpass-client.py" as described in link listed before in my post.
  2. Using your favorite pass keeper.

Thnks for attention, hope it helps!

Python Web Crawlers and "getting" html source code

If you are using Python > 3.x you don't need to install any libraries, this is directly built in the python framework. The old urllib2 package has been renamed to urllib:

from urllib import request

response = request.urlopen("https://www.google.com")
# set the correct charset below
page_source = response.read().decode('utf-8')
print(page_source)

How to print a groupby object

Thanks to Surya for good insights. I'd clean up his solution and simply do:

for key, value in df.groupby('A'):
    print(key, value)

What is the best way to conditionally apply attributes in AngularJS?

<h1 ng-attr-contenteditable="{{isTrue || undefined }}">{{content.title}}</h1>

will produce when isTrue=true : <h1 contenteditable="true">{{content.title}}</h1>

and when isTrue=false : <h1>{{content.title}}</h1>

How do you convert WSDLs to Java classes using Eclipse?

The Eclipse team with The Open University have prepared the following document, which includes creating proxy classes with tests. It might be what you are looking for.

http://www.eclipse.org/webtools/community/education/web/t320/Generating_a_client_from_WSDL.pdf

Everything is included in the Dynamic Web Project template.

In the project create a Web Service Client. This starts a wizard that has you point out a wsdl url and creates the client with tests for you.

The user guide (targeted at indigo though) for this task is found at http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.jst.ws.cxf.doc.user%2Ftasks%2Fcreate_client.html.

What is meant by immutable?

One meaning has to do with how the value is stored in the computer, For a .Net string for example, it means that the string in memory cannot be changed, When you think you're changing it, you are in fact creating a new string in memory and pointing the existing variable (which is just a pointer to the actual collection of characters somewhere else) to the new string.

Find and replace Android studio

I think the shortcut that you're looking for is:

Ctrl+Shift+R on Windows and Linux/Ubuntu

Cmd+Shift+R on Mac OS X

ref: source

How are environment variables used in Jenkins with Windows Batch Command?

I know nothing about Jenkins, but it looks like you are trying to access environment variables using some form of unix syntax - that won't work.

If the name of the variable is WORKSPACE, then the value is expanded in Windows batch using
%WORKSPACE%. That form of expansion is performed at parse time. For example, this will print to screen the value of WORKSPACE

echo %WORKSPACE%

If you need the value at execution time, then you need to use delayed expansion !WORKSPACE!. Delayed expansion is not normally enabled by default. Use SETLOCAL EnableDelayedExpansion to enable it. Delayed expansion is often needed because blocks of code within parentheses and/or multiple commands concatenated by &, &&, or || are parsed all at once, so a value assigned within the block cannot be read later within the same block unless you use delayed expansion.

setlocal enableDelayedExpansion
set WORKSPACE=BEFORE
(
  set WORKSPACE=AFTER
  echo Normal Expansion = %WORKSPACE%
  echo Delayed Expansion = !WORKSPACE!
)

The output of the above is

Normal Expansion = BEFORE
Delayed Expansion = AFTER

Use HELP SET or SET /? from the command line to get more information about Windows environment variables and the various expansion options. For example, it explains how to do search/replace and substring operations.

No more data to read from socket error

Another case: If you are sending date parameters to a parameterized sql, make sure you sent java.sql.Timestamp and not java.util.Date. Otherwise you get

java.sql.SQLRecoverableException: No more data to read from socket

Example statement: In our java code, we are using org.apache.commons.dbutils and we have the following:

final String sqlStatement = "select x from person where date_of_birth between ? and ?";
java.util.Date dtFrom = new Date(); //<-- this will fail
java.util.Date dtTo = new Date();   //<-- this will fail
Object[] params = new Object[]{ dtFrom , dtTo };
final List mapList = (List) query.query(conn, sqlStatement, new MapListHandler(),params); 

The above was failing until we changed the date parameters to be java.sql.Timestamp

java.sql.Timestamp tFrom = new java.sql.Timestamp (dtFrom.getTime()); //<-- this is OK
java.sql.Timestamp tTo = new java.sql.Timestamp(dtTo.getTime());   //<-- this is OK
Object[] params = new Object[]{ tFrom , tTo };
final List mapList = (List) query.query(conn, sqlStatement, new MapListHandler(),params); 

How to call Stored Procedure in Entity Framework 6 (Code-First)?

public IList<Models.StandardRecipeDetail> GetRequisitionDetailBySearchCriteria(Guid subGroupItemId, Guid groupItemId)
{
    var query = this.UnitOfWork.Context.Database.SqlQuery<Models.StandardRecipeDetail>("SP_GetRequisitionDetailBySearchCriteria @SubGroupItemId,@GroupItemId",
    new System.Data.SqlClient.SqlParameter("@SubGroupItemId", subGroupItemId),
    new System.Data.SqlClient.SqlParameter("@GroupItemId", groupItemId));
    return query.ToList();
}

MySql: is it possible to 'SUM IF' or to 'COUNT IF'?

You can also use SUM + IF which is shorter than SUM + CASE:

SELECT
    count(id)
    , SUM(IF(kind=1, 1, 0)) AS countKindOne
    , SUM(CASE WHEN kind=2 THEN 1 ELSE 0 END) AS countKindTwo

SQLAlchemy equivalent to SQL "LIKE" statement

Each column has like() method, which can be used in query.filter(). Given a search string, add a % character on either side to search as a substring in both directions.

tag = request.form["tag"]
search = "%{}%".format(tag)
posts = Post.query.filter(Post.tags.like(search)).all()

How to get pandas.DataFrame columns containing specific dtype

dtypes is a Pandas Series. That means it contains index & values attributes. If you only need the column names:

headers = df.dtypes.index

it will return a list containing the column names of "df" dataframe.

How to hide form code from view code/inspect element browser?

Below JavaScript code worked for me to disable inspect element.

// Disable inspect element
$(document).bind("contextmenu",function(e) {
 e.preventDefault();
});
$(document).keydown(function(e){
    if(e.which === 123){
       return false;
    }
});

CSS border less than 1px

A pixel is the smallest unit value to render something with, but you can trick thickness with optical illusions by modifying colors (the eye can only see up to a certain resolution too).

Here is a test to prove this point:

_x000D_
_x000D_
div { border-color: blue; border-style: solid; margin: 2px; }

div.b1 { border-width: 1px; }
div.b2 { border-width: 0.1em; }
div.b3 { border-width: 0.01em; }
div.b4 { border-width: 1px; border-color: rgb(160,160,255); }
_x000D_
<div class="b1">Some text</div>
<div class="b2">Some text</div>
<div class="b3">Some text</div>
<div class="b4">Some text</div>
_x000D_
_x000D_
_x000D_

Output

enter image description here

Which gives the illusion that the last DIV has a smaller border width, because the blue border blends more with the white background.


Edit: Alternate solution

Alpha values may also be used to simulate the same effect, without the need to calculate and manipulate RGB values.

_x000D_
_x000D_
.container {
  border-style: solid;
  border-width: 1px;
  
  margin-bottom: 10px;
}

.border-100 { border-color: rgba(0,0,255,1); }
.border-75 { border-color: rgba(0,0,255,0.75); }
.border-50 { border-color: rgba(0,0,255,0.5); }
.border-25 { border-color: rgba(0,0,255,0.25); }
_x000D_
<div class="container border-100">Container 1 (alpha = 1)</div>
<div class="container border-75">Container 2 (alpha = 0.75)</div>
<div class="container border-50">Container 3 (alpha = 0.5)</div>
<div class="container border-25">Container 4 (alpha = 0.25)</div>
_x000D_
_x000D_
_x000D_

How to update the constant height constraint of a UIView programmatically?

If you have a view with multiple constrains, a much easier way without having to create multiple outlets would be:

In interface builder, give each constraint you wish to modify an identifier:

enter image description here

Then in code you can modify multiple constraints like so:

for constraint in self.view.constraints {
    if constraint.identifier == "myConstraint" {
       constraint.constant = 50
    }
}
myView.layoutIfNeeded()

You can give multiple constrains the same identifier thus allowing you to group together constrains and modify all at once.

UIImageView aspect fit and center

Just pasting the solution:

Just like @manohar said

imageView.contentMode = UIViewContentModeCenter;
if (imageView.bounds.size.width > ((UIImage*)imagesArray[i]).size.width && imageView.bounds.size.height > ((UIImage*)imagesArray[i]).size.height) {
       imageView.contentMode = UIViewContentModeScaleAspectFit;
}

solved my problem

SQL - HAVING vs. WHERE

Didn't see an example of both in one query. So this example might help.

  /**
INTERNATIONAL_ORDERS - table of orders by company by location by day
companyId, country, city, total, date
**/

SELECT country, city, sum(total) totalCityOrders 
FROM INTERNATIONAL_ORDERS with (nolock)
WHERE companyId = 884501253109
GROUP BY country, city
HAVING country = 'MX'
ORDER BY sum(total) DESC

This filters the table first by the companyId, then groups it (by country and city) and additionally filters it down to just city aggregations of Mexico. The companyId was not needed in the aggregation but we were able to use WHERE to filter out just the rows we wanted before using GROUP BY.

Print Currency Number Format in PHP

with the intl extension in PHP 5.3+, you can use the NumberFormatter class:

$amount = '12345.67';

$formatter = new NumberFormatter('en_GB',  NumberFormatter::CURRENCY);
echo 'UK: ', $formatter->formatCurrency($amount, 'EUR'), PHP_EOL;

$formatter = new NumberFormatter('de_DE',  NumberFormatter::CURRENCY);
echo 'DE: ', $formatter->formatCurrency($amount, 'EUR'), PHP_EOL;

which prints :

 UK: €12,345.67
 DE: 12.345,67 €

Run a PHP file in a cron job using CPanel

For domain specific Multi PHP Cron Job, do like this,

/usr/local/bin/ea-php56 /home/username/domain_path/path/to/cron/script

In the above example, replace “ea-php56” with the PHP version assigned to the domain you wish to use.

Hope this helps someone.

SQL to add column and comment in table in single command

Query to add column with comment are :

alter table table_name 
add( "NISFLAG"    NUMBER(1,0) )

comment on column "ELIXIR"."PRD_INFO_1"."NISPRODGSTAPPL" is 'comment here'

commit;

How to display a PDF via Android web browser without "downloading" first

public class MainActivity extends AppCompatActivity {

    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openURL("http://docs.google.com/viewer?url=" + " your pdf link ");
            }
        });
    }

    private void openURL(String s) {
        Uri uri = Uri.parse(s);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri,"text/html");
        startActivity(intent);
    }
}

This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console

For me, it was Maps Embed API that I had to enable.

In the Google Cloud Console

Go to API tab, look through the Additional APIs section and try to enable any map-related APIs.

enter image description here

Write to Windows Application Event Log

You can using the EventLog class, as explained on How to: Write to the Application Event Log (Visual C#):

var appLog = new EventLog("Application");
appLog.Source = "MySource";
appLog.WriteEntry("Test log message");

However, you'll need to configure this source "MySource" using administrative privileges:

Use WriteEvent and WriteEntry to write events to an event log. You must specify an event source to write events; you must create and configure the event source before writing the first entry with the source.

"ORA-01438: value larger than specified precision allowed for this column" when inserting 3

You can't update with a number greater than 1 for datatype number(2,2) is because, the first parameter is the total number of digits in the number and the second one (.i.e 2 here) is the number of digits in decimal part. I guess you can insert or update data < 1. i.e. 0.12, 0.95 etc.

Please check NUMBER DATATYPE in NUMBER Datatype.

Send email by using codeigniter library via localhost

I had the same problem and I solved by using the postcast server. You can install it locally and use it.

SQL Server - NOT IN

One issue could be that if either make, model, or [serial number] were null, values would never get returned. Because string concatenations with null values always result in null, and not in () with null will always return nothing. The remedy for this is to use an operator such as IsNull(make, '') + IsNull(Model, ''), etc.

Why doesn't TFS get latest get the latest?

Unfortunately, there has to be one or more bugs in TFS 2008, since this problem regularly crop up on developer machines and build servers where I work as well.

I can do Get Latest, I can see in the history list of the project that there have been commits after I last did a Get Latest, I have not touched the files on disk in any way, but after the "Get Latest" function has completed, when I check the TFS tab, some of the files still says that they're not the latest version.

Obviously TFS is able to determine that I have old files locally, since the list says so. Yet, Get Latest fails to do that, get the latest version. If I do what you did, use the Get Specific version, and check the two checkboxes at the bottom of the dialog, then the files are retrieved.

We changed our build servers to always use the Get Specific version type of function instead, so this part now works, but since our build server (TeamCity) also relies on checking if there have been changes to the files in order to kick off a build, sometimes it lapses into a "nothing changed, nothing to see here, move along" mode and does nothing until we forcibly run the build configuration.

Note that I have experienced this problem on a machine that is never touched, except for get latest + build, both manually, so there's nothing tampering with the files. It's just TFS getting confused.

One time this cropped up I verified that the files on disk was indeed binary identical to the version previously retrieved, so no manual tampering had been done with the files.

Also, I fail to see how TFS can "know" whether files have changed on disk or not without actually looking at the contents. If one part of TFS can see that the files are indeed not the latest version, then the Get Latest version should absolutely be able to get the latest version. This in reference to comments to other answers here.

How can I break up this long line in Python?

That's a start. It's not a bad practice to define your longer strings outside of the code that uses them. It's a way to separate data and behavior. Your first option is to join string literals together implicitly by making them adjacent to one another:

("This is the first line of my text, "
"which will be joined to a second.")

Or with line ending continuations, which is a little more fragile, as this works:

"This is the first line of my text, " \
"which will be joined to a second."

But this doesn't:

"This is the first line of my text, " \ 
"which will be joined to a second."

See the difference? No? Well you won't when it's your code either.

The downside to implicit joining is that it only works with string literals, not with strings taken from variables, so things can get a little more hairy when you refactor. Also, you can only interpolate formatting on the combined string as a whole.

Alternatively, you can join explicitly using the concatenation operator (+):

("This is the first line of my text, " + 
"which will be joined to a second.")

Explicit is better than implicit, as the zen of python says, but this creates three strings instead of one, and uses twice as much memory: there are the two you have written, plus one which is the two of them joined together, so you have to know when to ignore the zen. The upside is you can apply formatting to any of the substrings separately on each line, or to the whole lot from outside the parentheses.

Finally, you can use triple-quoted strings:

"""This is the first line of my text
which will be joined to a second."""

This is often my favorite, though its behavior is slightly different as the newline and any leading whitespace on subsequent lines will show up in your final string. You can eliminate the newline with an escaping backslash.

"""This is the first line of my text \
which will be joined to a second."""

This has the same problem as the same technique above, in that correct code only differs from incorrect code by invisible whitespace.

Which one is "best" depends on your particular situation, but the answer is not simply aesthetic, but one of subtly different behaviors.

Chart.js v2 hide dataset labels

You can also put the tooltip onto one line by removing the "title":

this.chart = new Chart(ctx, {
    type: this.props.horizontal ? 'horizontalBar' : 'bar',
    options: {
        legend: {
            display: false,
        },
        tooltips: {
            callbacks: {
                label: tooltipItem => `${tooltipItem.yLabel}: ${tooltipItem.xLabel}`, 
                title: () => null,
            }
        },
    },
});

enter image description here

symfony2 : failed to write cache directory

Maybe you forgot to change the permissions of app/cache app/log

I'm using Ubuntu so

sudo chmod -R 777 app/cache
sudo chmod -R 777 app/logs
sudo setfacl -dR -m u::rwX app/cache app/logs

Hope it helps..

How to uncommit my last commit in Git

If you commit to the wrong branch

While on the wrong branch:

  1. git log -2 gives you hashes of 2 last commits, let's say $prev and $last
  2. git checkout $prev checkout correct commit
  3. git checkout -b new-feature-branch creates a new branch for the feature
  4. git cherry-pick $last patches a branch with your changes

Then you can follow one of the methods suggested above to remove your commit from the first branch.

What exactly is Python's file.flush() doing?

Basically, flush() cleans out your RAM buffer, its real power is that it lets you continue to write to it afterwards - but it shouldn't be thought of as the best/safest write to file feature. It's flushing your RAM for more data to come, that is all. If you want to ensure data gets written to file safely then use close() instead.

Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0

I'm having the same issue here and I was a bit afraid of checking the last box, since I have no idea what the 3rd party SDK will do with the data collected and if they will respect the Limit Ad Settings.

But I found a post by a Google Admob programmer, Eric Leichtenschlag, on their forums:

The Google Mobile Ads SDK and the Google Conversion Tracking SDK utilize Apple's advertising identifier introduced in iOS 6 (IDFA). While each developer is responsible for how they access device data, the SDKs use IDFA under the guidelines laid out in the iOS developer program license agreement, including Limit Ad Tracking.

Including Limit Ad Tracking. This is what the last box is all about. So you must check the that box if you use AdMob. If you use other SDK I strongly recommend checking if they respect the guidelines as well.

Since I run only ads (Google AdMob), I checked the first (Serve ads...) and last box (I, ___, confirm...). App was approved and released, no issues.

Source: https://groups.google.com/forum/#!topic/google-admob-ads-sdk/BsGRSZ-gLmk

Ship an application with a database

I wrote a library to simplify this process.

dataBase = new DataBase.Builder(context, "myDb").
//        setAssetsPath(). // default "databases"
//        setDatabaseErrorHandler().
//        setCursorFactory().
//        setUpgradeCallback()
//        setVersion(). // default 1
build();

It will create a dataBase from assets/databases/myDb.db file. In addition you will get all those functionality:

  • Load database from file
  • Synchronized access to the database
  • Using sqlite-android by requery, Android specific distribution of the latest versions of SQLite.

Clone it from github.

How to set max width of an image in CSS

The problem is that img tag is inline element and you can't restrict width of inline element.

So to restrict img tag width first you need to convert it into a inline-block element

img.Image{
    display: inline-block;
}

How do I reset a sequence in Oracle?

Here's how to make all auto-increment sequences match actual data:

  1. Create a procedure to enforce next value as was already described in this thread:

    CREATE OR REPLACE PROCEDURE Reset_Sequence(
        P_Seq_Name IN VARCHAR2,
        P_Val      IN NUMBER DEFAULT 0)
    IS
      L_Current    NUMBER                      := 0;
      L_Difference NUMBER                      := 0;
      L_Minvalue User_Sequences.Min_Value%Type := 0;
    BEGIN
      SELECT Min_Value
      INTO L_Minvalue
      FROM User_Sequences
      WHERE Sequence_Name = P_Seq_Name;
      EXECUTE Immediate 'select ' || P_Seq_Name || '.nextval from dual' INTO L_Current;
      IF P_Val        < L_Minvalue THEN
        L_Difference := L_Minvalue - L_Current;
      ELSE
        L_Difference := P_Val - L_Current;
      END IF;
      IF L_Difference = 0 THEN
        RETURN;
      END IF;
      EXECUTE Immediate 'alter sequence ' || P_Seq_Name || ' increment by ' || L_Difference || ' minvalue ' || L_Minvalue;
      EXECUTE Immediate 'select ' || P_Seq_Name || '.nextval from dual' INTO L_Difference;
      EXECUTE Immediate 'alter sequence ' || P_Seq_Name || ' increment by 1 minvalue ' || L_Minvalue;
    END Reset_Sequence;
    
  2. Create another procedure to reconcile all sequences with actual content:

    CREATE OR REPLACE PROCEDURE RESET_USER_SEQUENCES_TO_DATA
    IS
      STMT CLOB;
    BEGIN
      SELECT 'select ''BEGIN'' || chr(10) || x || chr(10) || ''END;'' FROM (select listagg(x, chr(10)) within group (order by null) x FROM ('
        || X
        || '))'
      INTO STMT
      FROM
        (SELECT LISTAGG(X, ' union ') WITHIN GROUP (
        ORDER BY NULL) X
        FROM
          (SELECT CHR(10)
            || 'select ''Reset_Sequence('''''
            || SEQ_NAME
            || ''''','' || coalesce(max('
            || COL_NAME
            || '), 0) || '');'' x from '
            || TABLE_NAME X
          FROM
            (SELECT TABLE_NAME,
              REGEXP_SUBSTR(WTEXT, 'NEW\.(\S*) IS NULL',1,1,'i',1) COL_NAME,
              REGEXP_SUBSTR(BTEXT, '(\.|\s)([a-z_]*)\.nextval',1,1,'i',2) SEQ_NAME
            FROM USER_TRIGGERS
            LEFT JOIN
              (SELECT NAME BNAME,
                TEXT BTEXT
              FROM USER_SOURCE
              WHERE TYPE = 'TRIGGER'
              AND UPPER(TEXT) LIKE '%NEXTVAL%'
              )
            ON BNAME = TRIGGER_NAME
            LEFT JOIN
              (SELECT NAME WNAME,
                TEXT WTEXT
              FROM USER_SOURCE
              WHERE TYPE = 'TRIGGER'
              AND UPPER(TEXT) LIKE '%IS NULL%'
              )
            ON WNAME             = TRIGGER_NAME
            WHERE TRIGGER_TYPE   = 'BEFORE EACH ROW'
            AND TRIGGERING_EVENT = 'INSERT'
            )
          )
        ) ;
      EXECUTE IMMEDIATE STMT INTO STMT;
      --dbms_output.put_line(stmt);
      EXECUTE IMMEDIATE STMT;
    END RESET_USER_SEQUENCES_TO_DATA;
    

NOTES:

  1. Procedure extracts names from trigger code and does not depend on naming conventions
  2. To check generated code before execution, switch comments on last two lines

Truncate (not round) decimal places in SQL Server

Please try to use this code for converting 3 decimal values after a point into 2 decimal places:

declare @val decimal (8, 2)
select @val = 123.456
select @val =  @val

select @val

The output is 123.46

Description Box using "onmouseover"

Well, I made a simple two liner script for this, Its small and does what u want.

Check it http://jsfiddle.net/9RxLM/

Its a jquery solution :D

How to send an email with Gmail as provider using Python?

There is a gmail API now, which lets you send email, read email and create drafts via REST. Unlike the SMTP calls, it is non-blocking which can be a good thing for thread-based webservers sending email in the request thread (like python webservers). The API is also quite powerful.

  • Of course, email should be handed off to a non-webserver queue, but it's nice to have options.

It's easiest to setup if you have Google Apps administrator rights on the domain, because then you can give blanket permission to your client. Otherwise you have to fiddle with OAuth authentication and permission.

Here is a gist demonstrating it:

https://gist.github.com/timrichardson/1154e29174926e462b7a

Find a pair of elements from an array whose sum equals a given number

I bypassed the bit manuplation and just compared the index values. This is less than the loop iteration value (i in this case). This will not print the duplicate pairs and duplicate array elements also.

public static void findSumHashMap(int[] arr, int key) {
    Map<Integer, Integer> valMap = new HashMap<Integer, Integer>();
    for (int i = 0; i < arr.length; i++) {
        valMap.put(arr[i], i);
    }
    for (int i = 0; i < arr.length; i++) {
        if (valMap.containsKey(key - arr[i])
                && valMap.get(key - arr[i]) != i) {
            if (valMap.get(key - arr[i]) < i) {
                int diff = key - arr[i];
                System.out.println(arr[i] + " " + diff);
            }
        }
    }
}

How to find sum of multiple columns in a table in SQL Server 2005?

Hi You can use a simple query,

select emp_cd, val1, val2, val3,
(val1+val2+val3) as total 
from emp;

In case you need to insert a new row,

insert into emp select emp_cd, val1, val2, val3,
(val1+val2+val3) as total 
from emp;

In order to update,

update emp set total = val1+val2+val3;

This will update for all comumns

How to make a new line or tab in <string> XML (eclipse/android)?

\n didn't work for me. So I used <br></br> HTML tag

    <string name="message_register_success">
Sign up is complete. <br></br>
 Enjoy a new shopping life at MageMobile!!
</string>

How can I send mail from an iPhone application

Swift 2.2. Adapted from Esq's answer

import Foundation
import MessageUI

class MailSender: NSObject, MFMailComposeViewControllerDelegate {

    let parentVC: UIViewController

    init(parentVC: UIViewController) {
        self.parentVC = parentVC
        super.init()
    }

    func send(title: String, messageBody: String, toRecipients: [String]) {
        if MFMailComposeViewController.canSendMail() {
            let mc: MFMailComposeViewController = MFMailComposeViewController()
            mc.mailComposeDelegate = self
            mc.setSubject(title)
            mc.setMessageBody(messageBody, isHTML: false)
            mc.setToRecipients(toRecipients)
            parentVC.presentViewController(mc, animated: true, completion: nil)
        } else {
            print("No email account found.")
        }
    }

    func mailComposeController(controller: MFMailComposeViewController,
        didFinishWithResult result: MFMailComposeResult, error: NSError?) {

            switch result.rawValue {
            case MFMailComposeResultCancelled.rawValue: print("Mail Cancelled")
            case MFMailComposeResultSaved.rawValue: print("Mail Saved")
            case MFMailComposeResultSent.rawValue: print("Mail Sent")
            case MFMailComposeResultFailed.rawValue: print("Mail Failed")
            default: break
            }

            parentVC.dismissViewControllerAnimated(false, completion: nil)
    }
}

Client code :

var ms: MailSender?

@IBAction func onSendPressed(sender: AnyObject) {
    ms = MailSender(parentVC: self)
    let title = "Title"
    let messageBody = "https://stackoverflow.com/questions/310946/how-can-i-send-mail-from-an-iphone-application this question."
    let toRecipents = ["[email protected]"]
    ms?.send(title, messageBody: messageBody, toRecipents: toRecipents)
}

Array versus linked-list

as arrays are static in nature, therefore all operations like memory allocation occur at the time of compilation only. So processor has to put less effort at its runtime .

Failed to Connect to MySQL at localhost:3306 with user root

  1. set root user to mysql_native_password

$ sudo mysql -u root -p # I had to use "sudo" since is new installation

mysql:~ USE mysql;
mysql:~ SELECT User, Host, plugin FROM mysql.user;
mysql:~ UPDATE user SET plugin='mysql_native_password' WHERE User='root';
mysql:~ FLUSH PRIVILEGES;
mysql:~ exit;

$ service mysql restart

How can I find WPF controls by name or type?

Here's my code to find controls by Type while controlling how deep we go into the hierarchy (maxDepth == 0 means infinitely deep).

public static class FrameworkElementExtension
{
    public static object[] FindControls(
        this FrameworkElement f, Type childType, int maxDepth)
    {
        return RecursiveFindControls(f, childType, 1, maxDepth);
    }

    private static object[] RecursiveFindControls(
        object o, Type childType, int depth, int maxDepth = 0)
    {
        List<object> list = new List<object>();
        var attrs = o.GetType()
            .GetCustomAttributes(typeof(ContentPropertyAttribute), true);
        if (attrs != null && attrs.Length > 0)
        {
            string childrenProperty = (attrs[0] as ContentPropertyAttribute).Name;
            foreach (var c in (IEnumerable)o.GetType()
                .GetProperty(childrenProperty).GetValue(o, null))
            {
                if (c.GetType().FullName == childType.FullName)
                    list.Add(c);
                if (maxDepth == 0 || depth < maxDepth)
                    list.AddRange(RecursiveFindControls(
                        c, childType, depth + 1, maxDepth));
            }
        }
        return list.ToArray();
    }
}

install cx_oracle for python

Thx Burhan Khalid, I overlooked your "You need to be root" quote, but found the way when you are not the root here.

At point 7 you need to use:

sudo env ORACLE_HOME=$ORACLE_HOME python setup.py install 

Or

sudo env ORACLE_HOME=/path/to/instantclient python setup.py install

CSS z-index not working (position absolute)

JSFiddle

You have to put the second div on top of the first one because the both have an z-index of zero so that the order in the dom will decide which is on top. This also affects the relative positioned div because its z-index relates to elements inside the parent div.

<div class="absolute" style="top: 54px"></div>
<div class="absolute">
    <div id="relative"></div>
</div>

Css stays the same.

How to test if a string is basically an integer in quotes using Ruby

For more generalised cases (including numbers with decimal point), you can try the following method:

def number?(obj)
  obj = obj.to_s unless obj.is_a? String
  /\A[+-]?\d+(\.[\d]+)?\z/.match(obj)
end

You can test this method in an irb session:

(irb)
>> number?(7)
=> #<MatchData "7" 1:nil>
>> !!number?(7)
=> true
>> number?(-Math::PI)
=> #<MatchData "-3.141592653589793" 1:".141592653589793">
>> !!number?(-Math::PI)
=> true
>> number?('hello world')
=> nil
>> !!number?('hello world')
=> false

For a detailed explanation of the regex involved here, check out this blog article :)

Python: How do I make a subclass from a superclass?

class Class1(object):
    pass

class Class2(Class1):
    pass

Class2 is a sub-class of Class1

Convert double to BigDecimal and set BigDecimal Precision

Why not :

b = b.setScale(2, RoundingMode.HALF_UP);

Show/Hide Multiple Divs with Jquery

I had this same problem, read this post, but ended building this solution that selects the divs dynamically by fetching the ID from a custom class on the href using JQuery's attr() function.

Here's the JQuery:

$('a.custom_class').click(function(e) {
  var div = $(this).attr('href');
  $(div).toggle('fast');
  e.preventDefault();
}

And you just have to create a link like this then in the HTML:

<a href="#" class="#1">Link Text</a>
<div id="1">Div Content</div>