Programs & Examples On #Communication diagram

How to set default value for column of new created table from select statement in 11g

new table inherits only "not null" constraint and no other constraint. Thus you can alter the table after creating it with "create table as" command or you can define all constraint that you need by following the

create table t1 (id number default 1 not null);
insert into t1 (id) values (2);

create table t2 as select * from t1;

This will create table t2 with not null constraint. But for some other constraint except "not null" you should use the following syntax

create table t1 (id number default 1 unique);
insert into t1 (id) values (2);

create table t2 (id default 1 unique)
as select * from t1;

How to generate random positive and negative numbers in Java

You random on (0, 32767+32768) then subtract by 32768

Finding last index of a string in Oracle

Use -1 as the start position:

INSTR('JD-EQ-0001', '-', -1)

Accessing MP3 metadata with Python

I've used mutagen to edit tags in media files before. The nice thing about mutagen is that it can handle other formats, such as mp4, FLAC etc. I've written several scripts with a lot of success using this API.

Parsing time string in Python

Your best bet is to have a look at strptime()

Something along the lines of

>>> from datetime import datetime
>>> date_str = 'Tue May 08 15:14:45 +0800 2012'
>>> date = datetime.strptime(date_str, '%a %B %d %H:%M:%S +0800 %Y')
>>> date
datetime.datetime(2012, 5, 8, 15, 14, 45)

Im not sure how to do the +0800 timezone unfortunately, maybe someone else can help out with that.

The formatting strings can be found at http://docs.python.org/library/time.html#time.strftime and are the same for formatting the string for printing.

Hope that helps

Mark

PS, Your best bet for timezones in installing pytz from pypi. ( http://pytz.sourceforge.net/ ) in fact I think pytz has a great datetime parsing method if i remember correctly. The standard lib is a little thin on the ground with timezone functionality.

How can I get around MySQL Errcode 13 with SELECT INTO OUTFILE?

You can do this :

mysql -u USERNAME --password=PASSWORD --database=DATABASE --execute='SELECT `FIELD`, `FIELD` FROM `TABLE` LIMIT 0, 10000 ' -X > file.xml

How to iterate through property names of Javascript object?

In JavaScript 1.8.5, Object.getOwnPropertyNames returns an array of all properties found directly upon a given object.

Object.getOwnPropertyNames ( obj )

and another method Object.keys, which returns an array containing the names of all of the given object's own enumerable properties.

Object.keys( obj )

I used forEach to list values and keys in obj, same as for (var key in obj) ..

Object.keys(obj).forEach(function (key) {
      console.log( key , obj[key] );
});

This all are new features in ECMAScript , the mothods getOwnPropertyNames, keys won't supports old browser's.

How to force a SQL Server 2008 database to go Offline

Go offline

USE master
GO
ALTER DATABASE YourDatabaseName
SET OFFLINE WITH ROLLBACK IMMEDIATE
GO

Go online

USE master
GO
ALTER DATABASE YourDatabaseName
SET ONLINE
GO

How to convert SQL Server's timestamp column to datetime format

The simplest way of doing this is:

SELECT id,name,FROM_UNIXTIME(registration_date) FROM `tbl_registration`;

This gives the date column atleast in a readable format. Further if you want to change te format click here.

JPA mapping: "QuerySyntaxException: foobar is not mapped..."

I got the same error while using other one entity, He was annotating the class wrongly by using the table name inside the @Entity annotation without using the @Table annotation

The correct format should be

@Entity //default name similar to class name 'FooBar' OR @Entity( name = "foobar" ) for differnt entity name
@Table( name = "foobar" ) // Table name 
public class FooBar{

How can I check if a JSON is empty in NodeJS?

Object.keys(myObj).length === 0;

As there is need to just check if Object is empty it will be better to directly call a native method Object.keys(myObj).length which returns the array of keys by internally iterating with for..in loop.As Object.hasOwnProperty returns a boolean result based on the property present in an object which itself iterates with for..in loop and will have time complexity O(N2).

On the other hand calling a UDF which itself has above two implementations or other will work fine for small object but will block the code which will have severe impact on overall perormance if Object size is large unless nothing else is waiting in the event loop.

How to redirect verbose garbage collection output to a file?

Java 9 & Unified JVM Logging

JEP 158 introduces a common logging system for all components of the JVM which will change (and IMO simplify) how logging works with GC. JEP 158 added a new command-line option to control logging from all components of the JVM:

-Xlog

For example, the following option:

-Xlog:gc

will log messages tagged with gc tag using info level to stdout. Or this one:

-Xlog:gc=debug:file=gc.txt:none

would log messages tagged with gc tag using debug level to a file called gc.txt with no decorations. For more detailed discussion, you can checkout the examples in the JEP page.

What is an efficient way to implement a singleton pattern in Java?

Wikipedia has some examples of singletons, also in Java. The Java 5 implementation looks pretty complete, and is thread-safe (double-checked locking applied).

Changing API level Android Studio

For the latest Android Studio v2.3.3 (October 11th, 2017) :
1. Click View on menu bar
2. Click Open Module Settings
3. Open Flavors tab
4. Choose Min Sdk version you need
IDE Project Structure Window 6. Click OK

Convert json to a C# array?

Yes, Json.Net is what you need. You basically want to deserialize a Json string into an array of objects.

See their examples:

string myJsonString = @"{
  "Name": "Apple",
  "Expiry": "\/Date(1230375600000+1300)\/",
  "Price": 3.99,
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ]
}";

// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);

Angular 2 - Checking for server errors from subscribe

As stated in the relevant RxJS documentation, the .subscribe() method can take a third argument that is called on completion if there are no errors.

For reference:

  1. [onNext] (Function): Function to invoke for each element in the observable sequence.
  2. [onError] (Function): Function to invoke upon exceptional termination of the observable sequence.
  3. [onCompleted] (Function): Function to invoke upon graceful termination of the observable sequence.

Therefore you can handle your routing logic in the onCompleted callback since it will be called upon graceful termination (which implies that there won't be any errors when it is called).

this.httpService.makeRequest()
    .subscribe(
      result => {
        // Handle result
        console.log(result)
      },
      error => {
        this.errors = error;
      },
      () => {
        // 'onCompleted' callback.
        // No errors, route to new page here
      }
    );

As a side note, there is also a .finally() method which is called on completion regardless of the success/failure of the call. This may be helpful in scenarios where you always want to execute certain logic after an HTTP request regardless of the result (i.e., for logging purposes or for some UI interaction such as showing a modal).

Rx.Observable.prototype.finally(action)

Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.

For instance, here is a basic example:

import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/finally';

// ...

this.httpService.getRequest()
    .finally(() => {
      // Execute after graceful or exceptionally termination
      console.log('Handle logging logic...');
    })
    .subscribe (
      result => {
        // Handle result
        console.log(result)
      },
      error => {
        this.errors = error;
      },
      () => {
        // No errors, route to new page
      }
    );

python modify item in list, save back in list

You need to use the enumerate function: python docs

for place, item in enumerate(list):
    if "foo" in item:
        item = replace_all(item, replaceDictionary)
        list[place] = item
        print item

Also, it's a bad idea to use the word list as a variable, due to it being a reserved word in python.

Since you had problems with enumerate, an alternative from the itertools library:

for place, item in itertools.zip(itertools.count(0), list):
    if "foo" in item:
        item = replace_all(item, replaceDictionary)
        list[place] = item
        print item

Resolving IP Address from hostname with PowerShell

If you know part of the subnet (i.e. 10.3 in this example), then this will grab any addresses that are in the given subnet:

PS C:\> [System.Net.Dns]::GetHostAddresses("MyPC") | foreach { $_.IPAddressToString | findstr "10.3."}

Giving multiple conditions in for loop in Java

If you want to do that why not go with a while, for ease of mind? :P No, but seriously I didn't know that and seems kinda nice so thanks, nice to know!

What does the 'static' keyword do in a class?

Understanding Static concepts

public class StaticPractise1 {
    public static void main(String[] args) {
        StaticPractise2 staticPractise2 = new StaticPractise2();
        staticPractise2.printUddhav(); //true
        StaticPractise2.printUddhav(); /* false, because printUddhav() is although inside StaticPractise2, but it is where exactly depends on PC program counter on runtime. */

        StaticPractise2.printUddhavsStatic1(); //true
        staticPractise2.printUddhavsStatic1(); /*false, because, when staticPractise2 is blueprinted, it tracks everything other than static  things and it organizes in its own heap. So, class static methods, object can't reference */

    }
}

Second Class

public class StaticPractise2 {
    public static void printUddhavsStatic1() {
        System.out.println("Uddhav");
    }

    public void printUddhav() {
        System.out.println("Uddhav");
    }
}

Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES)

try $conn = mysql_connect("localhost", "root") or $conn = mysql_connect("localhost", "root", "")

Databound drop down list - initial value

dropdownlist.Items.Insert(0, new Listitem("--Select One--", "0");

To switch from vertical split to horizontal split fast in Vim

In VIM, take a look at the following to see different alternatives for what you might have done:

:help opening-window

For instance:

Ctrl-W s
Ctrl-W o
Ctrl-W v
Ctrl-W o
Ctrl-W s
...

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

Even easier is just to add the following annotations to the top of your class:

[Serializable, XmlRoot("user")]
public partial class User
{
}

How to remove indentation from an unordered list item?

Doing this inline, I set the margin to 0 (ul style="margin:-0px"). The bullets align with paragraph with no overhang.

How do I print out the contents of a vector?

How about for_each + lambda expression:

#include <vector>
#include <algorithm>
// ...
std::vector<char> vec;
// ...
std::for_each(
              vec.cbegin(),
              vec.cend(),
              [] (const char c) {std::cout << c << " ";} 
              );
// ...

Of course, a range-based for is the most elegant solution for this concrete task, but this one gives many other possibilities as well.

Explanation

The for_each algorithm takes an input range and a callable object, calling this object on every element of the range. An input range is defined by two iterators. A callable object can be a function, a pointer to function, an object of a class which overloads () operator or as in this case, a lambda expression. The parameter for this expression matches the type of the elements from vector.

The beauty of this implementation is the power you get from lambda expressions - you can use this approach for a lot more things than just printing the vector.

Set NA to 0 in R

You can just use the output of is.na to replace directly with subsetting:

bothbeams.data[is.na(bothbeams.data)] <- 0

Or with a reproducible example:

dfr <- data.frame(x=c(1:3,NA),y=c(NA,4:6))
dfr[is.na(dfr)] <- 0
dfr
  x y
1 1 0
2 2 4
3 3 5
4 0 6

However, be careful using this method on a data frame containing factors that also have missing values:

> d <- data.frame(x = c(NA,2,3),y = c("a",NA,"c"))
> d[is.na(d)] <- 0
Warning message:
In `[<-.factor`(`*tmp*`, thisvar, value = 0) :
  invalid factor level, NA generated

It "works":

> d
  x    y
1 0    a
2 2 <NA>
3 3    c

...but you likely will want to specifically alter only the numeric columns in this case, rather than the whole data frame. See, eg, the answer below using dplyr::mutate_if.

What is the 'instanceof' operator used for in Java?

class Test48{
public static void main (String args[]){
Object Obj=new Hello();
//Hello obj=new Hello;
System.out.println(Obj instanceof String);
System.out.println(Obj instanceof Hello);
System.out.println(Obj instanceof Object);
Hello h=null;
System.out.println(h instanceof Hello);
System.out.println(h instanceof Object);
}
}  

TypeError: list indices must be integers or slices, not str

I had same error and the mistake was that I had added list and dictionary into the same list (object) and when I used to iterate over the list of dictionaries and use to hit a list (type) object then I used to get this error.

Its was a code error and made sure that I only added dictionary objects to that list and list typed object into the list, this solved my issue as well.

Writing Unicode text to a text file?

Deal exclusively with unicode objects as much as possible by decoding things to unicode objects when you first get them and encoding them as necessary on the way out.

If your string is actually a unicode object, you'll need to convert it to a unicode-encoded string object before writing it to a file:

foo = u'?, ?, ?, ? ?, ?, ?, ?, ?, and ?.'
f = open('test', 'w')
f.write(foo.encode('utf8'))
f.close()

When you read that file again, you'll get a unicode-encoded string that you can decode to a unicode object:

f = file('test', 'r')
print f.read().decode('utf8')

Difference between float and decimal data type

MySQL recently changed they way they store the DECIMAL type. In the past they stored the characters (or nybbles) for each digit comprising an ASCII (or nybble) representation of a number - vs - a two's complement integer, or some derivative thereof.

The current storage format for DECIMAL is a series of 1,2,3,or 4-byte integers whose bits are concatenated to create a two's complement number with an implied decimal point, defined by you, and stored in the DB schema when you declare the column and specify it's DECIMAL size and decimal point position.

By way of example, if you take a 32-bit int you can store any number from 0 - 4,294,967,295. That will only reliably cover 999,999,999, so if you threw out 2 bits and used (1<<30 -1) you'd give up nothing. Covering all 9-digit numbers with only 4 bytes is more efficient than covering 4 digits in 32 bits using 4 ASCII characters, or 8 nybble digits. (a nybble is 4-bits, allowing values 0-15, more than is needed for 0-9, but you can't eliminate that waste by going to 3 bits, because that only covers values 0-7)

The example used on the MySQL online docs uses DECIMAL(18,9) as an example. This is 9 digits ahead of and 9 digits behind the implied decimal point, which as explained above requires the following storage.

As 18 8-bit chars: 144 bits

As 18 4-bit nybbles: 72 bits

As 2 32-bit integers: 64 bits

Currently DECIMAL supports a max of 65 digits, as DECIMAL(M,D) where the largest value for M allowed is 65, and the largest value of D allowed is 30.

So as not to require chunks of 9 digits at a time, integers smaller than 32-bits are used to add digits using 1,2 and 3 byte integers. For some reason that defies logic, signed, instead of unsigned ints were used, and in so doing, 1 bit gets thrown out, resulting in the following storage capabilities. For 1,2 and 4 byte ints the lost bit doesn't matter, but for the 3-byte int it's a disaster because an entire digit is lost due to the loss of that single bit.

With an 7-bit int: 0 - 99

With a 15-bit int: 0 - 9,999

With a 23-bit int: 0 - 999,999 (0 - 9,999,999 with a 24-bit int)

1,2,3 and 4-byte integers are concatenated together to form a "bit pool" DECIMAL uses to represent the number precisely as a two's complement integer. The decimal point is NOT stored, it is implied.

This means that no ASCII to int conversions are required of the DB engine to convert the "number" into something the CPU recognizes as a number. No rounding, no conversion errors, it's a real number the CPU can manipulate.

Calculations on this arbitrarily large integer must be done in software, as there is no hardware support for this kind of number, but these libraries are very old and highly optimized, having been written 50 years ago to support IBM 370 Fortran arbitrary precision floating point data. They're still a lot slower than fixed-sized integer algebra done with CPU integer hardware, or floating point calculations done on the FPU.

In terms of storage efficiency, because the exponent of a float is attached to each and every float, specifying implicitly where the decimal point is, it is massively redundant, and therefore inefficient for DB work. In a DB you already know where the decimal point is to go up front, and every row in the table that has a value for a DECIMAL column need only look at the 1 & only specification of where that decimal point is to be placed, stored in the schema as the arguments to a DECIMAL(M,D) as the implication of the M and the D values.

The many remarks found here about which format is to be used for various kinds of applications are correct, so I won't belabor the point. I took the time to write this here because whoever is maintaining the linked MySQL online documentation doesn't understand any of the above and after rounds of increasingly frustrating attempts to explain it to them I gave up. A good indication of how poorly they understood what they were writing is the very muddled and almost indecipherable presentation of the subject matter.

As a final thought, if you have need of high-precision floating point computation, there've been tremendous advances in floating point code in the last 20 years, and hardware support for 96-bit and Quadruple Precision float are right around the corner, but there are good arbitrary precision libraries out there if manipulation of the stored value is important.

How to preview an image before and after upload?

                    #######################
                    ###  the img page   ###
                    #######################


<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $('#f').live('change' ,function(){
            $('#fo').ajaxForm({target: '#d'}).submit();
        });
    });
</script>
<form id="fo" name="fo" action="nextimg.php" enctype="multipart/form-data" method="post">
    <input type="file" name="f" id="f" value="start upload" />
    <input type="submit" name="sub" value="upload" />
</form>
<div id="d"></div>


                    #############################
                    ###    the nextimg page   ###
                    #############################


<?php
     $name=$_FILES['f']['name'];
     $tmp=$_FILES['f']['tmp_name'];
     $new=time().$name;
     $new="upload/".$new;
     move_uploaded_file($tmp,$new);
     if($_FILES['f']['error']==0)
     {
?>
     <h1>PREVIEW</h1><br /><img src="<?php echo $new;?>" width="100" height="100" />
<?php
     }
?>

Execute a shell function with timeout

This function uses only builtins

  • Maybe consider evaling "$*" instead of running $@ directly depending on your needs

  • It starts a job with the command string specified after the first arg that is the timeout value and monitors the job pid

  • It checks every 1 seconds, bash supports timeouts down to 0.01 so that can be tweaked

  • Also if your script needs stdin, read should rely on a dedicated fd (exec {tofd}<> <(:))

  • Also you might want to tweak the kill signal (the one inside the loop) which is default to -15, you might want -9

## forking is evil
timeout() {
    to=$1; shift
    $@ & local wp=$! start=0
     while kill -0 $wp; do
        read -t 1
        start=$((start+1))
        if [ $start -ge $to ]; then
            kill $wp && break
        fi
    done
}

How to initialize HashSet values by construction?

If you have only one value and want to get an immutable set this would be enough:

Set<String> immutableSet = Collections.singleton("a");

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

func funcationname()
{

    var parameters = [String:String]()
    let apiToken = "Bearer \(UserDefaults.standard.string(forKey: "vAuthToken")!)"
    let headers = ["Vauthtoken":apiToken]
    let mobile = "\(ApiUtillity.sharedInstance.getUserData(key: "mobile"))"
    parameters = ["first_name":First_name,"last_name":last_name,"email":Email,"mobile_no":mobile]

    print(parameters)
    ApiUtillity.sharedInstance.showSVProgressHUD(text: "Loading...")
    let URL1 = ApiUtillity.sharedInstance.API(Join: "user/update_profile")
    let url = URL(string: URL1.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
    var urlRequest = URLRequest(url: url!)
    urlRequest.httpMethod = "POST"
    urlRequest.allHTTPHeaderFields = headers
    Alamofire.upload(multipartFormData: { (multipartFormData) in

        multipartFormData.append(self.imageData_pf_pic, withName: "profile_image", fileName: "image.jpg", mimeType: "image/jpg")


        for (key, value) in parameters {

            multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
        }

    }, with: urlRequest) { (encodingResult) in

        switch encodingResult {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                if let JSON = response.result.value {
                    print("JSON: \(JSON)")
                    let status = (JSON as AnyObject).value(forKey: "status") as! Int
                    let sts = Int(status)
                    if sts == 200
                    {
                        ApiUtillity.sharedInstance.dismissSVProgressHUD()
                        let UserData = ((JSON as AnyObject).value(forKey: "data") as! NSDictionary)
                        ApiUtillity.sharedInstance.setUserData(data: UserData)


                    }
                    else
                    {
                        ApiUtillity.sharedInstance.dismissSVProgressHUD()

                        let ErrorDic:NSDictionary = (JSON as AnyObject).value(forKey: "message") as! NSDictionary

                        let Errormobile_no = ErrorDic.value(forKey: "mobile_no") as? String
                        let Erroremail = ErrorDic.value(forKey: "email") as? String

                        if Errormobile_no?.count == nil
                        {}
                        else
                        {
                            ApiUtillity.sharedInstance.dismissSVProgressHUDWithError(error: Errormobile_no!)
                        }
                        if Erroremail?.count == nil
                        {}
                        else
                        {
                            ApiUtillity.sharedInstance.dismissSVProgressHUDWithError(error: Erroremail!)
                        }
                    }

                }

            }

        case .failure(let encodingError):
            ApiUtillity.sharedInstance.dismissSVProgressHUD()
            print(encodingError)
        }

    }
}

How to position one element relative to another with jQuery?

Something like this?

$(menu).css("top", targetE1.y + "px"); 
$(menu).css("left", targetE1.x - widthOfMenu + "px");

How to get Git to clone into current directory

The solution for Windows is to clone the repository to other folder and then copy and paste to the original location or just copy the .git invisible folder.

How to print color in console using System.out.println?

To strikeout:

public static final String ANSI_STRIKEOUT_BLACK = "\u001B[30;9m";
public static final String ANSI_STRIKEOUT_RED = "\u001B[31;9m";
public static final String ANSI_STRIKEOUT_GREEN = "\u001B[32;9m";
public static final String ANSI_STRIKEOUT_YELLOW = "\u001B[33;9m";
public static final String ANSI_STRIKEOUT_BLUE = "\u001B[34;9m";
public static final String ANSI_STRIKEOUT_PURPLE = "\u001B[35;9m";
public static final String ANSI_STRIKEOUT_CYAN = "\u001B[36;9m";
public static final String ANSI_STRIKEOUT_WHITE = "\u001B[37;9m";

Sass Variable in CSS calc() function

Interpolate:

body
    height: calc(100% - #{$body_padding})

For this case, border-box would also suffice:

body
    box-sizing: border-box
    height: 100%
    padding-top: $body_padding

Unable to connect to SQL Server instance remotely

Open mysql server configuration manager. Click SQL server services, on the right side choose the server you've created during installation(by default its state is stopped), click once on it and a play button should appear on the tool bar, then click on this play button, wait till its state turn into "running". Now your good. Switch back to the sql server management studio; switch the "server type" to "database engine" and "authentification" to "sql server authentification", the default login is "sa", and the password is your password that you've choose on creating the server. Now your good to work.

How are booleans formatted in Strings in Python?

If you want True False use:

"%s %s" % (True, False)

because str(True) is 'True' and str(False) is 'False'.

or if you want 1 0 use:

"%i %i" % (True, False)

because int(True) is 1 and int(False) is 0.

Changing route doesn't scroll to top in the new page

I have finally gotten what I needed.

I needed to scroll to the top, but wanted some transitions not to

You can control this on a route-by-route level.
I'm combining the above solution by @wkonkel and adding a simple noScroll: true parameter to some route declarations. Then I'm catching that in the transition.

All in all: This floats to the top of the page on new transitions, it doesn't float to the top on Forward / Back transitions, and it allows you to override this behavior if necessary.

The code: (previous solution plus an extra noScroll option)

  // hack to scroll to top when navigating to new URLS but not back/forward
  let wrap = function(method) {
    let orig = $window.window.history[method];
    $window.window.history[method] = function() {
      let retval = orig.apply(this, Array.prototype.slice.call(arguments));
      if($state.current && $state.current.noScroll) {
        return retval;
      }
      $anchorScroll();
      return retval;
    };
  };
  wrap('pushState');
  wrap('replaceState');

Put that in your app.run block and inject $state... myApp.run(function($state){...})

Then, If you don't want to scroll to the top of the page, create a route like this:

.state('someState', {
  parent: 'someParent',
  url: 'someUrl',
  noScroll : true // Notice this parameter here!
})

Selenium and xpath: finding a div with a class/id and verifying text inside

To verify this:-

<div class="Caption">
  Model saved
</div>

Write this -

//div[contains(@class, 'Caption') and text()='Model saved']

And to verify this:-

<div id="alertLabel" class="gwt-HTML sfnStandardLeftMargin sfnStandardRightMargin sfnStandardTopMargin">
  Save to server successful
</div>

Write this -

//div[@id='alertLabel' and text()='Save to server successful']

Add tooltip to font awesome icon

codepen Is perhaps a helpful example.

<div class="social-icons">
  <a class="social-icon social-icon--codepen">
    <i class="fa fa-codepen"></i>
    <div class="tooltip">Codepen</div>
</div>

body {  
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
}

/* Color Variables */
$color-codepen: #000;

/* Social Icon Mixin */
@mixin social-icon($color) {
  background: $color;
  background: linear-gradient(tint($color, 5%), shade($color, 5%));
  border-bottom: 1px solid shade($color, 20%);
  color: tint($color, 50%);

  &:hover {
    color: tint($color, 80%);
    text-shadow: 0px 1px 0px shade($color, 20%);
  }

  .tooltip {
    background: $color;
    background: linear-gradient(tint($color, 15%), $color);
    color: tint($color, 80%);

    &:after {
      border-top-color: $color;
    }
  }
}

/* Social Icons */
.social-icons {
  display: flex;
}

.social-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  width: 80px;
  height: 80px;
  margin: 0 0.5rem;
  border-radius: 50%;
  cursor: pointer;
  font-family: "Helvetica Neue", "Helvetica", "Arial", sans-serif;
  font-size: 2.5rem;
  text-decoration: none;
  text-shadow: 0 1px 0 rgba(0,0,0,0.2);
  transition: all 0.15s ease;

  &:hover {
    color: #fff;

    .tooltip {
      visibility: visible;
      opacity: 1;
      transform: translate(-50%, -150%);
    }
  }

  &:active {
    box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.5) inset;
  }

  &--codepen { @include social-icon($color-codepen); }

  i {
    position: relative;
    top: 1px;
  }
}

/* Tooltips */
.tooltip {
  display: block;
  position: absolute;
  top: 0;
  left: 50%;
  padding: 0.8rem 1rem;
  border-radius: 3px;
  font-size: 0.8rem;
  font-weight: bold;
  opacity: 0;
  pointer-events: none;
  text-transform: uppercase;
  transform: translate(-50%, -100%);
  transition: all 0.3s ease;
  z-index: 1;

  &:after {
    display: block;
    position: absolute;
    bottom: 0;
    left: 50%;
    width: 0;
    height: 0;
    content: "";
    border: solid;
    border-width: 10px 10px 0 10px;
    border-color: transparent;
    transform: translate(-50%, 100%);
  }
}

How to convert an NSTimeInterval (seconds) into minutes

Here's a Swift version:

func durationsBySecond(seconds s: Int) -> (days:Int,hours:Int,minutes:Int,seconds:Int) {
    return (s / (24 * 3600),(s % (24 * 3600)) / 3600, s % 3600 / 60, s % 60)
}

Can be used like this:

let (d,h,m,s) = durationsBySecond(seconds: duration)
println("time left: \(d) days \(h) hours \(m) minutes \(s) seconds")

How to correctly iterate through getElementsByClassName

I followed Alohci's recommendation of looping in reverse because it's a live nodeList. Here's what I did for those who are curious...

  var activeObjects = documents.getElementsByClassName('active'); // a live nodeList

  //Use a reverse-loop because the array is an active NodeList
  while(activeObjects.length > 0) {
    var lastElem = activePaths[activePaths.length-1]; //select the last element

    //Remove the 'active' class from the element.  
    //This will automatically update the nodeList's length too.
    var className = lastElem.getAttribute('class').replace('active','');
    lastElem.setAttribute('class', className);
  }

Function overloading in Javascript - Best practices

There is no real function overloading in JavaScript since it allows to pass any number of parameters of any type. You have to check inside the function how many arguments have been passed and what type they are.

R memory management / cannot allocate vector of size n Mb

The simplest way to sidestep this limitation is to switch to 64 bit R.

Using Tkinter in python to edit the title bar

I found this works:

window = Tk()
window.title('Window')

Maybe this helps?

C# winforms combobox dynamic autocomplete

I wrote something like this ....

private void frmMain_Load(object sender, EventArgs e)
{
    cboFromCurrency.Items.Clear();
    cboComboBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
    cboComboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
    // Load data in comboBox => cboComboBox1.DataSource = .....
    // Other things
}

private void cboComboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    cboComboBox1.DroppedDown = false;
}

That's all (Y)

Passing a varchar full of comma delimited values to a SQL Server IN function

Thanks, for your function I Used IT........................ This is my EXAMPLE

**UPDATE [RD].[PurchaseOrderHeader]
SET     [DispatchCycleNumber] ='10'
 WHERE  OrderNumber in(select * FROM XA.fn_SplitOrderIDs(@InvoiceNumberList))**


CREATE FUNCTION [XA].[fn_SplitOrderIDs]
(
    @OrderList varchar(500)
)
RETURNS 
@ParsedList table
(
    OrderID int
)
AS
BEGIN
    DECLARE @OrderID varchar(10), @Pos int

    SET @OrderList = LTRIM(RTRIM(@OrderList))+ ','
    SET @Pos = CHARINDEX(',', @OrderList, 1)

    IF REPLACE(@OrderList, ',', '') <> ''
    BEGIN
        WHILE @Pos > 0
        BEGIN
                SET @OrderID = LTRIM(RTRIM(LEFT(@OrderList, @Pos - 1)))
                IF @OrderID <> ''
                BEGIN
                        INSERT INTO @ParsedList (OrderID) 
                        VALUES (CAST(@OrderID AS int)) --Use Appropriate conversion
                END
                SET @OrderList = RIGHT(@OrderList, LEN(@OrderList) - @Pos)
                SET @Pos = CHARINDEX(',', @OrderList, 1)

        END
    END 
    RETURN
END

Run as java application option disabled in eclipse

You can try and add a new run configuration: Run -> Run Configurations ... -> Select "Java Appliction" and click "New".

Alternatively use the shortcut: place the cursor in the class, then press Alt + Shift + X to open up a context menu, then press J.

List all indexes on ElasticSearch server?

To get all the details in Kibana.
 GET /_cat/indices




To get names only in Kibana.
GET /_cat/indices?h=index

Without using Kibana ,You can send a get request in postman or type this in Brower so you will get a list of indices names

http://localhost:9200/_cat/indices?h=index

enter image description here enter image description here

What is lexical scope?

I understand them through examples. :)

First, lexical scope (also called static scope), in C-like syntax:

void fun()
{
    int x = 5;

    void fun2()
    {
        printf("%d", x);
    }
}

Every inner level can access its outer levels.

There is another way, called dynamic scope used by the first implementation of Lisp, again in a C-like syntax:

void fun()
{
    printf("%d", x);
}

void dummy1()
{
    int x = 5;

    fun();
}

void dummy2()
{
    int x = 10;

    fun();
}

Here fun can either access x in dummy1 or dummy2, or any x in any function that call fun with x declared in it.

dummy1();

will print 5,

dummy2();

will print 10.

The first one is called static because it can be deduced at compile-time, and the second is called dynamic because the outer scope is dynamic and depends on the chain call of the functions.

I find static scoping easier for the eye. Most languages went this way eventually, even Lisp (can do both, right?). Dynamic scoping is like passing references of all variables to the called function.

As an example of why the compiler can not deduce the outer dynamic scope of a function, consider our last example. If we write something like this:

if(/* some condition */)
    dummy1();
else
    dummy2();

The call chain depends on a run time condition. If it is true, then the call chain looks like:

dummy1 --> fun()

If the condition is false:

dummy2 --> fun()

The outer scope of fun in both cases is the caller plus the caller of the caller and so on.

Just to mention that the C language does not allow nested functions nor dynamic scoping.

How to use forEach in vueJs?

The keyword you need is flatten an array. Modern javascript array comes with a flat method. You can use third party libraries like underscorejs in case you need to support older browsers.

Native Ex:

var response=[1,2,3,4[12,15],[20,21]];
var data=response.flat(); //data=[1,2,3,4,12,15,20,21]

Underscore Ex:

var response=[1,2,3,4[12,15],[20,21]];
var data=_.flatten(response);

What is path of JDK on Mac ?

Have a look and see if the the JDK is at:

Library/Java/JavaVirtualMachines/ Or /System/Library/Java/JavaVirtualMachines/

Check this earlier SO post: JDK on OSX 10.7 Lion

How to save an image locally using Python whose URL address I already know?

Using requests library

import requests
import shutil,os

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
}
currentDir = os.getcwd()
path = os.path.join(currentDir,'Images')#saving images to Images folder

def ImageDl(url):
    attempts = 0
    while attempts < 5:#retry 5 times
        try:
            filename = url.split('/')[-1]
            r = requests.get(url,headers=headers,stream=True,timeout=5)
            if r.status_code == 200:
                with open(os.path.join(path,filename),'wb') as f:
                    r.raw.decode_content = True
                    shutil.copyfileobj(r.raw,f)
            print(filename)
            break
        except Exception as e:
            attempts+=1
            print(e)


ImageDl(url)

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

#!/usr/bin/python

# encoding=utf8

Try This to starting of python file

Replace an element into a specific position of a vector

See an example here: http://www.cplusplus.com/reference/stl/vector/insert/ eg.:



...
vector::iterator iterator1;

  iterator1= vec1.begin();
  vec1.insert ( iterator1+i , vec2[i] );

// This means that at position "i" from the beginning it will insert the value from vec2 from position i

Your first approach was replacing the values from vec1[i] with the values from vec2[i]

Getting all selected checkboxes in an array

_x000D_
_x000D_
function selectedValues(ele){_x000D_
  var arr = [];_x000D_
  for(var i = 0; i < ele.length; i++){_x000D_
    if(ele[i].type == 'checkbox' && ele[i].checked){_x000D_
      arr.push(ele[i].value);_x000D_
    }_x000D_
  }_x000D_
  return arr;_x000D_
}
_x000D_
_x000D_
_x000D_

What is std::move(), and when should it be used?

std::move itself doesn't really do much. I thought that it called the moved constructor for an object, but it really just performs a type cast (casting an lvalue variable to an rvalue so that the said variable can be passed as an argument to a move constructor or assignment operator).

So std::move is just used as a precursor to using move semantics. Move semantics is essentially an efficient way for dealing with temporary objects.

Consider Object A = B + C + D + E + F;

This is nice looking code, but E + F produces a temporary object. Then D + temp produces another temporary object and so on. In each normal "+" operator of a class, deep copies occur.

For example

Object Object::operator+ (const Object& rhs) {
    Object temp (*this);
    // logic for adding
    return temp;
}

The creation of the temporary object in this function is useless - these temporary objects will be deleted at the end of the line anyway as they go out of scope.

We can rather use move semantics to "plunder" the temporary objects and do something like

 Object& Object::operator+ (Object&& rhs) {
     // logic to modify rhs directly
     return rhs;
 }

This avoids needless deep copies being made. With reference to the example, the only part where deep copying occurs is now E + F. The rest uses move semantics. The move constructor or assignment operator also needs to be implemented to assign the result to A.

jQuery DIV click, with anchors

$("div.clickable").click( function(event) { window.location = $(this).attr("url"); event.preventDefault(); });

List method to delete last element in list as well as all elements

To delete the last element from the list just do this.

a = [1,2,3,4,5]
a = a[:-1]
#Output [1,2,3,4] 

How to show changed file name only with git log?

This gives almost what you need:

git log --stat --oneline

Commit id + short one line still remains, followed by list of changed files by that commit.

Makefile: How to correctly include header file and its directory?

These lines in your makefile,

INC_DIR = ../StdCUtil
CFLAGS=-c -Wall -I$(INC_DIR)
DEPS = split.h

and this line in your .cpp file,

#include "StdCUtil/split.h"

are in conflict.

With your makefile in your source directory and with that -I option you should be using #include "split.h" in your source file, and your dependency should be ../StdCUtil/split.h.

Another option:

INC_DIR = ../StdCUtil
CFLAGS=-c -Wall -I$(INC_DIR)/..  # Ugly!
DEPS = $(INC_DIR)/split.h

With this your #include directive would remain as #include "StdCUtil/split.h".

Yet another option is to place your makefile in the parent directory:

root
  |____Makefile
  |
  |___Core
  |     |____DBC.cpp
  |     |____Lock.cpp
  |     |____Trace.cpp
  |
  |___StdCUtil
        |___split.h

With this layout it is common to put the object files (and possibly the executable) in a subdirectory that is parallel to your Core and StdCUtil directories. Object, for example. With this, your makefile becomes:

INC_DIR = StdCUtil
SRC_DIR = Core
OBJ_DIR = Object
CFLAGS  = -c -Wall -I.
SRCS = $(SRC_DIR)/Lock.cpp $(SRC_DIR)/DBC.cpp $(SRC_DIR)/Trace.cpp
OBJS = $(OBJ_DIR)/Lock.o $(OBJ_DIR)/DBC.o $(OBJ_DIR)/Trace.o
# Note: The above will soon get unwieldy.
# The wildcard and patsubt commands will come to your rescue.

DEPS = $(INC_DIR)/split.h
# Note: The above will soon get unwieldy.
# You will soon want to use an automatic dependency generator.


all: $(OBJS)

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
  $(CC) $(CFLAGS) -c $< -o $@

$(OBJ_DIR)/Trace.o: $(DEPS)

How to forcefully set IE's Compatibility Mode off from the server-side?

Changing my header to the following solve the problem:

<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

Difference between exit() and sys.exit() in Python

If I use exit() in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing. See here

But sys.exit() is better in this case. It closes the program and doesn't create any dialogue box.

Import Maven dependencies in IntelliJ IDEA

When importing the project, select pom.xml instead of the project directory. It should work.

wamp server does not start: Windows 7, 64Bit

Check your apache error log. I had this error "[error] (OS 5)Access is denied. : could not open transfer log file C:/wamp/logs/access.log. Unable to open logs" Then I rename my "access.log" to other name, you can delete if you don't need/never see your access log. Then restart your apache service. This happen because the file size too big. I think if you trying to open this file using notepad, it will not open, I tried to open that before. Hope it help.

How to show progress bar while loading, using ajax

I know that are already many answers written for this solution however I want to show another javascript method (dependent on JQuery) in which you simply need to include ONLY a single JS File without any dependency on CSS or Gif Images in your code and that will take care of all progress bar related animations that happens during Ajax Request. You need to simnply pass javascript function like this

var objGlobalEvent = new RegisterGlobalEvents(true, "");

Preview of Fiddle Loader Type

Here is the working fiddle for the code. https://jsfiddle.net/vibs2006/c7wukc41/3/

grep a file, but show several surrounding lines?

$ grep thestring thefile -5

-5 gets you 5 lines above and below the match 'thestring' is equivalent to -C 5 or -A 5 -B 5.

How to restrict UITextField to take only numbers in Swift?

I have edited Raj Joshi's version to allow one dot or one comma:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let inverseSet = CharacterSet(charactersIn:"0123456789").inverted
    let components = string.components(separatedBy: inverseSet)
    let filtered = components.joined(separator: "")

    if filtered == string {
        return true
    } else {
        if string == "." || string == "," {
            let countDots = textField.text!.components(separatedBy:".").count - 1
            let countCommas = textField.text!.components(separatedBy:",").count - 1

            if countDots == 0 && countCommas == 0 {
                return true
            } else {
                return false
            }
        } else  {
            return false
        }
    }
}

how to read xml file from url using php

It is working for me. I think you probably need to use urlencode() on each of the components of $map_url.

What does "ulimit -s unlimited" do?

ulimit -s unlimited lets the stack grow unlimited.

This may prevent your program from crashing if you write programs by recursion, especially if your programs are not tail recursive (compilers can "optimize" those), and the depth of recursion is large.

How can I determine the character encoding of an excel file?

For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:

"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
    <sheets>
        <sheet name="MySheet1" sheetId="1" r:id="rId1" /> 
        <sheet name="MySheet2" sheetId="2" r:id="rId2" /> 
    </sheets>
</workbook>

The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" ?> 
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <sheetData>
        <row r="1">
            <c r="A1">
                <v>100</v> 
            </c>
        </row>
    </sheetData>
</worksheet>

"

Detection of cell encodings:

https://metacpan.org/pod/Spreadsheet::ParseExcel::Cell

http://forums.asp.net/t/1608228.aspx/1

How do I pass command line arguments to a Node.js program?

To normalize the arguments like a regular javascript function would receive, I do this in my node.js shell scripts:

var args = process.argv.slice(2);

Note that the first arg is usually the path to nodejs, and the second arg is the location of the script you're executing.

How to disable editing of elements in combobox for c#?

Yow can change the DropDownStyle in properties to DropDownList. This will not show the TextBox for filter.

DropDownStyle Property
(Screenshot provided by FUSION CHA0S.)

Convert float to std::string in C++

You can use std::to_string in C++11

float val = 2.5;
std::string my_val = std::to_string(val);

What is the most efficient string concatenation method in python?

One Year later, let's test mkoistinen's answer with python 3.4.3:

  • plus 0.963564149000 (95.83% as fast)
  • join 0.923408469000 (100.00% as fast)
  • form 1.501130934000 (61.51% as fast)
  • intp 1.019677452000 (90.56% as fast)

Nothing changed. Join is still the fastest method. With intp being arguably the best choice in terms of readability you might want to use intp nevertheless.

ES6 map an array of objects, to return an array of objects with new keys

You just need to wrap object in ()

_x000D_
_x000D_
var arr = [{_x000D_
  id: 1,_x000D_
  name: 'bill'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

How to extract elements from a list using indices in Python?

I think you're looking for this:

elements = [10, 11, 12, 13, 14, 15]
indices = (1,1,2,1,5)

result_list = [elements[i] for i in indices]    

Android splash screen image sizes to fit all devices

Edited solution that will make your SplashScreen look great on all APIs including API21 to API23

If you are only targeting APIs24+ you can simply scale down your vector drawable directly in its xml file like so:

<vector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:aapt="http://schemas.android.com/aapt"
android:viewportWidth="640"
android:viewportHeight="640"
android:width="240dp"
android:height="240dp">
<path
    android:pathData="M320.96 55.9L477.14 345L161.67 345L320.96 55.9Z"
    android:strokeColor="#292929"
    android:strokeWidth="24" />
</vector>

in the code above I am rescaling a drawable I drew on a 640x640 canvas to be 240x240. then i just put it in my splash screen drawable like so and it works great:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" android:opacity="opaque"
android:paddingBottom="20dp" android:paddingRight="20dp" android:paddingLeft="20dp" android:paddingTop="20dp">

<!-- The background color, preferably the same as your normal theme -->
<item>
    <shape>
        <size android:height="120dp" android:width="120dp"/>
        <solid android:color="@android:color/white"/>
    </shape>
</item>

<!-- Your product logo - 144dp color version of your app icon -->
<item
    android:drawable="@drawable/logo_vect"
    android:gravity="center">

</item>
</layer-list>

my code is actually only drawing the triangle in the picture at the bottom but here you see what you can achieve with this. Resolution is finally great as opposed to the pixelated edges I was getting when using bitmap. so use a vector drawable by all means (there is a site called vectr that I used to create mine without the hasle of downloading specialized software).

EDIT in order to make it work also on API21-22-23

While the solution above works for devices runing API24+ I got really disappointed after installing my app a device running API22. I noticed that the splashscreen was again trying to fill the entire view and looking like shit. After tearing my eyebrows out for half a day I finally brute-forced a solution by sheer willpower.

you need to create a second file named exactly like the splashscreen xml (lets say splash_screen.xml) and place it into 2 folders called drawable-v22 and drawable-v21 that you will create in the res/ folder (in order to see them you have to change your project view from Android to Project). This serves to tell your phone to redirect to files placed in those folders whenever the relevant device runs an API corresponding to the -vXX suffix in the drawable folder, see this link. place the following code in the Layer-list of the splash_screen.xml file that you create in these folders:

<item>
<shape>
    <size android:height="120dp" android:width="120dp"/>
    <solid android:color="@android:color/white"/>
</shape>
</item>

<!-- Your product logo - 144dp color version of your app icon -->
<item android:gravity="center">
    <bitmap android:gravity="center"
        android:src="logo_vect"/>

</item>

these is how the folders look

For some reason for these APIs you have to wrap your drawable in a bitmap in order to make it work and jet the final result looks the same. The issue is that you have to use the aproach with the aditional drawable folders as the second version of the splash_screen.xml file will lead to your splash screen not being shown at all on devices running APIs higher than 23. You might also have to place the first version of the splash_screen.xml into drawable-v24 as android defaults to the closest drawable-vXX folder it can find for resources. hope this helps

my splashscreen

jQuery function to get all unique elements from an array?

Just use this code as the basis of a simple JQuery plugin.

$.extend({
    distinct : function(anArray) {
       var result = [];
       $.each(anArray, function(i,v){
           if ($.inArray(v, result) == -1) result.push(v);
       });
       return result;
    }
});

Use as so:

$.distinct([0,1,2,2,3]);

Selecting with complex criteria from pandas.DataFrame

Sure! Setup:

>>> import pandas as pd
>>> from random import randint
>>> df = pd.DataFrame({'A': [randint(1, 9) for x in range(10)],
                   'B': [randint(1, 9)*10 for x in range(10)],
                   'C': [randint(1, 9)*100 for x in range(10)]})
>>> df
   A   B    C
0  9  40  300
1  9  70  700
2  5  70  900
3  8  80  900
4  7  50  200
5  9  30  900
6  2  80  700
7  2  80  400
8  5  80  300
9  7  70  800

We can apply column operations and get boolean Series objects:

>>> df["B"] > 50
0    False
1     True
2     True
3     True
4    False
5    False
6     True
7     True
8     True
9     True
Name: B
>>> (df["B"] > 50) & (df["C"] == 900)
0    False
1    False
2     True
3     True
4    False
5    False
6    False
7    False
8    False
9    False

[Update, to switch to new-style .loc]:

And then we can use these to index into the object. For read access, you can chain indices:

>>> df["A"][(df["B"] > 50) & (df["C"] == 900)]
2    5
3    8
Name: A, dtype: int64

but you can get yourself into trouble because of the difference between a view and a copy doing this for write access. You can use .loc instead:

>>> df.loc[(df["B"] > 50) & (df["C"] == 900), "A"]
2    5
3    8
Name: A, dtype: int64
>>> df.loc[(df["B"] > 50) & (df["C"] == 900), "A"].values
array([5, 8], dtype=int64)
>>> df.loc[(df["B"] > 50) & (df["C"] == 900), "A"] *= 1000
>>> df
      A   B    C
0     9  40  300
1     9  70  700
2  5000  70  900
3  8000  80  900
4     7  50  200
5     9  30  900
6     2  80  700
7     2  80  400
8     5  80  300
9     7  70  800

Note that I accidentally typed == 900 and not != 900, or ~(df["C"] == 900), but I'm too lazy to fix it. Exercise for the reader. :^)

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

This is surely an encoding problem. You have a different encoding in your database and in your website and this fact is the cause of the problem. Also if you ran that command you have to change the records that are already in your tables to convert those character in UTF-8.

Update: Based on your last comment, the core of the problem is that you have a database and a data source (the CSV file) which use different encoding. Hence you can convert your database in UTF-8 or, at least, when you get the data that are in the CSV, you have to convert them from UTF-8 to latin1.

You can do the convertion following this articles:

Click outside menu to close in jquery

The stopPropagation options are bad because they can interfere with other event handlers including other menus that might have attached close handlers to the HTML element.

Here is a simple solution based on user2989143's answer:

$('html').click(function(event) {
    if ($(event.target).closest('#menu-container, #menu-activator').length === 0) {
        $('#menu-container').hide();
    }
});

ERROR: Cannot open source file " "

This was the top result when googling "cannot open source file" so I figured I would share what my issue was since I had already included the correct path.

I'm not sure about other IDEs or compilers, but least for Visual Studio, make sure there isn't a space in your list of include directories. I had put a space between the ; of the last entry and the beginning of my new entry which then caused Visual Studio to disregard my inclusion.

Skipping Iterations in Python

Something like this?

for i in xrange( someBigNumber ):
    try:
        doSomethingThatMightFail()
    except SomeException, e:
        continue
    doSomethingWhenNothingFailed()

matplotlib savefig in jpeg format

Just install pillow with pip install pillow and it will work.

Tools to search for strings inside files without indexing

I'm a fan of the Find-In-Files dialog in Notepad++. Bonus: It's free.

enter image description here

python inserting variable string as file name

you can do something like

filename = "%s.csv" % name
f = open(filename , 'wb')

or f = open('%s.csv' % name, 'wb')

Xcode 9 error: "iPhone has denied the launch request"

For me it was due to xcode getting confused on what device profile to use. I used Apple Configurator 2 with below steps.

  1. Open Apple Configurator
  2. select device
  3. Actions
  4. Remove
  5. Profiles
  6. Select Old Unwanted Profiles
  7. Click "Remove Profiles"

After waiting for couple minutes unwanted profiles were removed. And rerun of application didnt have the error while launching.

Selecting distinct values from a JSON

This is a great spot for a reduce

var uniqueArray = o.DATA.reduce(function (a, d) {
       if (a.indexOf(d.name) === -1) {
         a.push(d.name);
       }
       return a;
    }, []);

Failure [INSTALL_FAILED_ALREADY_EXISTS] when I tried to update my application

With my Android 5 tablet, every time I attempt to use adb, to install a signed release apk, I get the [INSTALL_FAILED_ALREADY_EXISTS] error.

I have to uninstall the debug package first. But, I cannot uninstall using the device's Application Manager!

If do uninstall the debug version with the Application Manager, then I have to re-run the debug build variant from Android Studio, then uninstall it using adb uninstall com.example.mypackagename

Finally, I can use adb install myApp.apk to install the signed release apk.

how to write procedure to insert data in to the table in phpmyadmin?

Try this-

CREATE PROCEDURE simpleproc (IN name varchar(50),IN user_name varchar(50),IN branch varchar(50))
BEGIN
    insert into student (name,user_name,branch) values (name ,user_name,branch);
END

filtering a list using LINQ

We should have the projects which include (at least) all the filtered tags, or said in a different way, exclude the ones which doesn't include all those filtered tags. So we can use Linq Except to get those tags which are not included. Then we can use Count() == 0 to have only those which excluded no tags:

var res = projects.Where(p => filteredTags.Except(p.Tags).Count() == 0);

Or we can make it slightly faster with by replacing Count() == 0 with !Any():

var res = projects.Where(p => !filteredTags.Except(p.Tags).Any());

install beautiful soup using pip

import os

os.system("pip install beautifulsoup4")

or

import subprocess

exe = subprocess.Popen("pip install beautifulsoup4")

exe_out = exe.communicate()

print(exe_out)

How to create user for a db in postgresql?

Create the user with a password :

http://www.postgresql.org/docs/current/static/sql-createuser.html

CREATE USER name [ [ WITH ] option [ ... ] ]

where option can be:

      SUPERUSER | NOSUPERUSER
    | CREATEDB | NOCREATEDB
    | CREATEROLE | NOCREATEROLE
    | CREATEUSER | NOCREATEUSER
    | INHERIT | NOINHERIT
    | LOGIN | NOLOGIN
    | REPLICATION | NOREPLICATION
    | CONNECTION LIMIT connlimit
    | [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password'
    | VALID UNTIL 'timestamp'
    | IN ROLE role_name [, ...]
    | IN GROUP role_name [, ...]
    | ROLE role_name [, ...]
    | ADMIN role_name [, ...]
    | USER role_name [, ...]
    | SYSID uid

Then grant the user rights on a specific database :

http://www.postgresql.org/docs/current/static/sql-grant.html

Example :

grant all privileges on database db_name to someuser;

How to get screen dimensions as pixels in Android

Using the following code in Activity.

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int wwidth = metrics.widthPixels;

What is the difference between 127.0.0.1 and localhost

The main difference is that the connection can be made via Unix Domain Socket, as stated here: localhost vs. 127.0.0.1

How to specify jackson to only use fields - preferably globally

If you want a way to do this globally without worrying about the configuration of your ObjectMapper, you can create your own annotation:

@Target({ElementType.ANNOTATION_TYPE, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonAutoDetect(
        getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE,
        setterVisibility = JsonAutoDetect.Visibility.NONE, fieldVisibility = JsonAutoDetect.Visibility.NONE,
        creatorVisibility = JsonAutoDetect.Visibility.NONE
)
public @interface JsonExplicit {
}

Now you just have to annotate your classes with @JsonExplicit and you're good to go!

Also make sure to edit the above call to @JsonAutoDetect to make sure you have the values set to what works with your program.

Credit to https://stackoverflow.com/a/13408807 for helping me find out about @JacksonAnnotationsInside

Get type name without full namespace

make use of (Type Properties)

 Name   Gets the name of the current member. (Inherited from MemberInfo.)
 Example : typeof(T).Name;

How to return a specific element of an array?

You code should look like this:

public int getElement(int[] arrayOfInts, int index) {
    return arrayOfInts[index];
}

Main points here are method return type, it should match with array elements type and if you are working from main() - this method must be static also.

How can I get the list of files in a directory using C or C++?

This implementation realizes your purpose, dynamically filling an array of strings with the content of the specified directory.

int exploreDirectory(const char *dirpath, char ***list, int *numItems) {
    struct dirent **direntList;
    int i;
    errno = 0;

    if ((*numItems = scandir(dirpath, &direntList, NULL, alphasort)) == -1)
        return errno;

    if (!((*list) = malloc(sizeof(char *) * (*numItems)))) {
        fprintf(stderr, "Error in list allocation for file list: dirpath=%s.\n", dirpath);
        exit(EXIT_FAILURE);
    }

    for (i = 0; i < *numItems; i++) {
        (*list)[i] = stringDuplication(direntList[i]->d_name);
    }

    for (i = 0; i < *numItems; i++) {
        free(direntList[i]);
    }

    free(direntList);

    return 0;
}

image.onload event and browser cache

I found that you can just do this in Chrome:

  $('.onload-fadein').each(function (k, v) {
    v.onload = function () {
        $(this).animate({opacity: 1}, 2000);
    };
    v.src = v.src;
});

Setting the .src to itself will trigger the onload event.

How to push a docker image to a private repository

Ref: dock.docker.com

This topic provides basic information about deploying and configuring a registry

Run a local registry

Before you can deploy a registry, you need to install Docker on the host.

Use a command like the following to start the registry container:

start_registry.sh

#!/bin/bash

docker run -d \
  -p 5000:5000 \
  --restart=always \
  --name registry \
  -v /data/registry:/var/lib/registry \
  registry:2

Copy an image from Docker Hub to your registry

  1. Pull the ubuntu:16.04 image from Docker Hub.

    $ docker pull ubuntu:16.04
    
  2. Tag the image as localhost:5000/my-ubuntu. This creates an additional tag for the existing image. When the first part of the tag is a hostname and port, Docker interprets this as the location of a registry, when pushing.

    $ docker tag ubuntu:16.04 localhost:5000/my-ubuntu
    
  3. Push the image to the local registry running at localhost:5000:

    $ docker push localhost:5000/my-ubuntu
    
  4. Remove the locally-cached images. This does not remove the localhost:5000/my-ubuntu image from your registry.

    $ docker image remove ubuntu:16.04
    $ docker image remove localhost:5000/my-ubuntu
    
  5. Pull the localhost:5000/my-ubuntu image from your local registry.

    $ docker pull localhost:5000/my-ubuntu
    
Deploy a plain HTTP registry

According to docs.docker.com, this is very insecure and is not recommended.

  1. Edit the daemon.json file, whose default location is /etc/docker/daemon.json on Linux or C:\ProgramData\docker\config\daemon.json on Windows Server. If you use Docker for Mac or Docker for Windows, click Docker icon -> Preferences -> Daemon, add in the insecure registry.

    If the daemon.json file does not exist, create it. Assuming there are no other settings in the file, it should have the following contents:

    {
      "insecure-registries" : ["myregistrydomain.com:5000"]
    }
    

    With insecure registries enabled, Docker goes through the following steps:

    • First, try using HTTPS.
      • If HTTPS is available but the certificate is invalid, ignore the error about the certificate.
      • If HTTPS is not available, fall back to HTTP.
  2. Restart Docker for the changes to take effect.

How do I list all remote branches in Git 1.7+?

git branch -a | grep remotes/*

Rails: Can't verify CSRF token authenticity when making a POST request

The simplest solution for the problem is do standard things in your controller or you can directely put it into ApplicationController

class ApplicationController < ActionController::Base protect_from_forgery with: :exception, prepend: true end

Swift: print() vs println() vs NSLog()

To add to Rob's answer, since iOS 10.0, Apple has introduced an entirely new "Unified Logging" system that supersedes existing logging systems (including ASL and Syslog, NSLog), and also surpasses existing logging approaches in performance, thanks to its new techniques including log data compression and deferred data collection.

From Apple:

The unified logging system provides a single, efficient, performant API for capturing messaging across all levels of the system. This unified system centralizes the storage of log data in memory and in a data store on disk.

Apple highly recommends using os_log going forward to log all kinds of messages, including info, debug, error messages because of its much improved performance compared to previous logging systems, and its centralized data collection allowing convenient log and activity inspection for developers. In fact, the new system is likely so low-footprint that it won't cause the "observer effect" where your bug disappears if you insert a logging command, interfering the timing of the bug to happen.

Performance of Activity Tracing, now part of the new Unified Logging system

You can learn more about this in details here.

To sum it up: use print() for your personal debugging for convenience (but the message won't be logged when deployed on user devices). Then, use Unified Logging (os_log) as much as possible for everything else.

How to add multiple font files for the same font?

/*
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# dejavu sans
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*/
/*default version*/
@font-face {
    font-family: 'DejaVu Sans';
    src: url('dejavu/DejaVuSans.ttf'); /* IE9 Compat Modes */
    src: 
        local('DejaVu Sans'),
        local('DejaVu-Sans'), /* Duplicated name with hyphen */
        url('dejavu/DejaVuSans.ttf') 
        format('truetype');
}
/*bold version*/
@font-face {
    font-family: 'DejaVu Sans';
    src: url('dejavu/DejaVuSans-Bold.ttf'); 
    src: 
        local('DejaVu Sans'),
        local('DejaVu-Sans'),
        url('dejavu/DejaVuSans-Bold.ttf') 
        format('truetype');
    font-weight: bold;
}
/*italic version*/
@font-face {
    font-family: 'DejaVu Sans';
    src: url('dejavu/DejaVuSans-Oblique.ttf'); 
    src: 
        local('DejaVu Sans'),
        local('DejaVu-Sans'),
        url('dejavu/DejaVuSans-Oblique.ttf') 
        format('truetype');
    font-style: italic;
}
/*bold italic version*/
@font-face {
    font-family: 'DejaVu Sans';
    src: url('dejavu/DejaVuSans-BoldOblique.ttf'); 
    src: 
        local('DejaVu Sans'),
        local('DejaVu-Sans'),
        url('dejavu/DejaVuSans-BoldOblique.ttf') 
        format('truetype');
    font-weight: bold;
    font-style: italic;
}

How do I simulate a low bandwidth, high latency environment?

Charles

I came across Charles the web debugging proxy application and had great success in emulating network latency. It works on Windows, Mac, and Linux.

Charles on Mac

Bandwidth throttle / Bandwidth simulator

Charles can be used to adjust the bandwidth and latency of your Internet connection. This enables you to simulate modem conditions using your high-speed connection.

The bandwidth may be throttled to any arbitrary bytes per second. This enables any connection speed to be simulated.

The latency may also be set to any arbitrary number of milliseconds. The latency delay simulates the latency experienced on slower connections, that is the delay between making a request and the request being received at the other end.

DummyNet

You could also use vmware to run BSD or Linux and try this article (DummyNet) or this one.

Is it ok having both Anacondas 2.7 and 3.5 installed in the same time?

Yes you can.

You don't have to download both Anaconda.

Only you need to download one of the version of Anaconda and need activate other version of Anaconda python.

If you have Python 3, you can set up a Python 2 kernel like this;

python2 -m pip install ipykernel

python2 -m ipykernel install --user

If you have Python 2,

python3 -m pip install ipykernel

python3 -m ipykernel install --user

Then you will be able to see both version of Python!

If you are using Anaconda Spyder then you should swap version here:

enter image description here

If you are using Jupiter then check here:

enter image description here

Note: If your Jupiter or Anaconda already open after installation you need to restart again. Then you will be able to see.

How do I get the path of the Python script I am running in?

os.path.realpath(__file__) will give you the path of the current file, resolving any symlinks in the path. This works fine on my mac.

Failed to load resource: the server responded with a status of 404 (Not Found) error in server

By default, IUSR account is used for anonymous user.

All you need to do is:

IIS -> Authentication --> Set Anonymous Authentication to Application Pool Identity.

Problem solved :)

Inline style to act as :hover in CSS

If that <p> tag is created from JavaScript, then you do have another option: use JSS to programmatically insert stylesheets into the document head. It does support '&:hover'. https://cssinjs.org/

Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

To speed things up, I would take advantage of the fact that you are not asked to find an arbitrary image/object, but specifically one with the Coca-Cola logo. This is significant because this logo is very distinctive, and it should have a characteristic, scale-invariant signature in the frequency domain, particularly in the red channel of RGB. That is to say, the alternating pattern of red-to-white-to-red encountered by a horizontal scan line (trained on a horizontally aligned logo) will have a distinctive "rhythm" as it passes through the central axis of the logo. That rhythm will "speed up" or "slow down" at different scales and orientations, but will remain proportionally equivalent. You could identify/define a few dozen such scanlines, both horizontally and vertically through the logo and several more diagonally, in a starburst pattern. Call these the "signature scan lines."

Signature scan line

Searching for this signature in the target image is a simple matter of scanning the image in horizontal strips. Look for a high-frequency in the red-channel (indicating moving from a red region to a white one), and once found, see if it is followed by one of the frequency rhythms identified in the training session. Once a match is found, you will instantly know the scan-line's orientation and location in the logo (if you keep track of those things during training), so identifying the boundaries of the logo from there is trivial.

I would be surprised if this weren't a linearly-efficient algorithm, or nearly so. It obviously doesn't address your can-bottle discrimination, but at least you'll have your logos.

(Update: for bottle recognition I would look for coke (the brown liquid) adjacent to the logo -- that is, inside the bottle. Or, in the case of an empty bottle, I would look for a cap which will always have the same basic shape, size, and distance from the logo and will typically be all white or red. Search for a solid color eliptical shape where a cap should be, relative to the logo. Not foolproof of course, but your goal here should be to find the easy ones fast.)

(It's been a few years since my image processing days, so I kept this suggestion high-level and conceptual. I think it might slightly approximate how a human eye might operate -- or at least how my brain does!)

Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

If you look at the chain of exceptions, the problem is

Caused by: org.hibernate.PropertyNotFoundException: Could not find a setter for property salt in class backend.Account

The problem is that the method Account.setSalt() works fine when you create an instance but not when you retrieve an instance from the database. This is because you don't want to create a new salt each time you load an Account.

To fix this, create a method setSalt(long) with visibility private and Hibernate will be able to set the value (just a note, I think it works with Private, but you might need to make it package or protected).

How can I declare a two dimensional string array?

string[,] Tablero = new string[3,3];

Modulo operator with negative values

The sign in such cases (i.e when one or both operands are negative) is implementation-defined. The spec says in §5.6/4 (C++03),

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.

That is all the language has to say, as far as C++03 is concerned.

Add unique constraint to combination of two columns

In my case, I needed to allow many inactives and only one combination of two keys active, like this:

UUL_USR_IDF  UUL_UND_IDF    UUL_ATUAL
137          18             0
137          19             0
137          20             1
137          21             0

This seems to work:

CREATE UNIQUE NONCLUSTERED INDEX UQ_USR_UND_UUL_USR_IDF_UUL_ATUAL
ON USER_UND(UUL_USR_IDF, UUL_ATUAL)
WHERE UUL_ATUAL = 1;

Here are my test cases:

SELECT * FROM USER_UND WHERE UUL_USR_IDF = 137

insert into USER_UND values (137, 22, 1) --I CAN NOT => Cannot insert duplicate key row in object 'dbo.USER_UND' with unique index 'UQ_USR_UND_UUL_USR_IDF_UUL_ATUAL'. The duplicate key value is (137, 1).
insert into USER_UND values (137, 23, 0) --I CAN
insert into USER_UND values (137, 24, 0) --I CAN

DELETE FROM USER_UND WHERE UUL_USR_ID = 137

insert into USER_UND values (137, 22, 1) --I CAN
insert into USER_UND values (137, 27, 1) --I CAN NOT => Cannot insert duplicate key row in object 'dbo.USER_UND' with unique index 'UQ_USR_UND_UUL_USR_IDF_UUL_ATUAL'. The duplicate key value is (137, 1).
insert into USER_UND values (137, 28, 0) --I CAN
insert into USER_UND values (137, 29, 0) --I CAN

How to terminate a python subprocess launched with shell=True

I could do it using

from subprocess import Popen

process = Popen(command, shell=True)
Popen("TASKKILL /F /PID {pid} /T".format(pid=process.pid))

it killed the cmd.exe and the program that i gave the command for.

(On Windows)

"Eliminate render-blocking CSS in above-the-fold content"

Hi For jQuery You can only use like this

Use async and type="text/javascript" only

How do I exit a while loop in Java?

Finding a while...do construct with while(true) in my code would make my eyes bleed. Use a standard while loop instead:

while (obj != null){
    ...
}

And take a look at the link Yacoby provided in his answer, and this one too. Seriously.

The while and do-while Statements

How to query all the GraphQL type fields without writing a long query?

Unfortunately what you'd like to do is not possible. GraphQL requires you to be explicit about specifying which fields you would like returned from your query.

Comparing two vectors in an if statement

all is one option:

> A <- c("A", "B", "C", "D")
> B <- A
> C <- c("A", "C", "C", "E")

> all(A==B)
[1] TRUE
> all(A==C)
[1] FALSE

But you may have to watch out for recycling:

> D <- c("A","B","A","B")
> E <- c("A","B")
> all(D==E)
[1] TRUE
> all(length(D)==length(E)) && all(D==E)
[1] FALSE

The documentation for length says it currently only outputs an integer of length 1, but that it may change in the future, so that's why I wrapped the length test in all.

Rendering HTML elements to <canvas>

According to the HTML specification you can't access the elements of the Canvas. You can get its context, and draw in it manipulate it, but that is all.

BUT, you can put both the Canvas and the html element in the same div with a aposition: relative and then set the canvas and the other element to position: absolute. This ways they will be on the top of each other. Then you can use the left and right CSS properties to position the html element.

If the element doesn't shows up, maybe the canvas is before it, so use the z-index CSS property to bring it before the canvas.

How to set the JSTL variable value in javascript?

Just don't. Don't write code with code. Write a JSON object or a var somewhere but for the love of a sensible HTTP divide, don't write JavaScript functions or methods hardcoded with vars/properties provided by JSTL. Generating JSON is cool. It ends there or your UI dev hates you.

Imagine if you had to dig into JavaScript to find something that was setting parameters in the middle of a class that originated on the client-side. It's awful. Pass data back and forth. Handle the data. But don't try to generate actual code.

What are the proper permissions for an upload folder with PHP/Apache?

You can create a new group with both the apache user and FTP user as members and then make the permission on the upload folder 775. This should give both the apache and FTP users the ability to write to the files in the folder but keep everyone else from modifying them.

Eclipse won't compile/run java file

I was also in the same problem, check your build path in eclipse by Right Click on Project > build path > configure build path

Now check for Excluded Files, it should not have your file specified there by any means or by regex.

Cheers!image for error fix view, see Excluded field

Using PHP Replace SPACES in URLS with %20

Use urlencode() rather than trying to implement your own. Be lazy.

Use of exit() function

on unix like operating systems exit belongs to group of system calls. system calls are special calls which enable user code (your code) to call kernel code. so exit call makes some OS specific clean-up actions before returning control to OS, it terminates the program.

#include <stdlib.h>

// example 1
int main(int argc, char *argv){
  exit(EXIT_SUCCESS);
}

// example 2
int main(int argc, char *argv){
  return 0;
}

Some compilers will give you the same opcode from both of these examples but some won't. For example opcode from first function will not include any kind of stack positioning opcode which will be included in the second example like for any other function. You could compile both examples and disassemble them and you will see the difference.

You can use exit from any part of your code and be sure that process terminates. Don't forget to include integer parameter.

Git fast forward VS no fast forward merge

I can give an example commonly seen in project.

Here, option --no-ff (i.e. true merge) creates a new commit with multiple parents, and provides a better history tracking. Otherwise, --ff (i.e. fast-forward merge) is by default.

$ git checkout master
$ git checkout -b newFeature
$ ...
$ git commit -m 'work from day 1'
$ ...
$ git commit -m 'work from day 2'
$ ...
$ git commit -m 'finish the feature'
$ git checkout master
$ git merge --no-ff newFeature -m 'add new feature'
$ git log
// something like below
commit 'add new feature'         // => commit created at merge with proper message
commit 'finish the feature'
commit 'work from day 2'
commit 'work from day 1'
$ gitk                           // => see details with graph

$ git checkout -b anotherFeature        // => create a new branch (*)
$ ...
$ git commit -m 'work from day 3'
$ ...
$ git commit -m 'work from day 4'
$ ...
$ git commit -m 'finish another feature'
$ git checkout master
$ git merge anotherFeature       // --ff is by default, message will be ignored
$ git log
// something like below
commit 'work from day 4'
commit 'work from day 3'
commit 'add new feature'
commit 'finish the feature'
commit ...
$ gitk                           // => see details with graph

(*) Note that here if the newFeature branch is re-used, instead of creating a new branch, git will have to do a --no-ff merge anyway. This means fast forward merge is not always eligible.

Headers and client library minor version mismatch

For WHM and cPanel, some versions need to explicty set mysqli to build.

Using WHM, under CENTOS 6.9 xen pv [dc] v68.0.27, one needed to rebuild Apache/PHP by looking at all options and select mysqli to build. The default was to build the deprecated mysql. Now the depreciation messages are gone and one is ready for future MySQL upgrades.

IntelliJ does not show 'Class' when we right click and select 'New'

The directory or one of the parent directories must be marked as Source Root (In this case, it appears in blue).

If this is not the case, right click your root source directory -> Mark As -> Source Root.

how to insert date and time in oracle?

You are doing everything right by using a to_date function and specifying the time. The time is there in the database. The trouble is just that when you select a column of DATE datatype from the database, the default format mask doesn't show the time. If you issue a

alter session set nls_date_format = 'dd/MON/yyyy hh24:mi:ss'

or something similar including a time component, you will see that the time successfully made it into the database.

How do I get the path to the current script with Node.js?

You can use process.env.PWD to get the current app folder path.

How do I view the list of functions a Linux shared library is exporting?

On a MAC, you need to use nm *.o | c++filt, as there is no -C option in nm.

Deserializing a JSON file with JavaScriptSerializer()

  public class User : List<UserData>
    {

        public int id { get; set; }
        public string screen_name { get; set; }

    }


    string json = client.DownloadString(url);
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    var Data = serializer.Deserialize<List<UserData>>(json);

How to insert an object in an ArrayList at a specific position

To insert value into ArrayList at particular index, use:

public void add(int index, E element)

This method will shift the subsequent elements of the list. but you can not guarantee the List will remain sorted as the new Object you insert may sit on the wrong position according to the sorting order.


To replace the element at the specified position, use:

public E set(int index, E element)

This method replaces the element at the specified position in the list with the specified element, and returns the element previously at the specified position.

Two Divs next to each other, that then stack with responsive change

Do like this:

HTML

<div class="parent">
    <div class="child"></div>
    <div class="child"></div>
</div>

CSS

.parent{
    width: 400px;
    background: red;
}
.child{
    float: left;
    width:200px;
    background:green;
    height: 100px;
}

This is working jsfiddle. Change child width to more then 200px and they will stack.

Bash array with spaces in elements

Not exactly an answer to the quoting/escaping problem of the original question but probably something that would actually have been more useful for the op:

unset FILES
for f in 2011-*.jpg; do FILES+=("$f"); done
echo "${FILES[@]}"

Where of course the expression would have to be adopted to the specific requirement (e.g. *.jpg for all or 2001-09-11*.jpg for only the pictures of a certain day).

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

A BLOB can be 65535 bytes (64 KB) maximum.

If you need more consider using:

  • a MEDIUMBLOB for 16777215 bytes (16 MB)

  • a LONGBLOB for 4294967295 bytes (4 GB).

See Storage Requirements for String Types for more info.

Multiple commands on a single line in a Windows batch file

Use:

echo %time% & dir & echo %time%

This is, from memory, equivalent to the semi-colon separator in bash and other UNIXy shells.

There's also && (or ||) which only executes the second command if the first succeeded (or failed), but the single ampersand & is what you're looking for here.


That's likely to give you the same time however since environment variables tend to be evaluated on read rather than execute.

You can get round this by turning on delayed expansion:

pax> cmd /v:on /c "echo !time! & ping 127.0.0.1 >nul: & echo !time!"
15:23:36.77
15:23:39.85

That's needed from the command line. If you're doing this inside a script, you can just use setlocal:

@setlocal enableextensions enabledelayedexpansion
@echo off
echo !time! & ping 127.0.0.1 >nul: & echo !time!
endlocal

Java says FileNotFoundException but file exists

The code itself is working correctly. The problem is, that the program working path is pointing to other place than you think.

Use this line and see where the path is:

System.out.println(new File(".").getAbsoluteFile());

Floating point vs integer calculations on modern hardware

I ran a test that just added 1 to the number instead of rand(). Results (on an x86-64) were:

  • short: 4.260s
  • int: 4.020s
  • long long: 3.350s
  • float: 7.330s
  • double: 7.210s

PHP Unset Array value effect on other indexes

The keys are not shuffled or renumbered. The unset() key is simply removed and the others remain.

$a = array(1,2,3,4,5);
unset($a[2]);
print_r($a);

Array
(
    [0] => 1
    [1] => 2
    [3] => 4
    [4] => 5
)

How to create tar.gz archive file in Windows?

tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.

If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.

Hide Command Window of .BAT file that Executes Another .EXE File

Please use this one, the above does not work. I have tested in Window server 2003.

@echo off 
copy "C:\Remoting.config-Training" "C:\Remoting.config"
Start /I "" "C:\ThirdParty.exe"
exit

MySQL LIMIT on DELETE statement

simply use

DELETE FROM test WHERE 1= 1 LIMIT 10 

Is it possible to interactively delete matching search pattern in Vim?

The best way is probably to use:

:%s/phrase//gc

c asks for confirmation before each deletion. g allows multiple replacements to occur on the same line.

You can also just search using /phrase, select the next match with gn, and delete it with d.

Is having an 'OR' in an INNER JOIN condition a bad idea?

You can use UNION ALL instead.

SELECT mt.ID, mt.ParentID, ot.MasterID FROM dbo.MainTable AS mt Union ALL SELECT mt.ID, mt.ParentID, ot.MasterID FROM dbo.OtherTable AS ot

NULL vs nullptr (Why was it replaced?)

One reason: the literal 0 has a bad tendency to acquire the type int, e.g. in perfect argument forwarding or more in general as argument with templated type.

Another reason: readability and clarity of code.

How do you list the primary key of a SQL Server table?

Is using MS SQL Server you can do the following:

--List all tables primary keys
select * from information_schema.table_constraints
where constraint_type = 'Primary Key'

You can also filter on the table_name column if you want a specific table.

Adding up BigDecimals using Streams

Use this approach to sum the list of BigDecimal:

List<BigDecimal> values = ... // List of BigDecimal objects
BigDecimal sum = values.stream().reduce((x, y) -> x.add(y)).get();

This approach maps each BigDecimal as a BigDecimal only and reduces them by summing them, which is then returned using the get() method.

Here's another simple way to do the same summing:

List<BigDecimal> values = ... // List of BigDecimal objects
BigDecimal sum = values.stream().reduce(BigDecimal::add).get();

Update

If I were to write the class and lambda expression in the edited question, I would have written it as follows:

import java.math.BigDecimal;
import java.util.LinkedList;

public class Demo
{
  public static void main(String[] args)
  {
    LinkedList<Invoice> invoices = new LinkedList<>();
    invoices.add(new Invoice("C1", "I-001", BigDecimal.valueOf(.1), BigDecimal.valueOf(10)));
    invoices.add(new Invoice("C2", "I-002", BigDecimal.valueOf(.7), BigDecimal.valueOf(13)));
    invoices.add(new Invoice("C3", "I-003", BigDecimal.valueOf(2.3), BigDecimal.valueOf(8)));
    invoices.add(new Invoice("C4", "I-004", BigDecimal.valueOf(1.2), BigDecimal.valueOf(7)));

    // Java 8 approach, using Method Reference for mapping purposes.
    invoices.stream().map(Invoice::total).forEach(System.out::println);
    System.out.println("Sum = " + invoices.stream().map(Invoice::total).reduce((x, y) -> x.add(y)).get());
  }

  // This is just my style of writing classes. Yours can differ.
  static class Invoice
  {
    private String company;
    private String number;
    private BigDecimal unitPrice;
    private BigDecimal quantity;

    public Invoice()
    {
      unitPrice = quantity = BigDecimal.ZERO;
    }

    public Invoice(String company, String number, BigDecimal unitPrice, BigDecimal quantity)
    {
      setCompany(company);
      setNumber(number);
      setUnitPrice(unitPrice);
      setQuantity(quantity);
    }

    public BigDecimal total()
    {
      return unitPrice.multiply(quantity);
    }

    public String getCompany()
    {
      return company;
    }

    public void setCompany(String company)
    {
      this.company = company;
    }

    public String getNumber()
    {
      return number;
    }

    public void setNumber(String number)
    {
      this.number = number;
    }

    public BigDecimal getUnitPrice()
    {
      return unitPrice;
    }

    public void setUnitPrice(BigDecimal unitPrice)
    {
      this.unitPrice = unitPrice;
    }

    public BigDecimal getQuantity()
    {
      return quantity;
    }

    public void setQuantity(BigDecimal quantity)
    {
      this.quantity = quantity;
    }
  }
}

Postgresql column reference "id" is ambiguous

You need the table name/alias in the SELECT part (maybe (vg.id, name)) :

SELECT (vg.id, name) FROM v_groups vg 
inner join people2v_groups p2vg on vg.id = p2vg.v_group_id
where p2vg.people_id =0;

Importing a function from a class in another file?

If, like me, you want to make a function pack or something that people can download then it's very simple. Just write your function in a python file and save it as the name you want IN YOUR PYTHON DIRECTORY. Now, in your script where you want to use this, you type:

from FILE NAME import FUNCTION NAME

Note - the parts in capital letters are where you type the file name and function name.

Now you just use your function however it was meant to be.

Example:

FUNCTION SCRIPT - saved at C:\Python27 as function_choose.py

def choose(a):
  from random import randint
  b = randint(0, len(a) - 1)
  c = a[b]
  return(c)

SCRIPT USING FUNCTION - saved wherever

from function_choose import choose
list_a = ["dog", "cat", "chicken"]
print(choose(list_a))

OUTPUT WILL BE DOG, CAT, OR CHICKEN

Hoped this helped, now you can create function packs for download!

--------------------------------This is for Python 2.7-------------------------------------

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

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

For example In the official Facebook analytics guide

They clearly state that you should add the following dependency:

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

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

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

Facebook partial SDK options

How to call a method defined in an AngularJS directive?

A bit late, but this is a solution with the isolated scope and "events" to call a function in the directive. This solution is inspired by this SO post by satchmorun and adds a module and an API.

//Create module
var MapModule = angular.module('MapModule', []);

//Load dependency dynamically
angular.module('app').requires.push('MapModule');

Create an API to communicate with the directive. The addUpdateEvent adds an event to the event array and updateMap calls every event function.

MapModule.factory('MapApi', function () {
    return {
        events: [],

        addUpdateEvent: function (func) {
            this.events.push(func);
        },

        updateMap: function () {
            this.events.forEach(function (func) {
                func.call();
            });
        }
    }
});

(Maybe you have to add functionality to remove event.)

In the directive set a reference to the MapAPI and add $scope.updateMap as an event when MapApi.updateMap is called.

app.directive('map', function () {
    return {
        restrict: 'E', 
        scope: {}, 
        templateUrl: '....',
        controller: function ($scope, $http, $attrs, MapApi) {

            $scope.api = MapApi;

            $scope.updateMap = function () {
                //Update the map 
            };

            //Add event
            $scope.api.addUpdateEvent($scope.updateMap);

        }
    }
});

In the "main" controller add a reference to the MapApi and just call MapApi.updateMap() to update the map.

app.controller('mainController', function ($scope, MapApi) {

    $scope.updateMapButtonClick = function() {
        MapApi.updateMap();    
    };
}

Testing the type of a DOM element in JavaScript

Perhaps you'll have to check the nodetype too:

if(element.nodeType == 1){//element of type html-object/tag
  if(element.tagName=="a"){
    //this is an a-element
  }
  if(element.tagName=="div"){
    //this is a div-element
  }
}

Edit: Corrected the nodeType-value

How to make a 3D scatter plot in Python?

You can use matplotlib for this. matplotlib has a mplot3d module that will do exactly what you want.

from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
import random


fig = pyplot.figure()
ax = Axes3D(fig)

sequence_containing_x_vals = list(range(0, 100))
sequence_containing_y_vals = list(range(0, 100))
sequence_containing_z_vals = list(range(0, 100))

random.shuffle(sequence_containing_x_vals)
random.shuffle(sequence_containing_y_vals)
random.shuffle(sequence_containing_z_vals)

ax.scatter(sequence_containing_x_vals, sequence_containing_y_vals, sequence_containing_z_vals)
pyplot.show()

The code above generates a figure like:

matplotlib 3D image

Twitter bootstrap modal-backdrop doesn't disappear

Adding data-dismiss="modal" on any buttons in my modal worked for me. I wanted my button to call a function with angular to fire an ajax call AND close the modal so I added a .toggle() within the function and it worked well. (In my case I used a bootstrap modal and used some angular, not an actual modal controller).

<button type="button" class="btn btn-primary" data-dismiss="modal"
ng-click="functionName()"> Do Something </button>

$scope.functionName = function () {
angular.element('#modalId').toggle();
  $.ajax({ ajax call })
}

MSVCP120d.dll missing

I have found myself wasting time searching for a solution on this, and i suspect doing it again in future. So here's a note to myself and others who might find this useful.

If MSVCP120.DLL is missing, that means you have not installed Visual C++ Redistributable Packages for Visual Studio 2013 (x86 and x64). Install that, restart and you should find this file in c:\Windows\System32 .

Now if MSVCP120D.DLL is missing, this means that the application you are trying to run is built in Debug mode. As OP has mentioned, the debug version of the runtime is NOT distributable.

So what do we do?

Well, there is one option that I know of: Go to your Project's Debug configuration > C/C++ > Code Generation > Runtime Library and select Multi-threaded Debug (/MTd). This will statically link MSVCP120D.dll into your executable.

There is also a quick-fix if you just want to get something up quickly: Copy the MSVCP120D.DLL from sys32 (mine is C:\Windows\System32) folder. You may also need MSVCR120D.DLL.

Addendum to the quick fix: To reduce guesswork, you can use dependency walker. Open your application with dependency walker, and you'll see what dll files are needed.

For example, my recent application was built in Visual Studio 2015 (Windows 10 64-bit machine) and I am targeting it to a 32-bit Windows XP machine. Using dependency walker, my application (see screenshot) needs the following files:

  • opencv_*.dll <-- my own dll files (might also have dependency)
  • msvcp140d.dll <-- SysWOW64\msvcp140d.dll
  • kernel32.dll <-- SysWOW64\kernel32.dll
  • vcruntime140d.dll <-- SysWOW64\vcruntime140d.dll
  • ucrtbased.dll <-- SysWOW64\ucrtbased.dll

Aside from the opencv* files that I have built, I would also need to copy the system files from C:\Windows\SysWow64 (System32 for 32-bit).

You're welcome. :-)

Angular, Http GET with parameter?

Above solutions not helped me, but I resolve same issue by next way

private setHeaders(params) {      
        const accessToken = this.localStorageService.get('token');
        const reqData = {
            headers: {
                Authorization: `Bearer ${accessToken}`
            },
        };
        if(params) {
            let reqParams = {};        
            Object.keys(params).map(k =>{
                reqParams[k] = params[k];
            });
            reqData['params'] = reqParams;
        }
        return reqData;
    }

and send request

this.http.get(this.getUrl(url), this.setHeaders(params))

Its work with NestJS backend, with other I don't know.

How do I query for all dates greater than a certain date in SQL Server?

Try enclosing your date into a character string.

 select * 
 from dbo.March2010 A
 where A.Date >= '2010-04-01';

select and echo a single field from mysql db using PHP

Read the manual, it covers it very well: http://php.net/manual/en/function.mysql-query.php

Usually you do something like this:

while ($row = mysql_fetch_assoc($result)) {
  echo $row['firstname'];
  echo $row['lastname'];
  echo $row['address'];
  echo $row['age'];
}

C# Parsing JSON array of objects

Use newtonsoft like so:

using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;

class Program
{
    static void Main()
    {
        string json = "{'results':[{'SwiftCode':'','City':'','BankName':'Deutsche    Bank','Bankkey':'10020030','Bankcountry':'DE'},{'SwiftCode':'','City':'10891    Berlin','BankName':'Commerzbank Berlin (West)','Bankkey':'10040000','Bankcountry':'DE'}]}";

        var resultObjects = AllChildren(JObject.Parse(json))
            .First(c => c.Type == JTokenType.Array && c.Path.Contains("results"))
            .Children<JObject>();

        foreach (JObject result in resultObjects) {
            foreach (JProperty property in result.Properties()) {
                // do something with the property belonging to result
            }
        }
    }

    // recursively yield all children of json
    private static IEnumerable<JToken> AllChildren(JToken json)
    {
        foreach (var c in json.Children()) {
            yield return c;
            foreach (var cc in AllChildren(c)) {
                yield return cc;
            }
        }
    }
}

How to write UTF-8 in a CSV file

From your shell run:

pip2 install unicodecsv

And (unlike the original question) presuming you're using Python's built in csv module, turn
import csv into
import unicodecsv as csv in your code.

Can I use a case/switch statement with two variables?

I don't believe a switch/case is any faster than a series of if/elseif's. They do the same thing, but if/elseif's you can check multiple variables. You cannot use a switch/case on more than one value.

How do I set the selected item in a comboBox to match my string using C#?

For me this worked only:

foreach (ComboBoxItem cbi in someComboBox.Items)
{
    if (cbi.Content as String == "sometextIntheComboBox")
    {
        someComboBox.SelectedItem = cbi;
        break;
    }
}

MOD: and if You have your own objects as items set up in the combobox, then substitute the ComboBoxItem with one of them like:

foreach (Debitor d in debitorCombo.Items)
{
    if (d.Name == "Chuck Norris")
    {
        debitorCombo.SelectedItem = d;
        break;
    }
}

Convert CString to const char*

Note: This answer predates the Unicode requirement; see the comments.

Just cast it:

CString s;
const TCHAR* x = (LPCTSTR) s;

It works because CString has a cast operator to do exactly this.

Using TCHAR makes your code Unicode-independent; if you're not concerned about Unicode you can simply use char instead of TCHAR.

Scale the contents of a div by a percentage?

This cross-browser lib seems safer - just zoom and moz-transform won't cover as many browsers as jquery.transform2d's scale().

http://louisremi.github.io/jquery.transform.js/

For example

$('#div').css({ transform: 'scale(.5)' });

Update

OK - I see people are voting this down without an explanation. The other answer here won't work in old Safari (people running Tiger), and it won't work consistently in some older browsers - that is, it does scale things but it does so in a way that's either very pixellated or shifts the position of the element in a way that doesn't match other browsers.

http://www.browsersupport.net/CSS/zoom

Or just look at this question, which this one is likely just a dupe of:

complete styles for cross browser CSS zoom

Send raw ZPL to Zebra printer via USB

I found the answer... or at least, the easiest answer (if there are multiple). When I installed the printer, I renamed it to "ICS Label Printer". Here's how to change the options to allow pass-through ZPL commands:

  1. Right-click on the "ICS Label Printer" and choose "Properties".
  2. On the "General" tab, click on the "Printing Preferences..." button.
  3. On the "Advanced Setup" tab, click on the "Other" button.
  4. Make sure there is a check in the box labeled "Enable Passthrough Mode".
  5. Make sure the "Start sequence:" is "${".
  6. Make sure the "End sequence:" is "}$".
  7. Click on the "Close" button.
  8. Click on the "OK" button.
  9. Click on the "OK" button.

In my code, I just have to add "${" to the beginning of my ZPL and "}$" to the end and print it as plain text. This is with the "Windows driver for ZDesigner LP 2844-Z printer Version 2.6.42 (Build 2382)". Works like a charm!

Difference between a Structure and a Union

As you already state in your question, the main difference between union and struct is that union members overlay the memory of each other so that the sizeof of a union is the one , while struct members are laid out one after each other (with optional padding in between). Also an union is large enough to contain all its members, and have an alignment that fits all its members. So let's say int can only be stored at 2 byte addresses and is 2 bytes wide, and long can only be stored at 4 byte addresses and is 4 bytes long. The following union

union test {
    int a;
    long b;
}; 

could have a sizeof of 4, and an alignment requirement of 4. Both an union and a struct can have padding at the end, but not at their beginning. Writing to a struct changes only the value of the member written to. Writing to a member of an union will render the value of all other members invalid. You cannot access them if you haven't written to them before, otherwise the behavior is undefined. GCC provides as an extension that you can actually read from members of an union, even though you haven't written to them most recently. For an Operation System, it doesn't have to matter whether a user program writes to an union or to a structure. This actually is only an issue of the compiler.

Another important property of union and struct is, they allow that a pointer to them can point to types of any of its members. So the following is valid:

struct test {
    int a;
    double b;
} * some_test_pointer;

some_test_pointer can point to int* or double*. If you cast an address of type test to int*, it will point to its first member, a, actually. The same is true for an union too. Thus, because an union will always have the right alignment, you can use an union to make pointing to some type valid:

union a {
    int a;
    double b;
};

That union will actually be able to point to an int, and a double:

union a * v = (union a*)some_int_pointer;
*some_int_pointer = 5;
v->a = 10;
return *some_int_pointer;    

is actually valid, as stated by the C99 standard:

An object shall have its stored value accessed only by an lvalue expression that has one of the following types:

  • a type compatible with the effective type of the object
  • ...
  • an aggregate or union type that includes one of the aforementioned types among its members

The compiler won't optimize out the v->a = 10; as it could affect the value of *some_int_pointer (and the function will return 10 instead of 5).

How to get the changes on a branch in Git

With Git 2.30 (Q1 2021), "git diff A...B(man)" learned "git diff --merge-base A B(man), which is a longer short-hand to say the same thing.

Thus you can do this using git diff --merge-base <branch> HEAD. This should be equivalent to git diff <branch>...HEAD but without the confusion of having to use range-notation in a diff.

How to disable sort in DataGridView?

I was looking for a way to disable my already existing DataGridView and came across several answers. Oddly enough, the first few results on google were some very old topics. This being the earliest one of them, I decide to put my answer here.

private void dgvDetails_ColumnStateChanged(object sender, DataGridViewColumnStateChangedEventArgs e)
{
    e.Column.SortMode = DataGridViewColumnSortMode.NotSortable;
}

The description when you click on ColumStateChanged in the properties window is:

"Occurs when a column changes state, such as gaining or loosing focus"

Granted there are many ways to do this but I thought I'd add this one here. Can't say I found it anywhere else but then again I only read the first 5 topics I found.

Elegant Python function to convert CamelCase to snake_case?

There's an inflection library in the package index that can handle these things for you. In this case, you'd be looking for inflection.underscore():

>>> inflection.underscore('CamelCase')
'camel_case'

Error QApplication: no such file or directory

Well, It's a bit late for this but I've just started learning Qt and maybe this could help somebody out there:

If you're using Qt Creator then when you've started creating the project you were asked to choose a kit to be used with your project, Let's say you chose Desktop Qt <version-here> MinGW 64-bit. For Qt 5, If you opened the Qt folder of your installation, you'll find a folder with the version of Qt installed as its name inside it, here you can find the kits you can choose from.

You can go to /PATH/FOR/Qt/mingw<version>_64/include and here you'll find all the includes you can use in your program, just search for QApplication and you'll find it inside the folder QtWidgets, So you can use #include <QtWidgets/QApplication> since the path starts from the include folder.

The same goes for other headers if you're stuck with any and for other kits.

Note: "all the includes you can use" doesn't mean these are the only ones you can use, If you include iostream for example then the compiler will include it from /PATH/FOR/Qt/Tools/mingw<version>_64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/iostream

Remove old Fragment from fragment manager

If you want to replace a fragment with another, you should have added them dynamically, first of all. Fragments that are hard coded in XML, cannot be replaced.

// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

Refer this post: Replacing a fragment with another fragment inside activity group

Refer1: Replace a fragment programmatically

PyCharm import external library

Answer for PyCharm 2016.1 on OSX: (This is an update to the answer by @GeorgeWilliams993's answer above, but I don't have the rep yet to make comments.)

Go to Pycharm menu --> Preferences --> Project: (projectname) --> Project Interpreter

At the top is a popup for "Project Interpreter," and to the right of it is a button with ellipses (...) - click on this button for a different popup and choose "More" (or, as it turns out, click on the main popup and choose "Show All").

This shows a list of interpreters, with one selected. At the bottom of the screen are a set of tools... pick the rightmost one:

Show path for the selected interpreter button

Now you should see all the paths pycharm is searching to find imports, and you can use the "+" button at the bottom to add a new path.

I think the most significant difference from @GeorgeWilliams993's answer is that the gear button has been replaced by a set of ellipses. That threw me off.

Can I change the Android startActivity() transition animation?

Starting from API level 5 you can call overridePendingTransition immediately to specify an explicit transition animation:

startActivity();
overridePendingTransition(R.anim.hold, R.anim.fade_in);

or

finish();
overridePendingTransition(R.anim.hold, R.anim.fade_out);

How to fix HTTP 404 on Github Pages?

My pages also kept 404'ing. Contacted support, and they pointed out that the url is case sensitive; solved my issue.

Remove duplicated rows using dplyr

If you want to find the rows that are duplicated you can use find_duplicates from hablar:

library(dplyr)
library(hablar)

df <- tibble(a = c(1, 2, 2, 4),
             b = c(5, 2, 2, 8))

df %>% find_duplicates()

How to run a command in the background and get no output?

Run in a subshell to remove notifications and close STDOUT and STDERR:

(&>/dev/null script.sh &)

how to use free cloud database with android app?

As Wingman said, Google App Engine is a great solution for your scenario.

You can get some information about GAE+Android here: https://developers.google.com/eclipse/docs/appengine_connected_android

And from this Google IO 2012 session: http://www.youtube.com/watch?v=NU_wNR_UUn4

What is the LDF file in SQL Server?

ldf saves the log of the db, certainly doesn't saves any real data, but is very important for the proper function of the database.

You can however change the log model to the database to simple so this log does not grow too fast.

Check this for example.

Check here for reference.

How to click a href link using Selenium

To click() on the element with text as App Configuration you can use either of the following Locator Strategies:

  • linkText:

    driver.findElement(By.linkText("App Configuration")).click();
    
  • cssSelector:

    driver.findElement(By.cssSelector("a[href='/docs/configuration']")).click();
    
  • xpath:

    driver.findElement(By.xpath("//a[@href='/docs/configuration' and text()='App Configuration']")).click();
    

Ideally, to click() on the element you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:

  • linkText:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.linkText("App Configuration"))).click();
    
  • cssSelector:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a[href='/docs/configuration']"))).click();
    
  • xpath:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@href='/docs/configuration' and text()='App Configuration']"))).click();
    

References

You can find a couple of relevant detailed discussions in:

Proper way to make HTML nested list?

I prefer option two because it clearly shows the list item as the possessor of that nested list. I would always lean towards semantically sound HTML.

UIImage resize (Scale proportion)

I used this single line of code to create a new UIImage which is scaled. Set the scale and orientation params to achieve what you want. The first line of code just grabs the image.

    // grab the original image
    UIImage *originalImage = [UIImage imageNamed:@"myImage.png"];
    // scaling set to 2.0 makes the image 1/2 the size. 
    UIImage *scaledImage = 
                [UIImage imageWithCGImage:[originalImage CGImage] 
                              scale:(originalImage.scale * 2.0)
                                 orientation:(originalImage.imageOrientation)];

What does %~d0 mean in a Windows batch file?

The magic variables %n contains the arguments used to invoke the file: %0 is the path to the bat-file itself, %1 is the first argument after, %2 is the second and so on.

Since the arguments are often file paths, there is some additional syntax to extract parts of the path. ~d is drive, ~p is the path (without drive), ~n is the file name. They can be combined so ~dp is drive+path.

%~dp0 is therefore pretty useful in a bat: it is the folder in which the executing bat file resides.

You can also get other kinds of meta info about the file: ~t is the timestamp, ~z is the size.

Look here for a reference for all command line commands. The tilde-magic codes are described under for.

QR Code encoding and decoding using zxing

Maybe worth looking at QRGen, which is built on top of ZXing and supports UTF-8 with this kind of syntax:

// if using special characters don't forget to supply the encoding
VCard johnSpecial = new VCard("Jöhn D?e")
                        .setAdress("ëåäö? Sträät 1, 1234 Döestüwn");
QRCode.from(johnSpecial).withCharset("UTF-8").file();

jQuery checkbox checked state changed event

Just another solution

$('.checkbox_class').on('change', function(){ // on change of state
   if(this.checked) // if changed state is "CHECKED"
    {
        // do the magic here
    }
})

How to select top n rows from a datatable/dataview in ASP.NET

If you want the number of rows to be flexible, you can add row_number in the SQL. For SQL server:

SELECT ROW_NUMBER() OVER (ORDER BY myOrder) ROW_NUMBER, * FROM myTable

Then filter the datatable on row_number:

Dataview dv= new Dataview(dt, "ROW_NUMBER<=100", "", CurrentRows)

Logcat not displaying my log calls

If all else fails:

I did all the above things and couldn't figure out what was wrong,

Test with:

adb logcat

to figure out that my entries were infact in logcat, but twas adt's quirks.

Fix:

Restart eclipse

This was the only thing that fixed it.

How to sum up elements of a C++ vector?

Why perform the summation forwards when you can do it backwards? Given:

std::vector<int> v;     // vector to be summed
int sum_of_elements(0); // result of the summation

We can use subscripting, counting backwards:

for (int i(v.size()); i > 0; --i)
    sum_of_elements += v[i-1];

We can use range-checked "subscripting," counting backwards (just in case):

for (int i(v.size()); i > 0; --i)
    sum_of_elements += v.at(i-1);

We can use reverse iterators in a for loop:

for(std::vector<int>::const_reverse_iterator i(v.rbegin()); i != v.rend(); ++i)
    sum_of_elements += *i;

We can use forward iterators, iterating backwards, in a for loop (oooh, tricky!):

for(std::vector<int>::const_iterator i(v.end()); i != v.begin(); --i)
    sum_of_elements += *(i - 1);

We can use accumulate with reverse iterators:

sum_of_elems = std::accumulate(v.rbegin(), v.rend(), 0);

We can use for_each with a lambda expression using reverse iterators:

std::for_each(v.rbegin(), v.rend(), [&](int n) { sum_of_elements += n; });

So, as you can see, there are just as many ways to sum the vector backwards as there are to sum the vector forwards, and some of these are much more exciting and offer far greater opportunity for off-by-one errors.

Changing case in Vim

Visual select the text, then U for uppercase or u for lowercase. To swap all casing in a visual selection, press ~ (tilde).

Without using a visual selection, gU<motion> will make the characters in motion uppercase, or use gu<motion> for lowercase.

For more of these, see Section 3 in Vim's change.txt help file.

what is trailing whitespace and how can I handle this?

I have got similar pep8 warning W291 trailing whitespace

long_text = '''Lorem Ipsum is simply dummy text  <-remove whitespace
of the printing and typesetting industry.'''

Try to explore trailing whitespaces and remove them. ex: two whitespaces at the end of Lorem Ipsum is simply dummy text