Programs & Examples On #Mysql error 1051

Android - running a method periodically using postDelayed() call

Please check the below its working on my side in below code your handler will run after every 1 Second when you are on same activity

 HandlerThread handlerThread = new HandlerThread("HandlerThread");
                handlerThread.start();
                handler = new Handler(handlerThread.getLooper());
                runnable = new Runnable()
                {
                    @Override
                    public void run()
                    {

                            handler.postDelayed(this, 1000);
                        }
                };
                handler.postDelayed(runnable, 1000);

Use of exit() function

The exit function is declared in the stdlib header, so you need to have

#include <stdlib.h>

at the top of your program to be able to use exit.

Note also that exit takes an integer argument, so you can't call it like exit(), you have to call as exit(0) or exit(42). 0 usually means your program completed successfully, and nonzero values are used as error codes.

There are also predefined macros EXIT_SUCCESS and EXIT_FAILURE, e.g. exit(EXIT_SUCCESS);

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

Also your server might just be closed. On a Mac, navigate to mySQL preference panel through the spotlight. When there, check the box to start your server when your computer starts and start the server.

Check if int is between two numbers

COBOL allows that (I am sure some other languages do as well). Java inherited most of it's syntax from C which doesn't allow it.

AngularJS routing without the hash '#'

Lets write answer that looks simple and short

In Router at end add html5Mode(true);

app.config(function($routeProvider,$locationProvider) {

    $routeProvider.when('/home', {
        templateUrl:'/html/home.html'
    });

    $locationProvider.html5Mode(true);
})

In html head add base tag

<html>
<head>
    <meta charset="utf-8">    
    <base href="/">
</head>

thanks To @plus- for detailing the above answer

What does the star operator mean, in a function call?

One small point: these are not operators. Operators are used in expressions to create new values from existing values (1+2 becomes 3, for example. The * and ** here are part of the syntax of function declarations and calls.

When is a CDATA section necessary within a script tag?

It to ensure that XHTML validation works correctly when you have JavaScript embedded in your page, rather than externally referenced.

XHTML requires that your page strictly conform to XML markup requirements. Since JavaScript may contain characters with special meaning, you must wrap it in CDATA to ensure that validation does not flag it as malformed.

With HTML pages on the web you can just include the required JavaScript between and tags. When you validate the HTML on your web page the JavaScript content is considered to be CDATA (character data) that is therefore ignored by the validator. The same is not true if you follow the more recent XHTML standards in setting up your web page. With XHTML the code between the script tags is considered to be PCDATA (parsed character data) which is therefore processed by the validator.

Because of this, you can't just include JavaScript between the script tags on your page without 'breaking' your web page (at least as far as the validator is concerned).

You can learn more about CDATA here, and more about XHTML here.

How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

This actually worked for me:

private String uri2filename() {

    String ret;
    String scheme = uri.getScheme();

    if (scheme.equals("file")) {
        ret = uri.getLastPathSegment();
    }
    else if (scheme.equals("content")) {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            ret = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
        }
   }
   return ret;
}

Display MessageBox in ASP

If you want to do it from code behind, try this:

System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Message');", true);

AngularJS : ng-click not working

For ng-click working properly you need define your controller after angularjs script binding and use it via $scope.

Where do I find the current C or C++ standard documents?

PDF versions of the standard

As of 1st September 2014, the best locations by price for C and C++ standards documents in PDF are:

You cannot usually get old revisions of a standard (any standard) directly from the standards bodies shortly after a new edition of the standard is released. Thus, standards for C89, C90, C99, C++98, C++03 will be hard to find for purchase from a standards body. If you need an old revision of a standard, check Techstreet as one possible source. For example, it can still provide the Canadian version CAN/CSA-ISO/IEC 9899:1990 standard in PDF, for a fee.

Non-PDF electronic versions of the standard

Print versions of the standard

Print copies of the standards are available from national standards bodies and ISO but are very expensive.

If you want a hardcopy of the C90 standard for much less money than above, you may be able to find a cheap used copy of Herb Schildt's book The Annotated ANSI Standard at Amazon, which contains the actual text of the standard (useful) and commentary on the standard (less useful - it contains several dangerous and misleading errors).

The C99 and C++03 standards are available in book form from Wiley and the BSI (British Standards Institute):

Standards committee draft versions (free)

The working drafts for future standards are often available from the committee websites:

If you want to get drafts from the current or earlier C/C++ standards, there are some available for free on the internet:

For C:

(Almost the same as ANSI X3.159-198 (C89) except for the frontmatter and section numbering. Note that the conversion between ANSI and ISO/IEC Standard is seen inside this document, the document refers to its name as "ANSI/ISO: 9899/99" although this isn't the right name of the later made standard of it, the right name is "ISO/IEC 9899:1990")

For C++:

Note that these documents are not the same as the standard, though the versions just prior to the meetings that decide on a standard are usually very close to what is in the final standard. The FCD (Final Committee Draft) versions are password protected; you need to be on the standards committee to get them.

Even though the draft versions might be very close to the final ratified versions of the standards, some of this post's editors would strongly advise you to get a copy of the actual documents — especially if you're planning on quoting them as references. Of course, starving students should go ahead and use the drafts if strapped for cash.


It appears that, if you are willing and able to wait a few months after ratification of a standard, to search for "INCITS/ISO/IEC" instead of "ISO/IEC" when looking for a standard is the key. By doing so, one of this post's editors was able to find the C11 and C++11 standards at reasonable prices. For example, if you search for "INCITS/ISO/IEC 9899:2011" instead of "ISO/IEC 9899:2011" on webstore.ansi.org you will find the reasonably priced PDF version.


The site https://wg21.link/ provides short-URL links to the C++ current working draft and draft standards, and committee papers:


The current draft of the standard is maintained as LaTeX sources on Github. These sources can be converted to HTML using cxxdraft-htmlgen. The following sites maintain HTML pages so generated:

Tim Song also maintains generated HTML and PDF versions of the Networking TS and Ranges TS.

Spring JSON request getting 406 (not Acceptable)

<dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
    <artifactId>jackson-jaxrs-base</artifactId>
    <version>2.6.3</version>
</dependency>

Is there an operator to calculate percentage in Python?

You could just divide your two numbers and multiply by 100. Note that this will throw an error if "whole" is 0, as asking what percentage of 0 a number is does not make sense:

def percentage(part, whole):
  return 100 * float(part)/float(whole)

Or with a % at the end:

 def percentage(part, whole):
  Percentage = 100 * float(part)/float(whole)
  return str(Percentage) + “%”

Or if the question you wanted it to answer was "what is 5% of 20", rather than "what percentage is 5 of 20" (a different interpretation of the question inspired by Carl Smith's answer), you would write:

def percentage(percent, whole):
  return (percent * whole) / 100.0

How to implement drop down list in flutter?

The error you are getting is due to ask for a property of a null object. Your item must be null so when asking for its value to be compared you are getting that error. Check that you are getting data or your list is a list of objects and not simple strings.

How to embed a YouTube channel into a webpage

In order to embed your channel, all you need to do is copy then paste the following code in another web-page.

<script src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/youtube.xml&up_channel=YourChannelName&synd=open&w=320&h=390&title=&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>

Make sure to replace the YourChannelName with your actual channel name.

For example: if your channel name were CaliChick94066 your channel embed code would be:

<script src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/youtube.xml&up_channel=CaliChick94066&synd=open&w=320&h=390&title=&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>

Please look at the following links:

YouTube on your site

Embed YouTube Channel

You just have to name the URL to your channel name. Also you can play with the height and the border color and size. Hope it helps

Cannot start MongoDB as a service

I ran this command:

C:\MongoDB\Server\3.4\bin>net start MongoDB

And got this message:

The service is not responding to the control function. More help is available by typing NET HELPMSG 2186.

After some trials and errors, I noticed when following the tutorial it asked me to name my file mongod.conf but the command was trying to refer to mongod.cfg.

As soon as I corrected that name and re-run the commands,

C:\MongoDB\Server\3.4\bin>sc.exe delete MongoDB
[SC] DeleteService SUCCESS

C:\MongoDB\Server\3.4\bin>sc.exe create MongoDB binPath= "\"C:\MongoDB\Server\3.4\bin\mongod.exe\" --service --config=\"C:\MongoDB\Server\3.4\mongod.cfg\"" DisplayName= "MongoDB" start= "auto"
[SC] CreateService SUCCESS

C:\MongoDB\Server\3.4\bin>net start MongoDB
The MongoDB service is starting....
The MongoDB service was started successfully.

The service started running fine.

deleting folder from java

Using the FileUtils.deleteDirectory() method can help to simplify the process of deleting directory and everything below it recursively.

Check this question

How to concatenate multiple lines of output to one line?

This could be what you want

cat file | grep pattern | paste -sd' '

As to your edit, I'm not sure what it means, perhaps this?

cat file | grep pattern | paste -sd'~' | sed -e 's/~/" "/g'

(this assumes that ~ does not occur in file)

How to convert seconds to HH:mm:ss in moment.js

How to correctly use moment.js durations? | Use moment.duration() in codes

First, you need to import moment and moment-duration-format.

import moment from 'moment';
import 'moment-duration-format';

Then, use duration function. Let us apply the above example: 28800 = 8 am.

moment.duration(28800, "seconds").format("h:mm a");

Well, you do not have above type error. Do you get a right value 8:00 am ? No…, the value you get is 8:00 a. Moment.js format is not working as it is supposed to.

The solution is to transform seconds to milliseconds and use UTC time.

moment.utc(moment.duration(value, 'seconds').asMilliseconds()).format('h:mm a')

All right we get 8:00 am now. If you want 8 am instead of 8:00 am for integral time, we need to do RegExp

const time = moment.utc(moment.duration(value, 'seconds').asMilliseconds()).format('h:mm a');
time.replace(/:00/g, '')

How to search for a string in cell array in MATLAB?

I guess the following code could do the trick:

strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}
ind=find(ismember(strs,'KU'))

This returns

ans = 
     2

Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?

There are a few functions like:

NSStringFromCGPoint  
NSStringFromCGSize  
NSStringFromCGRect  
NSStringFromCGAffineTransform  
NSStringFromUIEdgeInsets

An example:

NSLog(@"rect1: %@", NSStringFromCGRect(rect1));

How to deserialize JS date using Jackson?

This works for me - i am using jackson 2.0.4

ObjectMapper objectMapper = new ObjectMapper();
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
objectMapper.setDateFormat(df);

Calculating the position of points in a circle

Placing a number in a circular path

// variable

let number = 12; // how many number to be placed
let size = 260; // size of circle i.e. w = h = 260
let cx= size/2; // center of x(in a circle)
let cy = size/2; // center of y(in a circle)
let r = size/2; // radius of a circle

for(let i=1; i<=number; i++) {
  let ang = i*(Math.PI/(number/2));
  let left = cx + (r*Math.cos(ang));
  let top = cy + (r*Math.sin(ang));
  console.log("top: ", top, ", left: ", left);
}

How do I count the number of rows and columns in a file using bash?

Simple row count is $(wc -l "$file"). Use $(wc -lL "$file") to show both the number of lines and the number of characters in the longest line.

How to check Oracle database for long running queries

This one shows SQL that is currently "ACTIVE":-

select S.USERNAME, s.sid, s.osuser, t.sql_id, sql_text
from v$sqltext_with_newlines t,V$SESSION s
where t.address =s.sql_address
and t.hash_value = s.sql_hash_value
and s.status = 'ACTIVE'
and s.username <> 'SYSTEM'
order by s.sid,t.piece
/

This shows locks. Sometimes things are going slow, but it's because it is blocked waiting for a lock:

select
  object_name, 
  object_type, 
  session_id, 
  type,         -- Type or system/user lock
  lmode,        -- lock mode in which session holds lock
  request, 
  block, 
  ctime         -- Time since current mode was granted
from
  v$locked_object, all_objects, v$lock
where
  v$locked_object.object_id = all_objects.object_id AND
  v$lock.id1 = all_objects.object_id AND
  v$lock.sid = v$locked_object.session_id
order by
  session_id, ctime desc, object_name
/

This is a good one for finding long operations (e.g. full table scans). If it is because of lots of short operations, nothing will show up.

COLUMN percent FORMAT 999.99 

SELECT sid, to_char(start_time,'hh24:mi:ss') stime, 
message,( sofar/totalwork)* 100 percent 
FROM v$session_longops
WHERE sofar/totalwork < 1
/

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

Use a list comprehension:

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

Below is a demonstration:

>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> [x[0] for x in rows]
[1, 3, 5]
>>>

Alternately, you could use unpacking instead of x[0]:

res_list = [x for x,_ in rows]

Below is a demonstration:

>>> lst = [(1, 2), (3, 4), (5, 6)]
>>> [x for x,_ in lst]
[1, 3, 5]
>>>

Both methods practically do the same thing, so you can choose whichever you like.

Where can I get a virtual machine online?

Try this:

http://aws.amazon.com/free/

one year free. I do use this for a while.

What is the format for the PostgreSQL connection string / URL?

DATABASE_URL=postgres://{user}:{password}@{hostname}:{port}/{database-name}

Javascript isnull

You can also use the not operator. It will check if a variable is null, or, in the case of a string, is empty. It makes your code more compact and easier to read.

For example:

var pass = "";
if(!pass)
    return false;
else
    return true;

This would return false because the string is empty. It would also return false if the variable pass was null.

How to combine two lists in R

I was looking to do the same thing, but to preserve the list as a just an array of strings so I wrote a new code, which from what I've been reading may not be the most efficient but worked for what i needed to do:

combineListsAsOne <-function(list1, list2){
  n <- c()
  for(x in list1){
    n<-c(n, x)
  }
  for(y in list2){
    n<-c(n, y)
  }
  return(n)
}

It just creates a new list and adds items from two supplied lists to create one.

Forbidden You don't have permission to access / on this server

WORKING Method { if there is no problem other than configuration }

By Default Appache is not restricting access from ipv4. (common external ip)

What may restrict is the configurations in 'httpd.conf' (or 'apache2.conf' depending on your apache configuration)

Solution:

Replace all:

<Directory />
     AllowOverride none
    Require all denied

</Directory>

with

<Directory />
     AllowOverride none
#    Require all denied

</Directory>

hence removing out all restriction given to Apache

Replace Require local with Require all granted at C:/wamp/www/ directory

<Directory "c:/wamp/www/">
    Options Indexes FollowSymLinks
    AllowOverride all
    Require all granted
#   Require local
</Directory>

Remove directory which is not empty

Here is an async version of @SharpCoder's answer

const fs = require('fs');
const path = require('path');

function deleteFile(dir, file) {
    return new Promise(function (resolve, reject) {
        var filePath = path.join(dir, file);
        fs.lstat(filePath, function (err, stats) {
            if (err) {
                return reject(err);
            }
            if (stats.isDirectory()) {
                resolve(deleteDirectory(filePath));
            } else {
                fs.unlink(filePath, function (err) {
                    if (err) {
                        return reject(err);
                    }
                    resolve();
                });
            }
        });
    });
};

function deleteDirectory(dir) {
    return new Promise(function (resolve, reject) {
        fs.access(dir, function (err) {
            if (err) {
                return reject(err);
            }
            fs.readdir(dir, function (err, files) {
                if (err) {
                    return reject(err);
                }
                Promise.all(files.map(function (file) {
                    return deleteFile(dir, file);
                })).then(function () {
                    fs.rmdir(dir, function (err) {
                        if (err) {
                            return reject(err);
                        }
                        resolve();
                    });
                }).catch(reject);
            });
        });
    });
};

Unable to load script from assets index.android.bundle on windows

Make sure metro builder is running to make your physical device and server sync

First, run this command to run metro builder

npm start

Then you can start the build in react native

react-native run-android

Their should be no error this time. If you want your code to be live reload on change. Shake your device and then tap Enable Live Reload

Find a file with a certain extension in folder

Use this code for read file with all type of extension file.

string[] sDirectoryInfo = Directory.GetFiles(SourcePath, "*.*");

Internal vs. Private Access Modifiers

private - encapsulations in class/scope/struct ect'.

internal - encapsulation in assemblies.

Storing a file in a database as opposed to the file system?

In my own experience, it is always better to store files as files. The reason is that the filesystem is optimised for file storeage, whereas a database is not. Of course, there are some exceptions (e.g. the much heralded next-gen MS filesystem is supposed to be built on top of SQL server), but in general that's my rule.

Load external css file like scripts in jquery which is compatible in ie also

I think what the OP wanted to do was to load a style sheet asynchronously and add it. This works for me in Chrome 22, FF 16 and IE 8 for sets of CSS rules stored as text:

$.ajax({
    url: href,
    dataType: 'text',
    success: function(data) {
        $('<style type="text/css">\n' + data + '</style>').appendTo("head");                    
    }                  
});

In my case, I also sometimes want the loaded CSS to replace CSS that was previously loaded this way. To do that, I put a comment at the beginning, say "/* Flag this ID=102 */", and then I can do this:

// Remove old style
$("head").children().each(function(index, ele) {
    if (ele.innerHTML && ele.innerHTML.substring(0, 30).match(/\/\* Flag this ID=102 \*\//)) {
        $(ele).remove();
        return false;    // Stop iterating since we removed something
    }
});

angularjs make a simple countdown

It might help to "How to write the code for countdown watch in AngularJS"

Step 1 : HTML Code-sample

<div ng-app ng-controller="ExampleCtrl">
    <div ng-show="countDown_text > 0">Your password is expired in 180 Seconds.</div>
    <div ng-show="countDown_text > 0">Seconds left {{countDown_text}}</div>
    <div ng-show="countDown_text == 0">Your password is expired!.</div>
</div>

Step 2 : The AngulaJs code-sample

function ExampleCtrl($scope, $timeout) {
  var countDowner, countDown = 10;
  countDowner = function() {
    if (countDown < 0) {
      $("#warning").fadeOut(2000);
      countDown = 0;
      return; // quit
    } else {
      $scope.countDown_text = countDown; // update scope
      countDown--; // -1
      $timeout(countDowner, 1000); // loop it again
    }
  };

  $scope.countDown_text = countDown;
  countDowner()
}

The full example over countdown watch in AngularJs as given below.

<!DOCTYPE html>
<html>

<head>
  <title>AngularJS Example - Single Timer Example</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
  <script>
    function ExampleCtrl($scope, $timeout) {
      var countDowner, countDown = 10;
      countDowner = function() {
        if (countDown < 0) {
          $("#warning").fadeOut(2000);
          countDown = 0;
          return; // quit
        } else {
          $scope.countDown_text = countDown; // update scope
          countDown--; // -1
          $timeout(countDowner, 1000); // loop it again
        }
      };

      $scope.countDown_text = countDown;
      countDowner()
    }
  </script>
</head>

<body>
  <div ng-app ng-controller="ExampleCtrl">
    <div ng-show="countDown_text > 0">Your password is expired in 180 Seconds.</div>
    <div ng-show="countDown_text > 0">Seconds left {{countDown_text}}</div>
    <div ng-show="countDown_text == 0">Your password is expired!.</div>
  </div>
</body>

</html>

Javascript Get Element by Id and set the value

<html>
<head>
<script>
function updateTextarea(element)
{
document.getElementById(element).innerText = document.getElementById("ment").value;
}
</script>
</head>
<body>

<input type="text" value="Enter your text here." id = "ment" style = " border: 1px solid grey; margin-bottom: 4px;"  

onKeyUp="updateTextarea('myDiv')" />

<br>

<textarea id="myDiv" ></textarea>

</body>
</html>

How to import a new font into a project - Angular 5

the answer is already exist above, but I would like to add some thing.. you can specify the following in your @font-face

@font-face {
  font-family: 'Name You Font';
  src: url('assets/font/xxyourfontxxx.eot');
  src: local('Cera Pro Medium'), local('CeraPro-Medium'),
  url('assets/font/xxyourfontxxx.eot?#iefix') format('embedded-opentype'),
  url('assets/font/xxyourfontxxx.woff') format('woff'),
  url('assets/font/xxyourfontxxx.ttf') format('truetype');
  font-weight: 500;
  font-style: normal;
}

So you can just indicate your fontfamily name that you already choosed

NOTE: the font-weight and font-style depend on your .woff .ttf ... files

Convert a String to int?

You can directly convert to an int using the str::parse::<T>() method.

let my_string = "27".to_string();  // `parse()` works with `&str` and `String`!
let my_int = my_string.parse::<i32>().unwrap();

You can either specify the type to parse to with the turbofish operator (::<>) as shown above or via explicit type annotation:

let my_int: i32 = my_string.parse().unwrap();

As mentioned in the comments, parse() returns a Result. This result will be an Err if the string couldn't be parsed as the type specified (for example, the string "peter" can't be parsed as i32).

Split long commands in multiple lines through Windows batch file

You can break up long lines with the caret ^ as long as you remember that the caret and the newline following it are completely removed. So, if there should be a space where you're breaking the line, include a space. (More on that below.)

Example:

copy file1.txt file2.txt

would be written as:

copy file1.txt^
 file2.txt

fatal error LNK1169: one or more multiply defined symbols found in game programming

You can't put variable definitions in header files, as these will then be a part of all source file you include the header into.

The #pragma once is just to protect against multiple inclusions in the same source file, not against multiple inclusions in multiple source files.

You could declare the variables as extern in the header file, and then define them in a single source file. Or you could declare the variables as const in the header file and then the compiler and linker will manage it.

Is there a native jQuery function to switch elements?

$('.five').swap('.two');

Create a jQuery function like this

$.fn.swap = function (elem) 
{
    elem = elem.jquery ? elem : $(elem);
    return this.each(function () 
    {
        $('<span></span>').insertBefore(this).before(elem.before(this)).remove();
    });
};

Thanks to Yannick Guinness at https://jsfiddle.net/ARTsinn/TVjnr/

Replace missing values with column mean

dplyr's mutate_all or mutate_at could be useful here:

library(dplyr)                                                             

set.seed(10)                                                               
df <- data.frame(a = sample(c(NA, 1:3)    , replace = TRUE, 10),           
                 b = sample(c(NA, 101:103), replace = TRUE, 10),                            
                 c = sample(c(NA, 201:203), replace = TRUE, 10))                            

df         

#>     a   b   c
#> 1   2 102 203
#> 2   1 102 202
#> 3   1  NA 203
#> 4   2 102 201
#> 5  NA 101 201
#> 6  NA 101 202
#> 7   1  NA 203
#> 8   1 101  NA
#> 9   2 101 203
#> 10  1 103 201

df %>% mutate_all(~ifelse(is.na(.x), mean(.x, na.rm = TRUE), .x))          

#>        a       b        c
#> 1  2.000 102.000 203.0000
#> 2  1.000 102.000 202.0000
#> 3  1.000 101.625 203.0000
#> 4  2.000 102.000 201.0000
#> 5  1.375 101.000 201.0000
#> 6  1.375 101.000 202.0000
#> 7  1.000 101.625 203.0000
#> 8  1.000 101.000 202.1111
#> 9  2.000 101.000 203.0000
#> 10 1.000 103.000 201.0000

df %>% mutate_at(vars(a, b),~ifelse(is.na(.x), mean(.x, na.rm = TRUE), .x))

#>        a       b   c
#> 1  2.000 102.000 203
#> 2  1.000 102.000 202
#> 3  1.000 101.625 203
#> 4  2.000 102.000 201
#> 5  1.375 101.000 201
#> 6  1.375 101.000 202
#> 7  1.000 101.625 203
#> 8  1.000 101.000  NA
#> 9  2.000 101.000 203
#> 10 1.000 103.000 201

Parsing json and searching through it

ObjectPath is a library that provides ability to query JSON and nested structures of dicts and lists. For example, you can search for all attributes called "foo" regardless how deep they are by using $..foo.

While the documentation focuses on the command line interface, you can perform the queries programmatically by using the package's Python internals. The example below assumes you've already loaded the data into Python data structures (dicts & lists). If you're starting with a JSON file or string you just need to use load or loads from the json module first.

import objectpath

data = [
    {'foo': 1, 'bar': 'a'},
    {'foo': 2, 'bar': 'b'},
    {'NoFooHere': 2, 'bar': 'c'},
    {'foo': 3, 'bar': 'd'},
]

tree_obj = objectpath.Tree(data)

tuple(tree_obj.execute('$..foo'))
# returns: (1, 2, 3)

Notice that it just skipped elements that lacked a "foo" attribute, such as the third item in the list. You can also do much more complex queries, which makes ObjectPath handy for deeply nested structures (e.g. finding where x has y that has z: $.x.y.z). I refer you to the documentation and tutorial for more information.

How to select clear table contents without destroying the table?

I use this code to remove my data but leave the formulas in the top row. It also removes all rows except for the top row and scrolls the page up to the top.

Sub CleanTheTable()
    Application.ScreenUpdating = False
    Sheets("Data").Select
    ActiveSheet.ListObjects("TestTable").HeaderRowRange.Select
    'Remove the filters if one exists.
    If ActiveSheet.FilterMode Then
    Selection.AutoFilter
    End If
    'Clear all lines but the first one in the table leaving formulas for the next go round.
    With Worksheets("Data").ListObjects("TestTable")
    .Range.AutoFilter
    On Error Resume Next
    .DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
    .DataBodyRange.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
    ActiveWindow.SmallScroll Down:=-10000

    End With
Application.ScreenUpdating = True
End Sub

Batch File; List files in directory, only filenames?

Windows 10:

  1. open cmd

  2. change directory where you want to create text file(movie_list.txt) for the folder (d:\videos\movies)

  3. type following command

    d:\videos\movies> dir /b /a-d > movie_list.txt

How do you fix the "element not interactable" exception?

I have found that using Thread.sleep(milliseconds) helps almost all the time for me. It takes time for the element to load hence it is not interactable. So i put Thread.sleep() after selecting each value. So far this has helped me avoid the error.

try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}

        Select nationalityDropdown=new Select(driver.findElement(By.id("ContentPlaceHolderMain_ddlNationality")));

        nationalityDropdown.selectByValue("Indian");

        try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}     

How do I remove the file suffix and path portion from a path string in Bash?

Using basename assumes that you know what the file extension is, doesn't it?

And I believe that the various regular expression suggestions don't cope with a filename containing more than one "."

The following seems to cope with double dots. Oh, and filenames that contain a "/" themselves (just for kicks)

To paraphrase Pascal, "Sorry this script is so long. I didn't have time to make it shorter"


  #!/usr/bin/perl
  $fullname = $ARGV[0];
  ($path,$name) = $fullname =~ /^(.*[^\\]\/)*(.*)$/;
  ($basename,$extension) = $name =~ /^(.*)(\.[^.]*)$/;
  print $basename . "\n";
 

When should I use Lazy<T>?

I have been considering using Lazy<T> properties to help improve the performance of my own code (and to learn a bit more about it). I came here looking for answers about when to use it but it seems that everywhere I go there are phrases like:

Use lazy initialization to defer the creation of a large or resource-intensive object, or the execution of a resource-intensive task, particularly when such creation or execution might not occur during the lifetime of the program.

from MSDN Lazy<T> Class

I am left a bit confused because I am not sure where to draw the line. For example, I consider linear interpolation as a fairly quick computation but if I don't need to do it then can lazy initialisation help me to avoid doing it and is it worth it?

In the end I decided to try my own test and I thought I would share the results here. Unfortunately I am not really an expert at doing these sort of tests and so I am happy to get comments that suggest improvements.

Description

For my case, I was particularly interested to see if Lazy Properties could help improve a part of my code that does a lot of interpolation (most of it being unused) and so I have created a test that compared 3 approaches.

I created a separate test class with 20 test properties (lets call them t-properties) for each approach.

  • GetInterp Class: Runs linear interpolation every time a t-property is got.
  • InitInterp Class: Initialises the t-properties by running the linear interpolation for each one in the constructor. The get just returns a double.
  • InitLazy Class: Sets up the t-properties as Lazy properties so that linear interpolation is run once when the property is first got. Subsequent gets should just return an already calculated double.

The test results are measured in ms and are the average of 50 instantiations or 20 property gets. Each test was then run 5 times.

Test 1 Results: Instantiation (average of 50 instantiations)

Class      1        2        3        4        5        Avg       %
------------------------------------------------------------------------
GetInterp  0.005668 0.005722 0.006704 0.006652 0.005572 0.0060636 6.72
InitInterp 0.08481  0.084908 0.099328 0.098626 0.083774 0.0902892 100.00
InitLazy   0.058436 0.05891  0.068046 0.068108 0.060648 0.0628296 69.59

Test 2 Results: First Get (average of 20 property gets)

Class      1        2        3        4        5        Avg       %
------------------------------------------------------------------------
GetInterp  0.263    0.268725 0.31373  0.263745 0.279675 0.277775 54.38
InitInterp 0.16316  0.161845 0.18675  0.163535 0.173625 0.169783 33.24
InitLazy   0.46932  0.55299  0.54726  0.47878  0.505635 0.510797 100.00

Test 3 Results: Second Get (average of 20 property gets)

Class      1        2        3        4        5        Avg       %
------------------------------------------------------------------------
GetInterp  0.08184  0.129325 0.112035 0.097575 0.098695 0.103894 85.30
InitInterp 0.102755 0.128865 0.111335 0.10137  0.106045 0.110074 90.37
InitLazy   0.19603  0.105715 0.107975 0.10034  0.098935 0.121799 100.00

Observations

GetInterp is fastest to instantiate as expected because its not doing anything. InitLazy is faster to instantiate than InitInterp suggesting that the overhead in setting up lazy properties is faster than my linear interpolation calculation. However, I am a bit confused here because InitInterp should be doing 20 linear interpolations (to set up it's t-properties) but it is only taking 0.09 ms to instantiate (test 1), compared to GetInterp which takes 0.28 ms to do just one linear interpolation the first time (test 2), and 0.1 ms to do it the second time (test 3).

It takes InitLazy almost 2 times longer than GetInterp to get a property the first time, while InitInterp is the fastest, because it populated its properties during instantiation. (At least that is what it should have done but why was it's instantiation result so much quicker than a single linear interpolation? When exactly is it doing these interpolations?)

Unfortunately it looks like there is some automatic code optimisation going on in my tests. It should take GetInterp the same time to get a property the first time as it does the second time, but it is showing as more than 2x faster. It looks like this optimisation is also affecting the other classes as well since they are all taking about the same amount of time for test 3. However, such optimisations may also take place in my own production code which may also be an important consideration.

Conclusions

While some results are as expected, there are also some very interesting unexpected results probably due to code optimisations. Even for classes that look like they are doing a lot of work in the constructor, the instantiation results show that they may still be very quick to create, compared to getting a double property. While experts in this field may be able to comment and investigate more thoroughly, my personal feeling is that I need to do this test again but on my production code in order to examine what sort of optimisations may be taking place there too. However, I am expecting that InitInterp may be the way to go.

JOIN queries vs multiple queries

This is way too vague to give you an answer relevant to your specific case. It depends on a lot of things. Jeff Atwood (founder of this site) actually wrote about this. For the most part, though, if you have the right indexes and you properly do your JOINs it is usually going to be faster to do 1 trip than several.

Total number of items defined in an enum

You can use Enum.GetNames to return an IEnumerable of values in your enum and then .Count the resulting IEnumerable.

GetNames produces much the same result as GetValues but is faster.

How to acces external json file objects in vue.js app

Typescript projects (I have typescript in SFC vue components), need to set resolveJsonModule compiler option to true.

In tsconfig.json:

{
  "compilerOptions": {
    ...
    "resolveJsonModule": true,
    ...
  },
  ...
}

Happy coding :)

(Source https://www.typescriptlang.org/docs/handbook/compiler-options.html)

Where is the .NET Framework 4.5 directory?

Whilst the above answers are correct its worth noting that MSBuild has changed and it no longer ships with the .net framework, it comes either stand alone or with visual studio. As a result it's binaries have moved... so the one you get under the 4.0.303619 directory is actually the old one!

I've just been caught out by this - I found automatic binding redirects were only working when running from VisualStudio but not when running msbuild from the command line... the clue was that binding redirects were added in VS 2013 (for that read .net framework 4.5). If you open up a vs command prompt you'll see it now gets it from program files as the other article mentions. Whereas I was using a batch file on my path which linked to the old version.

Version numbers

Under framework:

PS C:\Windows\Microsoft.NET\Framework\v4.0.30319> .\msbuild.exe -version
Microsoft (R) Build Engine version 4.0.30319.33440
[Microsoft .NET Framework, version 4.0.30319.34014]
Copyright (C) Microsoft Corporation. All rights reserved.

4.0.30319.33440PS C:\Windows\Microsoft.NET\Framework\v4.0.30319>

Under program files:

PS C:\Program Files (x86)\MSBuild\12.0\Bin> .\MSBuild.exe -version
Microsoft (R) Build Engine version 12.0.21005.1
[Microsoft .NET Framework, version 4.0.30319.34014]
Copyright (C) Microsoft Corporation. All rights reserved.

12.0.21005.1PS C:\Program Files (x86)\MSBuild\12.0\Bin>

Find out free space on tablespace

Here is a query used by Oracle SQL Developer in its Tablespaces view

select a.tablespace_name as "Tablespace Name",
       round(a.bytes_alloc / 1024 / 1024) "Allocated (MB)",
       round(nvl(b.bytes_free, 0) / 1024 / 1024) "Free (MB)",
       round((a.bytes_alloc - nvl(b.bytes_free, 0)) / 1024 / 1024) "Used (MB)",
       round((nvl(b.bytes_free, 0) / a.bytes_alloc) * 100) "% Free",
       100 - round((nvl(b.bytes_free, 0) / a.bytes_alloc) * 100) "% Used",
       round(maxbytes/1024 / 1024) "Max. Bytes (MB)"
from  ( select  f.tablespace_name,
               sum(f.bytes) bytes_alloc,
               sum(decode(f.autoextensible, 'YES',f.maxbytes,'NO', f.bytes)) maxbytes
        from dba_data_files f
        group by tablespace_name) a,
      ( select  f.tablespace_name,
               sum(f.bytes)  bytes_free
        from dba_free_space f
        group by tablespace_name) b
where a.tablespace_name = b.tablespace_name (+)
union all
select 
       h.tablespace_name as tablespace_name,
       round(sum(h.bytes_free + h.bytes_used) / 1048576) megs_alloc,
       round(sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / 1048576) megs_free,
       round(sum(nvl(p.bytes_used, 0))/ 1048576) megs_used,
       round((sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / sum(h.bytes_used + h.bytes_free)) * 100) Pct_Free,
       100 - round((sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / sum(h.bytes_used + h.bytes_free)) * 100) pct_used,
       round(sum(f.maxbytes) / 1048576) max
from   sys.v_$TEMP_SPACE_HEADER h, sys.v_$Temp_extent_pool p, dba_temp_files f
where  p.file_id(+) = h.file_id
and    p.tablespace_name(+) = h.tablespace_name
and    f.file_id = h.file_id
and    f.tablespace_name = h.tablespace_name
group by h.tablespace_name
ORDER BY 2;

Can Flask have optional URL parameters?

You can write as you show in example, but than you get build-error.

For fix this:

  1. print app.url_map () in you root .py
  2. you see something like:

<Rule '/<userId>/<username>' (HEAD, POST, OPTIONS, GET) -> user.show_0>

and

<Rule '/<userId>' (HEAD, POST, OPTIONS, GET) -> .show_1>

  1. than in template you can {{ url_for('.show_0', args) }} and {{ url_for('.show_1', args) }}

How do I get an empty array of any size in python?

x=[]
for i in range(0,5):
    x.append(i)
    print(x[i])

Getting value of HTML text input

Yes, you can use jQuery to make this done, the idea is

Use a hidden value in your form, and copy the value from external text box to this hidden value just before submitting the form.

<form name="input" action="handle_email.php" method="post">
  <input type="hidden" name="email" id="email" />
  <input type="submit" value="Submit" />
</form> 

<script>
   $("form").submit(function() {
     var emailFromOtherTextBox = $("#email_textbox").val();
     $("#email").val(emailFromOtherTextBox ); 
     return true;
  });
</script>

also see http://api.jquery.com/submit/

How can I set the current working directory to the directory of the script in Bash?

cd "$(dirname "${BASH_SOURCE[0]}")"

It's easy. It works.

Capturing window.onbeforeunload

There seems to be a lot of misinformation about how to use this event going around (even in upvoted answers on this page).

The onbeforeunload event API is supplied by the browser for a specific purpose: The only thing you can do that's worth doing in this method is to return a string which the browser will then prompt to the user to indicate to them that action should be taken before they navigate away from the page. You CANNOT prevent them from navigating away from a page (imagine what a nightmare that would be for the end user).

Because browsers use a confirm prompt to show the user the string you returned from your event listener, you can't do anything else in the method either (like perform an ajax request).

In an application I wrote, I want to prompt the user to let them know they have unsaved changes before they leave the page. The browser prompts them with the message and, after that, it's out of my hands, the user can choose to stay or leave, but you no longer have control of the application at that point.

An example of how I use it (pseudo code):

onbeforeunload = function() {

  if(Application.hasUnsavedChanges()) {
    return 'You have unsaved changes. Please save them before leaving this page';
  }


};

If (and only if) the application has unsaved changes, then the browser prompts the user to either ignore my message (and leave the page anyway) or to not leave the page. If they choose to leave the page anyway, too bad, there's nothing you can do (nor should be able to do) about it.

How do I format a number in Java?

There are two approaches in the standard library. One is to use java.text.DecimalFormat. The other more cryptic methods (String.format, PrintStream.printf, etc) based around java.util.Formatter should keep C programmers happy(ish).

How to sort List of objects by some property

JAVA 8 and Above Answer (Using Lambda Expressions)

In Java 8, Lambda expressions were introduced to make this even easier! Instead of creating a Comparator() object with all of it's scaffolding, you can simplify it as follows: (Using your object as an example)

Collections.sort(list, (ActiveAlarm a1, ActiveAlarm a2) -> a1.timeStarted-a2.timeStarted);

or even shorter:

Collections.sort(list, Comparator.comparingInt(ActiveAlarm ::getterMethod));

That one statement is equivalent to the following:

Collections.sort(list, new Comparator<ActiveAlarm>() {
    @Override
    public int compare(ActiveAlarm a1, ActiveAlarm a2) {
        return a1.timeStarted - a2.timeStarted;
    }
});

Think of Lambda expressions as only requiring you to put in the relevant parts of the code: the method signature and what gets returned.

Another part of your question was how to compare against multiple fields. To do that with Lambda expressions, you can use the .thenComparing() function to effectively combine two comparisons into one:

Collections.sort(list, (ActiveAlarm a1, ActiveAlarm a2) -> a1.timeStarted-a2.timeStarted             
       .thenComparing ((ActiveAlarm a1, ActiveAlarm a2) -> a1.timeEnded-a2.timeEnded)
);

The above code will sort the list first by timeStarted, and then by timeEnded (for those records that have the same timeStarted).

One last note: It is easy to compare 'long' or 'int' primitives, you can just subtract one from the other. If you are comparing objects ('Long' or 'String'), I suggest you use their built-in comparison. Example:

Collections.sort(list, (ActiveAlarm a1, ActiveAlarm a2) -> a1.name.compareTo(a2.name) );

EDIT: Thanks to Lukas Eder for pointing me to .thenComparing() function.

Eclipse/Maven error: "No compiler is provided in this environment"

I also faced similar error when I was working with Jdk1.8_92. For me, I found tools.jar was missing in my jdk folder. Since I was running in console, I couldn't try the options of eclipse suggested by others..

I installed jdk-8u92-windows-x64. After I tried all options, I observed that tools.jar was missing in jdk1.8.0_92/lib folder. I copied tools.jar from my older version of java. Then It was able to compile.

Best Java obfuscator?

We've had much better luck encrypting the jars rather than obfuscating. We use Classguard.

How do the likely/unlikely macros in the Linux kernel work and what is their benefit?

These are GCC functions for the programmer to give a hint to the compiler about what the most likely branch condition will be in a given expression. This allows the compiler to build the branch instructions so that the most common case takes the fewest number of instructions to execute.

How the branch instructions are built are dependent upon the processor architecture.

Why is a div with "display: table-cell;" not affected by margin?

If you have div next each other like this

<div id="1" style="float:left; margin-right:5px">

</div>
<div id="2" style="float:left">

</div>

This should work!

What's the difference between window.location and document.location in JavaScript?

Yes, they are the same. It's one of the many historical quirks in the browser JS API. Try doing:

window.location === document.location

How to set the title of UIButton as left alignment?

In Swift 3+:

button.contentHorizontalAlignment = .left

show icon in actionbar/toolbar with AppCompat-v7 21

getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.drawable.ic_launcher);

OR make a XML layout call the tool_bar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@color/colorPrimary"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    android:elevation="4dp">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:src="@drawable/ic_action_search"/>

    </RelativeLayout>
</android.support.v7.widget.Toolbar>

Now in you main activity add this line

 <include
     android:id="@+id/tool_bar"
     layout="@layout/tool_bar" />

How can I find all matches to a regular expression in Python?

Use re.findall or re.finditer instead.

re.findall(pattern, string) returns a list of matching strings.

re.finditer(pattern, string) returns an iterator over MatchObject objects.

Example:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']

[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']

Show whitespace characters in Visual Studio Code

Just to demonstrate the changes that editor.renderWhitespace : none||boundary||all will do to your VSCode I added this screenshot:
enter image description here.

Where Tab are ? and Spaceare .

Explain the "setUp" and "tearDown" Python methods used in test cases

Suppose you have a suite with 10 tests. 8 of the tests share the same setup/teardown code. The other 2 don't.

setup and teardown give you a nice way to refactor those 8 tests. Now what do you do with the other 2 tests? You'd move them to another testcase/suite. So using setup and teardown also helps give a natural way to break the tests into cases/suites

SQL Error: ORA-00922: missing or invalid option

You should not use space character while naming database objects. Even though it's possible by using double quotes(quoted identifiers), CREATE TABLE "chartered flight" ..., it's not recommended. Take a closer look here

Creating a select box with a search option

This will done by using jquery. Here is the code

<select class="chosen" style="width:500px;">
<option>Html</option>
<option>Css</option>
<option>Css3</option>
<option>Php</option>
<option>MySql</option>
<option>Javascript</option>
<option>Jquery</option>
<option>Html5</option>
<option>Wordpress</option>
<option>Joomla</option>
<option>Druple</option>
<option>Json</option>
<option>Angular Js</option>
</select>
</div>
<script type="text/javascript">
$(".chosen").chosen();
</script>

Working Example Here...

lodash: mapping array to object

Yep it is here, using _.reduce

var params = [
    { name: 'foo', input: 'bar' },
    { name: 'baz', input: 'zle' }
];

_.reduce(params , function(obj,param) {
 obj[param.name] = param.input
 return obj;
}, {});

Karma: Running a single test file from command line

First you need to start karma server with

karma start

Then, you can use grep to filter a specific test or describe block:

karma run -- --grep=testDescriptionFilter

Clearing localStorage in javascript?

localStorage.clear();

or

window.localStorage.clear();

to clear particular item

window.localStorage.removeItem("item_name");

To remove particular value by id :

var item_detail = JSON.parse(localStorage.getItem("key_name")) || [];           
            $.each(item_detail, function(index, obj){
                if (key_id == data('key')) {
                    item_detail.splice(index,1);
                    localStorage["key_name"] = JSON.stringify(item_detail);
                    return false;
                }
            });

iPhone 6 and 6 Plus Media Queries

This works for me for the iphone 6

/*iPhone 6 Portrait*/
@media only screen and (min-device-width: 375px) and (max-device-width: 667px) and (orientation : portrait) { 

}

/*iPhone 6 landscape*/
@media only screen and (min-device-width: 375px) and (max-device-width: 667px) and (orientation : landscape) { 

}

/*iPhone 6+ Portrait*/
@media only screen and (min-device-width: 414px) and (max-device-width: 736px) and (orientation : portrait) { 

}

/*iPhone 6+ landscape*/
@media only screen and (min-device-width: 414px) and (max-device-width: 736px) and (orientation : landscape) { 

}

/*iPhone 6 and iPhone 6+ portrait and landscape*/
@media only screen and (max-device-width: 640px), only screen and (max-device-width: 667px), only screen and (max-width: 480px){ 
}

/*iPhone 6 and iPhone 6+ portrait*/
@media only screen and (max-device-width: 640px), only screen and (max-device-width: 667px), only screen and (max-width: 480px) and (orientation : portrait){ 

}

/*iPhone 6 and iPhone 6+ landscape*/
@media only screen and (max-device-width: 640px), only screen and (max-device-width: 667px), only screen and (max-width: 480px) and (orientation : landscape){ 

}

isPrime Function for Python Language

Every code you write should be efficient.For a beginner like you the easiest way is to check the divisibility of the number 'n' from 2 to (n-1). This takes a lot of time when you consider very big numbers. The square root method helps us make the code faster by less number of comparisons. Read about complexities in Design and Analysis of Algorithms.

What is a 'multi-part identifier' and why can't it be bound?

When you type the FROM table those errors will disappear. Type FROM below what your typing then Intellisense will work and multi-part identifier will work.

What does "Could not find or load main class" mean?

I spent a decent amount of time trying to solve this problem. I thought that I was somehow setting my classpath incorrectly but the problem was that I typed:

java -cp C:/java/MyClasses C:/java/MyClasses/utilities/myapp/Cool  

instead of:

java -cp C:/java/MyClasses utilities/myapp/Cool   

I thought the meaning of fully qualified meant to include the full path name instead of the full package name.

Applying function with multiple arguments to create a new pandas column

This solves the problem:

df['newcolumn'] = df.A * df.B

You could also do:

def fab(row):
  return row['A'] * row['B']

df['newcolumn'] = df.apply(fab, axis=1)

Get Filename Without Extension in Python

If I had to do this with a regex, I'd do it like this:

s = re.sub(r'\.jpg$', '', s)

How to get docker-compose to always re-create containers from fresh images?

I claimed 3.5gb space in ubuntu AWS through this.

clean docker

docker stop $(docker ps -qa) && docker system prune -af --volumes

build again

docker build .

docker-compose build

docker-compose up

Java Reflection: How to get the name of a variable?

update @Marcel Jackwerth's answer for general.

and only working with class attribute, not working with method variable.

    /**
     * get variable name as string
     * only work with class attributes
     * not work with method variable
     *
     * @param headClass variable name space
     * @param vars      object variable
     * @throws IllegalAccessException
     */
    public static void printFieldNames(Object headClass, Object... vars) throws IllegalAccessException {
        List<Object> fooList = Arrays.asList(vars);
        for (Field field : headClass.getClass().getFields()) {
            if (fooList.contains(field.get(headClass))) {
                System.out.println(field.getGenericType() + " " + field.getName() + " = " + field.get(headClass));
            }
        }
    }

Center Contents of Bootstrap row container

Try this, it works!

<div class="row">
    <div class="center">
        <div class="col-xs-12 col-sm-4">
            <p>hi 1!</p>
        </div>
        <div class="col-xs-12 col-sm-4">
            <p>hi 2!</p>
        </div>
        <div class="col-xs-12 col-sm-4">
            <p>hi 3!</p>
        </div>
    </div>
</div>

Then, in css define the width of center div and center in a document:

.center {
    margin: 0 auto;
    width: 80%;
}

Visual Studio Expand/Collapse keyboard shortcuts

You can use Ctrl + M and Ctrl + P

It's called Edit.StopOutlining

How to horizontally center an element

Instead of multiple wrappers and/or auto margins, this simple solution works for me:

<div style="top: 50%; left: 50%;
    height: 100px; width: 100px;
    margin-top: -50px; margin-left: -50px;
    background: url('lib/loading.gif') no-repeat center #fff;
    text-align: center;
    position: fixed; z-index: 9002;">Loading...</div>

It puts the div at the center of the view (vertical and horizontal), sizes and adjusts for size, centers background image (vertical and horizontal), centers text (horizontal), and keeps div in the view and on top of the content. Simply place in the HTML body and enjoy.

Load JSON text into class object in c#

To create a json class off a string, copy the string.

In Visual Sudio, click Edit > Paste special > Paste Json as classes.

Use of def, val, and var in scala

As Kintaro already says, person is a method (because of def) and always returns a new Person instance. As you found out it would work if you change the method to a var or val:

val person = new Person("Kumar",12)

Another possibility would be:

def person = new Person("Kumar",12)
val p = person
p.age=20
println(p.age)

However, person.age=20 in your code is allowed, as you get back a Person instance from the person method, and on this instance you are allowed to change the value of a var. The problem is, that after that line you have no more reference to that instance (as every call to person will produce a new instance).

This is nothing special, you would have exactly the same behavior in Java:

class Person{ 
   public int age; 
   private String name;
   public Person(String name; int age) {
      this.name = name;  
      this.age = age;
   }
   public String name(){ return name; }
}

public Person person() { 
  return new Person("Kumar", 12); 
}

person().age = 20;
System.out.println(person().age); //--> 12

How to read a file without newlines?

my_file = open("first_file.txt", "r")
for line in my_file.readlines():
    if line[-1:] == "\n":
        print(line[:-1])
    else:
        print(line)
my_file.close() 

Is this a good way to clone an object in ES6?

EDIT: When this answer was posted, {...obj} syntax was not available in most browsers. Nowadays, you should be fine using it (unless you need to support IE 11).

Use Object.assign.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

var obj = { a: 1 };
var copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }

However, this won't make a deep clone. There is no native way of deep cloning as of yet.

EDIT: As @Mike 'Pomax' Kamermans mentioned in the comments, you can deep clone simple objects (ie. no prototypes, functions or circular references) using JSON.parse(JSON.stringify(input))

SQL server stored procedure return a table

Consider creating a function which can return a table and be used in a query.

https://msdn.microsoft.com/en-us/library/ms186755.aspx

The main difference between a function and a procedure is that a function makes no changes to any table. It only returns a value.

In this example I'm creating a query to give me the counts of all the columns in a given table which aren't null or empty.

There are probably many ways to clean this up. But it illustrates a function well.

USE Northwind

CREATE FUNCTION usp_listFields(@schema VARCHAR(50), @table VARCHAR(50))
RETURNS @query TABLE (
    FieldName VARCHAR(255)
    )
BEGIN
    INSERT @query
    SELECT
        'SELECT ''' + @table+'~'+RTRIM(COLUMN_NAME)+'~''+CONVERT(VARCHAR, COUNT(*)) '+
    'FROM '+@schema+'.'+@table+' '+
          ' WHERE isnull("'+RTRIM(COLUMN_NAME)+'",'''')<>'''' UNION'
    FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table and TABLE_SCHEMA = @schema
    RETURN
END

Then executing the function with

SELECT * FROM usp_listFields('Employees')

produces a number of rows like:

SELECT 'Employees~EmployeeID~'+CONVERT(VARCHAR, COUNT(*)) FROM dbo.Employees  WHERE isnull("EmployeeID",'')<>'' UNION
SELECT 'Employees~LastName~'+CONVERT(VARCHAR, COUNT(*)) FROM dbo.Employees  WHERE isnull("LastName",'')<>'' UNION
SELECT 'Employees~FirstName~'+CONVERT(VARCHAR, COUNT(*)) FROM dbo.Employees  WHERE isnull("FirstName",'')<>'' UNION

How does Java deal with multiple conditions inside a single IF statement

Please look up the difference between & and && in Java (the same applies to | and ||).

& and | are just logical operators, while && and || are conditional logical operators, which in your example means that

if(bool1 && bool2 && bool3) {

will skip bool2 and bool3 if bool1 is false, and

if(bool1 & bool2 & bool3) {

will evaluate all conditions regardless of their values.

For example, given:

boolean foo() {
    System.out.println("foo");
    return true;
}

if(foo() | foo()) will print foo twice, and if(foo() || foo()) - just once.

What primitive data type is time_t?

You could always use something like mktime to create a known time (midnight, last night) and use difftime to get a double-precision time difference between the two. For a platform-independant solution, unless you go digging into the details of your libraries, you're not going to do much better than that. According to the C spec, the definition of time_t is implementation-defined (meaning that each implementation of the library can define it however they like, as long as library functions with use it behave according to the spec.)

That being said, the size of time_t on my linux machine is 8 bytes, which suggests a long int or a double. So I did:

int main()
{
    for(;;)
    {
        printf ("%ld\n", time(NULL));
        printf ("%f\n", time(NULL));
        sleep(1);
    }
    return 0;
}

The time given by the %ld increased by one each step and the float printed 0.000 each time. If you're hell-bent on using printf to display time_ts, your best bet is to try your own such experiment and see how it work out on your platform and with your compiler.

internet explorer 10 - how to apply grayscale filter?

Use this jQuery plugin https://gianlucaguarini.github.io/jQuery.BlackAndWhite/

That seems to be the only one cross-browser solution. Plus it has a nice fade in and fade out effect.

$('.bwWrapper').BlackAndWhite({
    hoverEffect : true, // default true
    // set the path to BnWWorker.js for a superfast implementation
    webworkerPath : false,
    // to invert the hover effect
    invertHoverEffect: false,
    // this option works only on the modern browsers ( on IE lower than 9 it remains always 1)
    intensity:1,
    speed: { //this property could also be just speed: value for both fadeIn and fadeOut
        fadeIn: 200, // 200ms for fadeIn animations
        fadeOut: 800 // 800ms for fadeOut animations
    },
    onImageReady:function(img) {
        // this callback gets executed anytime an image is converted
    }
});

Switch statement with returns -- code correctness

I'd normally write the code without them. IMO, dead code tends to indicate sloppiness and/or lack of understanding.

Of course, I'd also consider something like:

char const *rets[] = {"blah", "foo", "bar"};

return rets[something];

Edit: even with the edited post, this general idea can work fine:

char const *rets[] = { "blah", "foo", "bar", "bar", "foo"};

if ((unsigned)something < 5)
    return rets[something]
return "foobar";

At some point, especially if the input values are sparse (e.g., 1, 100, 1000 and 10000), you want a sparse array instead. You can implement that as either a tree or a map reasonably well (though, of course, a switch still works in this case as well).

How to detect when facebook's FB.init is complete

Another way to check if FB has initialized is by using the following code:

ns.FBInitialized = function () {
    return typeof (FB) != 'undefined' && window.fbAsyncInit.hasRun;
};

Thus in your page ready event you could check ns.FBInitialized and defer the event to later phase by using setTimeOut.

<xsl:variable> Print out value of XSL variable using <xsl:value-of>

Your main problem is thinking that the variable you declared outside of the template is the same variable being "set" inside the choose statement. This is not how XSLT works, the variable cannot be reassigned. This is something more like what you want:

<xsl:template match="class">
  <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
  <xsl:variable name="subexists">
    <xsl:choose>
      <xsl:when test="joined-subclass">true</xsl:when>
      <xsl:otherwise>false</xsl:otherwise>
    </xsl:choose>
  </xsl:variable>
  subexists:      <xsl:value-of select="$subexists" />
</xsl:template>

And if you need the variable to have "global" scope then declare it outside of the template:

<xsl:variable name="subexists">
  <xsl:choose>
     <xsl:when test="/path/to/node/joined-subclass">true</xsl:when>
     <xsl:otherwise>false</xsl:otherwise>
  </xsl:choose>
</xsl:variable>

<xsl:template match="class">
   subexists:      <xsl:value-of select="$subexists" />
</xsl:template>

Python, creating objects

when you create an object using predefine class, at first you want to create a variable for storing that object. Then you can create object and store variable that you created.

class Student:
     def __init__(self):

# creating an object....

   student1=Student()

Actually this init method is the constructor of class.you can initialize that method using some attributes.. In that point , when you creating an object , you will have to pass some values for particular attributes..

class Student:
      def __init__(self,name,age):
            self.name=value
            self.age=value

 # creating an object.......

     student2=Student("smith",25)

How do I create a custom Error in JavaScript?

Another alternative , might not work in all enviroments.Atleast assured it works in nodejs 0.8 This approach uses a non standard way of modifying the internal proto prop

function myError(msg){ 
      var e = new Error(msg); 
      _this = this; 
      _this.__proto__.__proto__ = e;
}

Laravel Update Query

It is very simple to do. Code are given below :

 DB::table('user')->where('email', $userEmail)->update(array('member_type' => $plan));  

Reading a binary input stream into a single byte array in Java

You can use Apache commons-io for this task:

Refer to this method:

public static byte[] readFileToByteArray(File file) throws IOException

Update:

Java 7 way:

byte[] bytes = Files.readAllBytes(Paths.get(filename));

and if it is a text file and you want to convert it to String (change encoding as needed):

StandardCharsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString()

Getting Spring Application Context

Note that by storing any state from the current ApplicationContext, or the ApplicationContext itself in a static variable - for example using the singleton pattern - you will make your tests unstable and unpredictable if you're using Spring-test. This is because Spring-test caches and reuses application contexts in the same JVM. For example:

  1. Test A run and it is annotated with @ContextConfiguration({"classpath:foo.xml"}).
  2. Test B run and it is annotated with @ContextConfiguration({"classpath:foo.xml", "classpath:bar.xml})
  3. Test C run and it is annotated with @ContextConfiguration({"classpath:foo.xml"})

When Test A runs, an ApplicationContext is created, and any beans implemeting ApplicationContextAware or autowiring ApplicationContext might write to the static variable.

When Test B runs the same thing happens, and the static variable now points to Test B's ApplicationContext

When Test C runs, no beans are created as the TestContext (and herein the ApplicationContext) from Test A is resused. Now you got a static variable pointing to another ApplicationContext than the one currently holding the beans for your test.

Get difference between 2 dates in JavaScript?

Here is one way:

_x000D_
_x000D_
const date1 = new Date('7/13/2010');_x000D_
const date2 = new Date('12/15/2010');_x000D_
const diffTime = Math.abs(date2 - date1);_x000D_
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); _x000D_
console.log(diffTime + " milliseconds");_x000D_
console.log(diffDays + " days");
_x000D_
_x000D_
_x000D_

Observe that we need to enclose the date in quotes. The rest of the code gets the time difference in milliseconds and then divides to get the number of days. Date expects mm/dd/yyyy format.

In Java, remove empty elements from a list of Strings

Another way to do this now that we have Java 8 lambda expressions.

arrayList.removeIf(item -> item == null || "".equals(item));

Referring to the null object in Python

Null is a special object type like:

>>>type(None)
<class 'NoneType'>

You can check if an object is in class 'NoneType':

>>>variable = None
>>>variable is None
True

More information is available at Python Docs

Where is GACUTIL for .net Framework 4.0 in windows 7?

There is no Gacutil included in the .net 4.0 standard installation. They have moved the GAC too, from %Windir%\assembly to %Windir%\Microsoft.NET\Assembly.

They havent' even bothered adding a "special view" for the folder in Windows explorer, as they have for the .net 1.0/2.0 GAC.

Gacutil is part of the Windows SDK, so if you want to use it on your developement machine, just install the Windows SDK for your current platform. Then you will find it somewhere like this (depending on your SDK version):

C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools

There is a discussion on the new GAC here: .NET 4.0 has a new GAC, why?

If you want to install something in GAC on a production machine, you need to do it the "proper" way (gacutil was never meant as a tool for installing stuff on production servers, only as a development tool), with a Windows Installer, or with other tools. You can e.g. do it with PowerShell and the System.EnterpriseServices dll.

On a general note, and coming from several years of experience, I would personally strongly recommend against using GAC at all. Your application will always work if you deploy the DLL with each application in its bin folder as well. Yes, you will get multiple copies of the DLL on your server if you have e.g. multiple web apps on one server, but it's definitely worth the flexibility of being able to upgrade one application without breaking the others (by introducing an incompatible version of the shared DLL in the GAC).

Windows Batch: How to add Host-Entries?

Sometime I have to work from home and connect to office through vpn. Internal domain names should be resolved to different IPs at home. There are several names that have to be changed between office and home. For example:

At office, a => 192.168.0.3, b => 192.168.0.52. 
At home, a => 10.6.1.7, b => 10.4.5.23. 

My solution is to create two files: C:\WINDOWS\system32\drivers\etc\hosts-home and C:\WINDOWS\system32\drivers\etc\hosts-office. Each of them contains set of name-to-IP mapping. From Administrator PowerShell, When I work at the office, execute

C:\WINDOWS\system32> cp .\drivers\etc\hosts-office .\drivers\etc\hosts

When I arrive at home, execute

C:\WINDOWS\system32> cp .\drivers\etc\hosts-home .\drivers\etc\hosts

Filtering Pandas DataFrames on dates

I'm not allowed to write any comments yet, so I'll write an answer, if somebody will read all of them and reach this one.

If the index of the dataset is a datetime and you want to filter that just by (for example) months, you can do following:

df.loc[df.index.month == 3]

That will filter the dataset for you by March.

SQL Server remove milliseconds from datetime

There's more than one way to do it:

select 1 where datediff(second, '2010-07-20 03:21:52', '2010-07-20 03:21:52.577') >= 0

or

select *
from table
where datediff(second, '2010-07-20 03:21:52', date) >= 0 

one less function call, but you have to be beware of overflowing the max integer if the dates are too far apart.

python for increment inner loop

In python, for loops iterate over iterables, instead of incrementing a counter, so you have a couple choices. Using a skip flag like Artsiom recommended is one way to do it. Another option is to make a generator from your range and manually advance it by discarding an element using next().

iGen = (i for i in range(0, 6))
for i in iGen:
    print i
    if not i % 2:
        iGen.next()

But this isn't quite complete because next() might throw a StopIteration if it reaches the end of the range, so you have to add some logic to detect that and break out of the outer loop if that happens.

In the end, I'd probably go with aw4ully's solution with the while loops.

How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

Starting a shell in the Docker Alpine container

Nowadays, Alpine images will boot directly into /bin/sh by default, without having to specify a shell to execute:

$ sudo docker run -it --rm alpine  
/ # echo $0  
/bin/sh  

This is since the alpine image Dockerfiles now contain a CMD command, that specifies the shell to execute when the container starts: CMD ["/bin/sh"].

In older Alpine image versions (pre-2017), the CMD command was not used, since Docker used to create an additional layer for CMD which caused the image size to increase. This is something that the Alpine image developers wanted to avoid. In recent Docker versions (1.10+), CMD no longer occupies a layer, and so it was added to alpine images. Therefore, as long as CMD is not overridden, recent Alpine images will boot into /bin/sh.

For reference, see the following commit to the official Alpine Dockerfiles by Glider Labs:
https://github.com/gliderlabs/docker-alpine/commit/ddc19dd95ceb3584ced58be0b8d7e9169d04c7a3#diff-db3dfdee92c17cf53a96578d4900cb5b

Specifying colClasses in the read.csv

I know OP asked about the utils::read.csv function, but let me provide an answer for these that come here searching how to do it using readr::read_csv from the tidyverse.

read_csv ("test.csv", col_names=FALSE, col_types = cols (.default = "c", time = "i"))

This should set the default type for all columns as character, while time would be parsed as integer.

How can I truncate a string to the first 20 words in PHP?

function getShortString($string,$wordCount,$etc = true) 
{
     $expString = explode(' ',$string);
     $wordsInString = count($expString);
     if($wordsInString >= $wordCount )
     {
         $shortText = '';
         for($i=0; $i < $wordCount-1; $i++)
         {
             $shortText .= $expString[$i].' ';
         }
         return  $etc ? $shortText.='...' : $shortText; 
     }
     else return $string;
} 

How to reload page every 5 seconds?

For auto reload and clear cache after 3 second you can do it easily using javascript setInterval function. Here is simple code

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  setInterval(function() {_x000D_
    cache_clear()_x000D_
  }, 3000);_x000D_
});_x000D_
_x000D_
function cache_clear() {_x000D_
  window.location.reload(true);_x000D_
  // window.location.reload(); use this if you do not remove cache_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>_x000D_
<p>Auto reload page and clear cache</p>
_x000D_
_x000D_
_x000D_

and you can also use meta for this

<meta http-equiv="Refresh" content="5">

How to host material icons offline?

My recipe has three steps:

  1. to install material-design-icons package

    npm install material-design-icons
    
  2. to import material-icons.css file into .less or .scss file/ project

    @import "~/node_modules/material-design-icons/iconfont/material-icons.css";
    
  3. to include recommended code into the reactjs .js file/ project

    <i className='material-icons' style={{fontSize: '36px'}}>close</i>
    

Reload browser window after POST without prompting user to resend POST data

This worked

<button onclick="window.location.href=window.location.href; return false;">Continue</button>

The reason it doesn't work without the return false; is that the button click would trigger a form submit. With an explicit return false on it, it doesn't do the form submit and just does the reload of the same page that was a result of a previous POST to that page.

Failed to find Build Tools revision 23.0.1

Two solutions: You have to instal the required buildToolVersion or set it as described above.
Notice that if you are trying to set the buildToolsVersion "23.0.3" using Android Studio 3.0 or more it won't work until you remove all builversion you have keeping just one last version you use. I read this somewhere else and this works for me. Hope this helps.

Split string into strings by length?

And for dudes who prefer it to be a bit more readable:

def itersplit_into_x_chunks(string,x=10): # we assume here that x is an int and > 0
    size = len(string)
    chunksize = size//x
    for pos in range(0, size, chunksize):
        yield string[pos:pos+chunksize]

output:

>>> list(itersplit_into_x_chunks('qwertyui',x=4))
['qw', 'er', 'ty', 'ui']

How to get a List<string> collection of values from app.config in WPF?

You can create your own custom config section in the app.config file. There are quite a few tutorials around to get you started. Ultimately, you could have something like this:

<configSections>
    <section name="backupDirectories" type="TestReadMultipler2343.BackupDirectoriesSection, TestReadMultipler2343" />
  </configSections>

<backupDirectories>
   <directory location="C:\test1" />
   <directory location="C:\test2" />
   <directory location="C:\test3" />
</backupDirectories>

To complement Richard's answer, this is the C# you could use with his sample configuration:

using System.Collections.Generic;
using System.Configuration;
using System.Xml;

namespace TestReadMultipler2343
{
    public class BackupDirectoriesSection : IConfigurationSectionHandler
    {
        public object Create(object parent, object configContext, XmlNode section)
        {
            List<directory> myConfigObject = new List<directory>();

            foreach (XmlNode childNode in section.ChildNodes)
            {
                foreach (XmlAttribute attrib in childNode.Attributes)
                {
                    myConfigObject.Add(new directory() { location = attrib.Value });
                }
            }
            return myConfigObject;
        }
    }

    public class directory
    {
        public string location { get; set; }
    }
}

Then you can access the backupDirectories configuration section as follows:

List<directory> dirs = ConfigurationManager.GetSection("backupDirectories") as List<directory>;

On duplicate key ignore?

Would suggest NOT using INSERT IGNORE as it ignores ALL errors (ie its a sloppy global ignore). Instead, since in your example tag is the unique key, use:

INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c') ON DUPLICATE KEY UPDATE tag=tag;

on duplicate key produces:

Query OK, 0 rows affected (0.07 sec)

Python NameError: name is not defined

Define the class before you use it:

class Something:
    def out(self):
        print("it works")

s = Something()
s.out()

You need to pass self as the first argument to all instance methods.

What is the convention in JSON for empty vs. null?

Empty array for empty collections and null for everything else.

Convert datetime to Unix timestamp and convert it back in python

This class will cover your needs, you can pass the variable into ConvertUnixToDatetime & call which function you want it to operate based off.

from datetime import datetime
import time

class ConvertUnixToDatetime:
    def __init__(self, date):
        self.date = date

    # Convert unix to date object
    def convert_unix(self):
        unix = self.date

        # Check if unix is a string or int & proceeds with correct conversion
        if type(unix).__name__ == 'str':
            unix = int(unix[0:10])
        else:
            unix = int(str(unix)[0:10])

        date = datetime.utcfromtimestamp(unix).strftime('%Y-%m-%d %H:%M:%S')

        return date

    # Convert date to unix object
    def convert_date(self):
        date = self.date

        # Check if datetime object or raise ValueError
        if type(date).__name__ == 'datetime':
            unixtime = int(time.mktime(date.timetuple()))
        else:
            raise ValueError('You are trying to pass a None Datetime object')
        return type(unixtime).__name__, unixtime


if __name__ == '__main__':

    # Test Date
    date_test = ConvertUnixToDatetime(datetime.today())
    date_test = date_test.convert_date()
    print(date_test)

    # Test Unix
    unix_test = ConvertUnixToDatetime(date_test[1])
    print(unix_test.convert_unix())

Sorting int array in descending order

For primitive array types, you would have to write a reverse sort algorithm:

Alternatively, you can convert your int[] to Integer[] and write a comparator:

public class IntegerComparator implements Comparator<Integer> {

    @Override
    public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1);
    }
}

or use Collections.reverseOrder() since it only works on non-primitive array types.

and finally,

Integer[] a2 = convertPrimitiveArrayToBoxableTypeArray(a1);
Arrays.sort(a2, new IntegerComparator()); // OR
// Arrays.sort(a2, Collections.reverseOrder());

//Unbox the array to primitive type
a1 = convertBoxableTypeArrayToPrimitiveTypeArray(a2);

How do I include negative decimal numbers in this regular expression?

I have some experiments about regex in django url, which required from negative to positive numbers

^(?P<pid>(\-\d+|\d+))$

Let's we focused on this (\-\d+|\d+) part and ignoring others, this semicolon | means OR in regex, then the negative value will match with this \-\d+ part, and positive value into this \d+

How to group dataframe rows into list in pandas groupby

A handy way to achieve this would be:

df.groupby('a').agg({'b':lambda x: list(x)})

Look into writing Custom Aggregations: https://www.kaggle.com/akshaysehgal/how-to-group-by-aggregate-using-py

How can I use async/await at the top level?

To give some further info on top of current answers:

The contents of a node.js file are currently concatenated, in a string-like way, to form a function body.

For example if you have a file test.js:

// Amazing test file!
console.log('Test!');

Then node.js will secretly concatenate a function that looks like:

function(require, __dirname, ... perhaps more top-level properties) {
  // Amazing test file!
  console.log('Test!');
}

The major thing to note, is that the resulting function is NOT an async function. So you cannot use the term await directly inside of it!

But say you need to work with promises in this file, then there are two possible methods:

  1. Don't use await directly inside the function
  2. Don't use await

Option 1 requires us to create a new scope (and this scope can be async, because we have control over it):

// Amazing test file!
// Create a new async function (a new scope) and immediately call it!
(async () => {
  await new Promise(...);
  console.log('Test!');
})();

Option 2 requires us to use the object-oriented promise API (the less pretty but equally functional paradigm of working with promises)

// Amazing test file!
// Create some sort of promise...
let myPromise = new Promise(...);

// Now use the object-oriented API
myPromise.then(() => console.log('Test!'));

It would be interesting to see node add support for top-level await!

CheckBox in RecyclerView keeps on checking different items

What worked for me is to nullify the listeners on the viewHolder when the view is going to be recycled (onViewRecycled):

 override fun onViewRecycled(holder: AttendeeViewHolder) {
            super.onViewRecycled(holder)
            holder.itemView.hasArrived.setOnCheckedChangeListener(null);
            holder.itemView.edit.setOnClickListener { null }
        }

How do I prevent people from doing XSS in Spring MVC?

When you are trying to prevent XSS, it's important to think of the context. As an example how and what to escape is very different if you are ouputting data inside a variable in a javascript snippet as opposed to outputting data in an HTML tag or an HTML attribute.

I have an example of this here: http://erlend.oftedal.no/blog/?blogid=91

Also checkout the OWASP XSS Prevention Cheat Sheet: http://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet

So the short answer is, make sure you escape output like suggested by Tendayi Mawushe, but take special care when you are outputting data in HTML attributes or javascript.

mappedBy reference an unknown target entity property

I know the answer by @Pascal Thivent has solved the issue. I would like to add a bit more to his answer to others who might be surfing this thread.

If you are like me in the initial days of learning and wrapping your head around the concept of using the @OneToMany annotation with the 'mappedBy' property, it also means that the other side holding the @ManyToOne annotation with the @JoinColumn is the 'owner' of this bi-directional relationship.

Also, mappedBy takes in the instance name (mCustomer in this example) of the Class variable as an input and not the Class-Type (ex:Customer) or the entity name(Ex:customer).

BONUS : Also, look into the orphanRemoval property of @OneToMany annotation. If it is set to true, then if a parent is deleted in a bi-directional relationship, Hibernate automatically deletes it's children.

Mysql: Select all data between two dates

its very easy to handle this situation

You can use BETWEEN CLAUSE in combination with date_sub( now( ) , INTERVAL 30 DAY ) AND NOW( )

SELECT
    sc_cust_design.design_id as id,
    sc_cust_design.main_image,
    FROM
    sc_cust_design
WHERE
    sc_cust_design.publish = 1 
    AND **`datein`BETWEEN date_sub( now( ) , INTERVAL 30 DAY ) AND NOW( )**

Happy Coding :)

Keystore change passwords

[How can I] Change the password, so I can share it with others and let them sign

Using keytool:

keytool -storepasswd -keystore /path/to/keystore
Enter keystore password:  changeit
New keystore password:  new-password
Re-enter new keystore password:  new-password

Finding index of character in Swift String

let mystring:String = "indeep";
let findCharacter:Character = "d";

if (mystring.characters.contains(findCharacter))
{
    let position = mystring.characters.indexOf(findCharacter);
    NSLog("Position of c is \(mystring.startIndex.distanceTo(position!))")

}
else
{
    NSLog("Position of c is not found");
}

how to set "camera position" for 3d plots using python/matplotlib?

Minimal example varying azim, dist and elev

To add some simple sample images to what was explained at: https://stackoverflow.com/a/12905458/895245

Here is my test program:

#!/usr/bin/env python3

import sys

import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

if len(sys.argv) > 1:
    azim = int(sys.argv[1])
else:
    azim = None
if len(sys.argv) > 2:
    dist = int(sys.argv[2])
else:
    dist = None
if len(sys.argv) > 3:
    elev = int(sys.argv[3])
else:
    elev = None

# Make data.
X = np.arange(-5, 6, 1)
Y = np.arange(-5, 6, 1)
X, Y = np.meshgrid(X, Y)
Z = X**2

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, linewidth=0, antialiased=False)

# Labels.
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

if azim is not None:
    ax.azim = azim
if dist is not None:
    ax.dist = dist
if elev is not None:
    ax.elev = elev

print('ax.azim = {}'.format(ax.azim))
print('ax.dist = {}'.format(ax.dist))
print('ax.elev = {}'.format(ax.elev))

plt.savefig(
    'main_{}_{}_{}.png'.format(ax.azim, ax.dist, ax.elev),
    format='png',
    bbox_inches='tight'
)

Running it without arguments gives the default values:

ax.azim = -60
ax.dist = 10
ax.elev = 30

main_-60_10_30.png

enter image description here

Vary azim

The azimuth is the rotation around the z axis e.g.:

  • 0 means "looking from +x"
  • 90 means "looking from +y"

main_-60_10_30.png

enter image description here

main_0_10_30.png

enter image description here

main_60_10_30.png

enter image description here

Vary dist

dist seems to be the distance from the center visible point in data coordinates.

main_-60_10_30.png

enter image description here

main_-60_5_30.png

enter image description here

main_-60_20_-30.png

enter image description here

Vary elev

From this we understand that elev is the angle between the eye and the xy plane.

main_-60_10_60.png

enter image description here

main_-60_10_30.png

enter image description here

main_-60_10_0.png

enter image description here

main_-60_10_-30.png

enter image description here

Tested on matpotlib==3.2.2.

Fast Linux file count for a large number of files

Use find. For example:

find . -name "*.ext" | wc -l

How to replace a substring of a string

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

from javadoc.

Pipenv: Command Not Found

I have same problem with pipenv on Mac OS X 10.13 High Seirra, another Mac works just fine. I use Heroku to deploy my Django servers, some in 2.7 and some in 3.6. So, I need both 2.7 and 3.6. When HomeBrew install Python, it keeps python points to original 2.7, and python3 points to 3.6.

The problem might due to $ pip install pipenv. I checked /usr/local/bin and pipenv isn't there. So, I tried a full uninstall:

$ pip uninstall pipenv

Cannot uninstall requirement pipenv, not installed
You are using pip version 9.0.1, however version 10.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

$ pip3 uninstall pipenv
Skipping pipenv as it is not installed.

Then reinstall and works now:

$ pip3 install pipenv
Collecting pipenv

Twitter bootstrap hide element on small devices

For Bootstrap 4.0 there is a change

See the docs: https://getbootstrap.com/docs/4.0/utilities/display/

In order to hide the content on mobile and display on the bigger devices you have to use the following classes:

d-none d-sm-block

The first class set display none all across devices and the second one display it for devices "sm" up (you could use md, lg, etc. instead of sm if you want to show on different devices.

I suggest to read about that before migration:

https://getbootstrap.com/docs/4.0/migration/#responsive-utilities

What is secret key for JWT based authentication and how to generate it?

A Json Web Token made up of three parts. The header, the payload and the signature Now the header is just some metadata about the token itself and the payload is the data that we can encode into the token, any data really that we want. So the more data we want to encode here the bigger the JWT. Anyway, these two parts are just plain text that will get encoded, but not encrypted.

So anyone will be able to decode them and to read them, we cannot store any sensitive data in here. But that's not a problem at all because in the third part, so in the signature, is where things really get interesting. The signature is created using the header, the payload, and the secret that is saved on the server.

And this whole process is then called signing the Json Web Token. The signing algorithm takes the header, the payload, and the secret to create a unique signature. So only this data plus the secret can create this signature, all right? Then together with the header and the payload, these signature forms the JWT, which then gets sent to the client. enter image description here

Once the server receives a JWT to grant access to a protected route, it needs to verify it in order to determine if the user really is who he claims to be. In other words, it will verify if no one changed the header and the payload data of the token. So again, this verification step will check if no third party actually altered either the header or the payload of the Json Web Token.

So, how does this verification actually work? Well, it is actually quite straightforward. Once the JWT is received, the verification will take its header and payload, and together with the secret that is still saved on the server, basically create a test signature.

But the original signature that was generated when the JWT was first created is still in the token, right? And that's the key to this verification. Because now all we have to do is to compare the test signature with the original signature. And if the test signature is the same as the original signature, then it means that the payload and the header have not been modified. enter image description here

Because if they had been modified, then the test signature would have to be different. Therefore in this case where there has been no alteration of the data, we can then authenticate the user. And of course, if the two signatures are actually different, well, then it means that someone tampered with the data. Usually by trying to change the payload. But that third party manipulating the payload does of course not have access to the secret, so they cannot sign the JWT. So the original signature will never correspond to the manipulated data. And therefore, the verification will always fail in this case. And that's the key to making this whole system work. It's the magic that makes JWT so simple, but also extremely powerful.

Now let's do some practices with nodejs:

Configuration file is perfect for storing JWT SECRET data. Using the standard HSA 256 encryption for the signature, the secret should at least be 32 characters long, but the longer the better.

config.env:

JWT_SECRET = my-32-character-ultra-secure-and-ultra-long-secret
//after 90days JWT will no longer be valid, even the signuter is correct and everything is matched.
JWT_EXPIRES_IN=90

now install JWT using command

npm i jsonwebtoken

Example after user signup passing him JWT token so he can stay logged in and get access of resources.

exports.signup = catchAsync(async (req, res, next) => {
  const newUser = await User.create({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
    passwordConfirm: req.body.passwordConfirm,
  });
  const token = jwt.sign({ id: newUser._id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN,
  });

  res.status(201).json({
    status: 'success',
    token,
    data: {
      newUser,
    },
  });
});

output: enter image description here

In my opinion, do not take help from a third-party to generate your super-secret key, because you can't say it's secret anymore. Just use your keyboard.

jQuery UI Tabs - How to Get Currently Selected Tab Index

In case if you find Active tab Index and then point to Active Tab

First get the Active index

var activeIndex = $("#panel").tabs('option', 'active');

Then using the css class get the tab content panel

// this will return the html element
var element=   $("#panel").find( ".ui-tabs-panel" )[activeIndex]; 

now wrapped it in jQuery object to further use it

 var tabContent$ = $(element);

here i want to add two info the class .ui-tabs-nav is for Navigation associated with and .ui-tabs-panel is associated with tab content panel. in this link demo in jquery ui website you will see this class is used - http://jqueryui.com/tabs/#manipulation

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

Maybe a little late to reply. I happen to run into the same problem today. I find that on Windows you can change the console encoder to utf-8 or other encoder that can represent your data. Then you can print it to sys.stdout.

First, run following code in the console:

chcp 65001
set PYTHONIOENCODING=utf-8

Then, start python do anything you want.

Get current time in milliseconds in Python?

time.time() may only give resolution to the second, the preferred approach for milliseconds is datetime.

from datetime import datetime
dt = datetime.now()
dt.microsecond

ExecuteReader: Connection property has not been initialized

After SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)values('.... Add

cmd.Connection = conn;

Hope this help

How do I add a .click() event to an image?

First of all, this line

<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />.click()

You're mixing HTML and JavaScript. It doesn't work like that. Get rid of the .click() there.

If you read the JavaScript you've got there, document.getElementById('foo') it's looking for an HTML element with an ID of foo. You don't have one. Give your image that ID:

<img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />

Alternatively, you could throw the JS in a function and put an onclick in your HTML:

<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" onclick="myfunction()" />

I suggest you do some reading up on JavaScript and HTML though.


The others are right about needing to move the <img> above the JS click binding too.

HTTPS connections over proxy servers

If it's still of interest, here is an answer to a similar question: Convert HTTP Proxy to HTTPS Proxy in Twisted

To answer the second part of the question:

If yes, what kind of proxy server allows this?

Out of the box, most proxy servers will be configured to allow HTTPS connections only to port 443, so https URIs with custom ports wouldn't work. This is generally configurable, depending on the proxy server. Squid and TinyProxy support this, for example.

how do I get eclipse to use a different compiler version for Java?

Just to clarify, do you have JAVA_HOME set as a system variable or set in Eclipse classpath variables? I'm pretty sure (but not totally sure!) that the system variable is used by the command line compiler (and Ant), but that Eclipse modifies this accroding to the JDK used

Docker - a way to give access to a host USB or serial device?

With latest versions of docker, this is enough:

docker run -ti --privileged ubuntu bash

It will give access to all system resources (in /dev for instance)

Vagrant shared and synced folders

shared folders VS synced folders

Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf between host and guest (there is known performance issues if there are large numbers of files/directories).

Vagrantfile directory mounted as /vagrant in guest

Vagrant is mounting the current working directory (where Vagrantfile resides) as /vagrant in the guest, this is the default behaviour.

See docs

NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.

You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true in your Vagrantfile.

Why synced folder is not working

Based on the output /tmp on host was NOT mounted during up time.

Use VAGRANT_INFO=debug vagrant up or VAGRANT_INFO=debug vagrant reload to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp on host should be drwxrwxrwt).

I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)

config.vm.synced_folder "/tmp", "/tmp/src"

output

$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src

Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw).

Convert python datetime to epoch with strftime

if you just need a timestamp in unix /epoch time, this one line works:

created_timestamp = int((datetime.datetime.now() - datetime.datetime(1970,1,1)).total_seconds())
>>> created_timestamp
1522942073L

and depends only on datetime works in python2 and python3

How to add a RequiredFieldValidator to DropDownList control?

For the most part you treat it as if you are validating any other kind of control but use the InitialValue property of the required field validator.

<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="your-dropdownlist" InitialValue="Please select" ErrorMessage="Please select something" />

Basically what it's saying is that validation will succeed if any other value than the 1 set in InitialValue is selected in the dropdownlist.

If databinding you will need to insert the "Please select" value afterwards as follows

this.ddl1.Items.Insert(0, "Please select");

How can I edit javascript in my browser like I can use Firebug to edit CSS/HTML?

I would still recommend Firebug. Not only it can debug JS within your JSP files, it can enhance debugging experience with addons like JS Deminifier (if your production JS is minified), FireQuery, FireRainbow and more.

There is also Firebug lite which is nothing but a bookmarklet. It lets you do limited things but still is useful.

Chrome as a developer console built-in that would let you modify javascript.

Using these tools, you should be able to inject your own JS too.

Is there a way to only install the mysql client (Linux)?

To install only mysql (client) you should execute

yum install mysql

To install mysql client and mysql server:

yum install mysql mysql-server

How can I delete derived data in Xcode 8?

For Xcode Version 8.2 (8C38), you can remove the projects completely (project name in Xcode, programs, data, etc.) one by one by doing the following: [Note: the instructions are not for just remove the project names from the Welcome Window]

Launch the Xocde and wait until the Welcome window is displayed. The projects will be shown on the right hand side (see below) Xcode Welcome Window

Right click the project you want to remove completely and a pop window [Show in Folder] jumps out; selec it to find out where is the project in the [Finder] (see below) Find the project folder

Right click the project folder in the Finder to find it’s path through [Get Info]; use path in the Info window to go to the parent folder, and go to there[Locate the project folder path] (see below)

Right click the Project Folder (e.g. DemoProject01) and Porject file (DemoProject01.xcodeproj) and select [Move to Trash] ; you will see that (a) the folder in finder is removed AND (b) the Project in the Xcode Welcome Window’s Project List is removed.

Edit seaborn legend

If legend_out is set to True then legend is available thought g._legend property and it is a part of a figure. Seaborn legend is standard matplotlib legend object. Therefore you may change legend texts like:

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = True)

# title
new_title = 'My title'
g._legend.set_title(new_title)
# replace labels
new_labels = ['label 1', 'label 2']
for t, l in zip(g._legend.texts, new_labels): t.set_text(l)

sns.plt.show()

enter image description here

Another situation if legend_out is set to False. You have to define which axes has a legend (in below example this is axis number 0):

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = False)

# check axes and find which is have legend
leg = g.axes.flat[0].get_legend()
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels): t.set_text(l)
sns.plt.show()

enter image description here

Moreover you may combine both situations and use this code:

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = True)

# check axes and find which is have legend
for ax in g.axes.flat:
    leg = g.axes.flat[0].get_legend()
    if not leg is None: break
# or legend may be on a figure
if leg is None: leg = g._legend

# change legend texts
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels): t.set_text(l)

sns.plt.show()

This code works for any seaborn plot which is based on Grid class.

How to sign an android apk file

I ran into this problem and was solved by checking the min sdk version in the manifest. It was set to 15 (ICS), but my phone was running 10(Gingerbread)

Make button width fit to the text

Keeping the element's size relative to its content can also be done with display: inline-flex and display: table

The centering can be done with..

  • text-align: center; on the parent (or above, it's inherited)

  • display: flex; and justify-content: center; on the parent

  • position: absolute; left: 50%; transform: translateX(-50%); on the element with position: relative; (at least) on the parent.

Here's a flexbox guide from CSS Tricks

Here's an article on centering from CSS Tricks.

Keeping an element only as wide as its content..

  • Can use display: table;

  • Or inline-anything including inline-flex as used in my snippet example below.

Keep in mind that when centering with flexbox's justify-content: center; when the text wraps the text will align left. So you will still need text-align: center; if your site is responsive and you expect lines to wrap.

_x000D_
_x000D_
body {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  height: 100vh;_x000D_
  padding: 20px;_x000D_
}_x000D_
.container {_x000D_
  display: flex;_x000D_
  justify-content: center; /* center horizontally */_x000D_
  align-items: center; /* center vertically */_x000D_
  height: 50%;_x000D_
}_x000D_
.container.c1 {_x000D_
  text-align: center; /* needed if the text wraps */_x000D_
  /* text-align is inherited, it can be put on the parent or the target element */_x000D_
}_x000D_
.container.c2 {_x000D_
 /* without text-align: center; */_x000D_
}_x000D_
.button {_x000D_
  padding: 5px 10px;_x000D_
  font-size: 30px;_x000D_
  text-decoration: none;_x000D_
  color: hsla(0, 0%, 90%, 1);_x000D_
  background: linear-gradient(hsla(21, 85%, 51%, 1), hsla(21, 85%, 61%, 1));_x000D_
  border-radius: 10px;_x000D_
  box-shadow: 2px 2px 15px -5px hsla(0, 0%, 0%, 1);_x000D_
}_x000D_
.button:hover {_x000D_
  background: linear-gradient(hsl(207.5, 84.8%, 51%), hsla(207, 84%, 62%, 1));_x000D_
  transition: all 0.2s linear;_x000D_
}_x000D_
.button.b1 {_x000D_
    display: inline-flex; /* element only as wide as content */_x000D_
}_x000D_
.button.b2 {_x000D_
    display: table; /* element only as wide as content */_x000D_
}
_x000D_
<div class="container c1">_x000D_
  <a class="button b1" href="https://stackoverflow.com/questions/27722872/">This Text Is Centered Before And After Wrap</a>_x000D_
</div>_x000D_
<div class="container c2">_x000D_
  <a class="button b2" href="https://stackoverflow.com/questions/27722872/">This Text Is Centered Only Before Wrap</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle

https://jsfiddle.net/Hastig/02fbs3pv/

Performing user authentication in Java EE / JSF using j_security_check

After searching the Web and trying many different ways, here's what I'd suggest for Java EE 6 authentication:

Set up the security realm:

In my case, I had the users in the database. So I followed this blog post to create a JDBC Realm that could authenticate users based on username and MD5-hashed passwords in my database table:

http://blog.gamatam.com/2009/11/jdbc-realm-setup-with-glassfish-v3.html

Note: the post talks about a user and a group table in the database. I had a User class with a UserType enum attribute mapped via javax.persistence annotations to the database. I configured the realm with the same table for users and groups, using the userType column as the group column and it worked fine.

Use form authentication:

Still following the above blog post, configure your web.xml and sun-web.xml, but instead of using BASIC authentication, use FORM (actually, it doesn't matter which one you use, but I ended up using FORM). Use the standard HTML , not the JSF .

Then use BalusC's tip above on lazy initializing the user information from the database. He suggested doing it in a managed bean getting the principal from the faces context. I used, instead, a stateful session bean to store session information for each user, so I injected the session context:

 @Resource
 private SessionContext sessionContext;

With the principal, I can check the username and, using the EJB Entity Manager, get the User information from the database and store in my SessionInformation EJB.

Logout:

I also looked around for the best way to logout. The best one that I've found is using a Servlet:

 @WebServlet(name = "LogoutServlet", urlPatterns = {"/logout"})
 public class LogoutServlet extends HttpServlet {
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   HttpSession session = request.getSession(false);

   // Destroys the session for this user.
   if (session != null)
        session.invalidate();

   // Redirects back to the initial page.
   response.sendRedirect(request.getContextPath());
  }
 }

Although my answer is really late considering the date of the question, I hope this helps other people that end up here from Google, just like I did.

Ciao,

Vítor Souza

HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.)

In your web.config, make sure these keys exist:

<configuration>
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
    </system.webServer>
</configuration>

Generating statistics from Git repository

I'm doing a git repository statistics generator in ruby, it's called git_stats.

You can find examples generated for some repositories on project page.

Here is a list of what it can do:

  • General statistics
    • Total files (text and binary)
    • Total lines (added and deleted)
    • Total commits
    • Authors
  • Activity (total and per author)
    • Commits by date
    • Commits by hour of day
    • Commits by day of week
    • Commits by hour of week
    • Commits by month of year
    • Commits by year
    • Commits by year and month
  • Authors
    • Commits by author
    • Lines added by author
    • Lines deleted by author
    • Lines changed by author
  • Files and lines
    • By date
    • By extension

If you have any idea what to add or improve please let me know, I would appreciate any feedback.

Float to String format specifier

Firstly, as Etienne says, float in C# is Single. It is just the C# keyword for that data type.

So you can definitely do this:

float f = 13.5f;
string s = f.ToString("R");

Secondly, you have referred a couple of times to the number's "format"; numbers don't have formats, they only have values. Strings have formats. Which makes me wonder: what is this thing you have that has a format but is not a string? The closest thing I can think of would be decimal, which does maintain its own precision; however, calling simply decimal.ToString should have the effect you want in that case.

How about including some example code so we can see exactly what you're doing, and why it isn't achieving what you want?

How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

One line fixes this:

modelBuilder.Properties<DateTime>().Configure(c => c.HasColumnType("datetime2"));

So, in my code, I added:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Properties<DateTime>().Configure(c => c.HasColumnType("datetime2"));
}

Adding that one line to the DBContext subclass override void OnModelCreating section should work.

Google Maps API 3 - Custom marker color for default (dot) marker

Well the closest thing I've been able to get with the StyledMarker is this.

The bullet in the middle isn't quite a big as the default one though. The StyledMarker class simply builds this url and asks the google api to create the marker.

From the class use example use "%E2%80%A2" as your text, as in:

var styleMaker2 = new StyledMarker({styleIcon:new StyledIcon(StyledIconTypes.MARKER,{text:"%E2%80%A2"},styleIconClass),position:new google.maps.LatLng(37.263477473067, -121.880502070713),map:map});

You will need to modifiy StyledMarker.js to comment out the lines:

  if (text_) {
    text_ = text_.substr(0,2);
  }

as this will trim the text string to 2 characters.

Alternatively you could create custom marker images based on the default one with the colors you desire and override the default marker with code such as this:

marker = new google.maps.Marker({
  map:map,
  position: latlng,
  icon: new google.maps.MarkerImage(
    'http://www.gettyicons.com/free-icons/108/gis-gps/png/24/needle_left_yellow_2_24.png',
    new google.maps.Size(24, 24),
    new google.maps.Point(0, 0),
    new google.maps.Point(0, 24)
  )
});

JSON.NET Error Self referencing loop detected for type

We can add these two lines into DbContext class constructor to disable Self referencing loop, like

public TestContext()
        : base("name=TestContext")
{
    this.Configuration.LazyLoadingEnabled = false;
    this.Configuration.ProxyCreationEnabled = false;
}

SQLite3 database or disk is full / the database disk image is malformed

while using Google App Engine, i had this problem. For some reason i did following since then Google App Engine was never starting.

$ echo '' > /tmp/appengine.apprtc.root/*.db

To fix it i required to do manually:

$ sqlite3 datastore.db
sqlite> begin immediate;
<press CTRL+Z>
$ cp datastore.db logs.db

And then run the Google App Engine with flag:

$ dev_appserver.py --clear_datastore --clear_search_index

after that it finally worked.

How to use Collections.sort() in Java?

Use the method that accepts a Comparator when you want to sort in something other than natural order.

Collections.sort(List, Comparator)

MomentJS getting JavaScript Date in UTC

Or simply:

Date.now

From MDN documentation:

The Date.now() method returns the number of milliseconds elapsed since January 1, 1970

Available since ECMAScript 5.1

It's the same as was mentioned above (new Date().getTime()), but more shortcutted version.

How to set Java environment path in Ubuntu

  1. Update bashrc file to add JAVA_HOME

    sudo nano ~/.bashrc

  2. Add JAVA_HOME to bashrc file.

    export JAVA_HOME=/usr/java/<your version of java>
    export PATH=${PATH}:${JAVA_HOME}/bin

  3. Ensure Java is accessible

    java -version

  4. In Case of Manual installation of JDK, If you got an error as shown below

    Error occurred during initialization of VM
    java/lang/NoClassDefFoundError: java/lang/Object
    
  5. Execute the following command in your JAVA_HOME/lib directory:

    unpack200 -r -v -l "" tools.pack tools.jar

  6. Execute the following commands in your JAVA_HOME/jre/lib

    ../../bin/unpack200 rt.pack rt.jar ../../bin/unpack200 jsse.pack jsse.rar ../../bin/unpack200 charsets.pack charsets.jar

  7. Ensure Java is accessible

    java -version

how to use DEXtoJar

  1. Download dex2jar https://code.google.com/p/dex2jar/downloads/list
  2. Run dex2jar on apk d2j-dex2jar.sh someApk.apk
  3. open jar file in JD GUI http://jd.benow.ca/

Follow this guide: https://code.google.com/p/dex2jar/wiki/UserGuide

--Update 10/11/2016--

Found this ClassyShark from Google's github pretty easy to view code from APK.

https://github.com/google/android-classyshark

// make sure that you downloaded release https://github.com/pxb1988/dex2jar/releases (for the ppl who coldnt find this link in /dex2jar/downloads/list

What is a good naming convention for vars, methods, etc in C++?

I actually often use Java style: PascalCase for type names, camelCase for functions and variables, CAPITAL_WORDS for preprocessor macros. I prefer that over the Boost/STL conventions because you don't have to suffix types with _type. E.g.

Size size();

instead of

size_type size();   // I don't like suffixes

This has the additional benefit that the StackOverflow code formatter recognizes Size as a type name ;-)

pycharm convert tabs to spaces automatically

For me it was having a file called ~/.editorconfig that was overriding my tab settings. I removed that (surely that will bite me again someday) but it fixed my pycharm issue

How can I call the 'base implementation' of an overridden virtual method?

You can do it, but not at the point you've specified. Within the context of B, you may invoke A.X() by calling base.X().

How to fix SSL certificate error when running Npm on Windows?

I was having same issue. After some digging I realized that many post/pre-install scripts would try to install various dependencies and some times specific repositories are used. A better way is to disable certificate check for https module for nodejs that worked for me.

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"

From this question

adding css file with jquery

This is how I add css using jQuery ajax. Hope it helps someone..

$.ajax({
            url:"site/test/style.css",
            success:function(data){
                 $("<style></style>").appendTo("head").html(data);
            }
        })

Hashing a file in Python

TL;DR use buffers to not use tons of memory.

We get to the crux of your problem, I believe, when we consider the memory implications of working with very large files. We don't want this bad boy to churn through 2 gigs of ram for a 2 gigabyte file so, as pasztorpisti points out, we gotta deal with those bigger files in chunks!

import sys
import hashlib

# BUF_SIZE is totally arbitrary, change for your app!
BUF_SIZE = 65536  # lets read stuff in 64kb chunks!

md5 = hashlib.md5()
sha1 = hashlib.sha1()

with open(sys.argv[1], 'rb') as f:
    while True:
        data = f.read(BUF_SIZE)
        if not data:
            break
        md5.update(data)
        sha1.update(data)

print("MD5: {0}".format(md5.hexdigest()))
print("SHA1: {0}".format(sha1.hexdigest()))

What we've done is we're updating our hashes of this bad boy in 64kb chunks as we go along with hashlib's handy dandy update method. This way we use a lot less memory than the 2gb it would take to hash the guy all at once!

You can test this with:

$ mkfile 2g bigfile
$ python hashes.py bigfile
MD5: a981130cf2b7e09f4686dc273cf7187e
SHA1: 91d50642dd930e9542c39d36f0516d45f4e1af0d
$ md5 bigfile
MD5 (bigfile) = a981130cf2b7e09f4686dc273cf7187e
$ shasum bigfile
91d50642dd930e9542c39d36f0516d45f4e1af0d  bigfile

Hope that helps!

Also all of this is outlined in the linked question on the right hand side: Get MD5 hash of big files in Python


Addendum!

In general when writing python it helps to get into the habit of following pep-8. For example, in python variables are typically underscore separated not camelCased. But that's just style and no one really cares about those things except people who have to read bad style... which might be you reading this code years from now.

PHP: How to check if a date is today, yesterday or tomorrow

function get_when($date) {

    $current = strtotime(date('Y-m-d H:i'));

    $date_diff = $date - $current;
    $difference = round($date_diff/(60*60*24));

    if($difference >= 0) {
            return 'Today';
    } else if($difference == -1) {
            return 'Yesterday';
    } else if($difference == -2 || $difference == -3  || $difference == -4 || $difference == -5) {
            return date('l', $date);
    } else {
            return ('on ' . date('jS/m/y', $date));
    }

}

get_when(date('Y-m-d H:i', strtotime($your_targeted_date)));

"code ." Not working in Command Line for Visual Studio Code on OSX/Mac

Alternative to commandline Solution:

Recently I was playing with Services in Mac OS X. I added a service to a folder or file so that I can open that folder or file in Visual Studio Code. I think this could be an alternative to using 'code .' command if you are using the Finder app. Here are the steps:

  • Open Automator App from Application. (Or you can use Spotlight).
  • Click on 'New Document' button to create a new script.
  • Choose 'Service' as a new type of document.
  • Select 'files and folders' in 'Service receives selected' dropdown.
  • Search for 'Open Finder Items' action item.
  • Drag that action item to the workflow area.
  • Select 'Visual Studio Code.app' application in the action 'Open with' dropdown.
  • Press 'command + s' to save the service. It will ask a name of service. Give it a name. I gave 'Open with VSCode'. Close the Automator app. Check the image below for more information.

enter image description here

Verify:

  • Open the Finder app.
  • Right-click on any folder.
  • In the context menu, look for 'Open with VSCode' menu option.
  • Click on the 'Open with VSCode' menu option.
  • The folder should get open in the Visual Studio Code application. Check image below for more info.

enter image description here

how to install gcc on windows 7 machine?

I use msysgit to install gcc on Windows, it has a nice installer which installs most everything that you might need. Most devs will need more than just the compiler, e.g. the shell, shell tools, make, git, svn, etc. msysgit comes with all of that. https://msysgit.github.io/

edit: I am now using msys2. Msys2 uses pacman from Arch Linux to install packages, and includes three environments, for building msys2 apps, 32-bit native apps, and 64-bit native apps. (You probably want to build 32-bit native apps.)

https://msys2.github.io/

You could also go full-monty and install code::blocks or some other gui editor that comes with a compiler. I prefer to use vim and make.

Differences in string compare methods in C#

Using .Equals is also a lot easier to read.

How to compare strings in sql ignoring case?

before comparing the two or more strings first execute the following commands

alter session set NLS_COMP=LINGUISTIC;
alter session set NLS_SORT=BINARY_CI;

after those two statements executed then you may compare the strings and there will be case insensitive.for example you had two strings s1='Apple' and s2='apple', if yow want to compare the two strings before executing the above statements then those two strings will be treated as two different strings but when you compare the strings after the execution of the two alter statements then those two strings s1 and s2 will be treated as the same string

reasons for using those two statements

We need to set NLS_COMP=LINGUISTIC and NLS_SORT=BINARY_CI in order to use 10gR2 case insensitivity. Since these are session modifiable, it is not as simple as setting them in the initialization parameters. We can set them in the initialization parameters but they then only affect the server and not the client side.

What is the correct way to read a serial port using .NET framework?

    using System;
    using System.IO.Ports;
    using System.Threading;

    namespace SerialReadTest
    {
        class SerialRead
        {
            static void Main(string[] args)
            {
        Console.WriteLine("Serial read init");
        SerialPort port = new SerialPort("COM6", 115200, Parity.None, 8, StopBits.One);
        port.Open();
        while(true){
          Console.WriteLine(port.ReadLine());
        }

    }
}
}

Delete worksheet in Excel using VBA

Consider:

Sub SheetKiller()
    Dim s As Worksheet, t As String
    Dim i As Long, K As Long
    K = Sheets.Count

    For i = K To 1 Step -1
        t = Sheets(i).Name
        If t = "ID Sheet" Or t = "Summary" Then
            Application.DisplayAlerts = False
                Sheets(i).Delete
            Application.DisplayAlerts = True
        End If
    Next i
End Sub

NOTE:

Because we are deleting, we run the loop backwards.

Origin is not allowed by Access-Control-Allow-Origin

You may make it work without modifiying the server by making the broswer including the header Access-Control-Allow-Origin: * in the HTTP OPTIONS' responses.

In Chrome, use this extension. If you are on Mozilla check this answer.

Get HTML code using JavaScript with a URL

There is a tutorial on how to use Ajax here: https://www.w3schools.com/xml/ajax_intro.asp

This is an example code taken from that tutorial:

<html>

<head>
    <script type="text/javascript">
        function loadXMLDoc()
        {
            var xmlhttp;
            if (window.XMLHttpRequest)
            {
              // Code for Internet Explorer 7+, Firefox, Chrome, Opera, and Safari
              xmlhttp = new XMLHttpRequest();
            }
            else
            {
                // Code for Internet Explorer 6 and Internet Explorer 5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET", "ajax_info.txt", true);
            xmlhttp.send();
        }
    </script>
</head>

<body>
    <div id="myDiv"><h2>Let AJAX change this text</h2></div>
    <button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>

</html>

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET);

$timelines = $connection->get('statuses/user_timeline', array('screen_name' => 'NSE_NIFTY', 'count' => 100, 'include_rts' => 1));

How can I find the latitude and longitude from address?

If you want to place your address in google map then easy way to use following

Intent searchAddress = new  Intent(Intent.ACTION_VIEW,Uri.parse("geo:0,0?q="+address));
startActivity(searchAddress);

OR

if you needed to get lat long from your address then use Google Place Api following

create a method that returns a JSONObject with the response of the HTTP Call like following

public static JSONObject getLocationInfo(String address) {
        StringBuilder stringBuilder = new StringBuilder();
        try {

        address = address.replaceAll(" ","%20");    

        HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        stringBuilder = new StringBuilder();


            response = client.execute(httppost);
            HttpEntity entity = response.getEntity();
            InputStream stream = entity.getContent();
            int b;
            while ((b = stream.read()) != -1) {
                stringBuilder.append((char) b);
            }
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        }

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = new JSONObject(stringBuilder.toString());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return jsonObject;
    }

now pass that JSONObject to getLatLong() method like following

public static boolean getLatLong(JSONObject jsonObject) {

        try {

            longitute = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lng");

            latitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lat");

        } catch (JSONException e) {
            return false;

        }

        return true;
    }

I hope this helps to you nd others..!! Thank you..!!

How can I remove file extension from a website address?

Tony, your script is ok, but if you have 100 files? Need add this code in all these :

include_once('scripts.php');
strip_php_extension();

I think you include a menu in each php file (probably your menu is showed in all your web pages), so you can add these 2 lines of code only in your menu file. This work for me :D

Convert a Pandas DataFrame to a dictionary

Try to use Zip

df = pd.read_csv("file")
d= dict([(i,[a,b,c ]) for i, a,b,c in zip(df.ID, df.A,df.B,df.C)])
print d

Output:

{'p': [1, 3, 2], 'q': [4, 3, 2], 'r': [4, 0, 9]}

Simple example for Intent and Bundle

Try this: if you need pass values between the activities you use this...

This is code for Main_Activity put the values to intent

 String name="aaaa";
 Intent intent=new Intent(Main_Activity.this,Other_Activity.class);
 intent.putExtra("name", name);
 startActivity(intent);

This code for Other_Activity and get the values form intent

    Bundle b = new Bundle();
    b = getIntent().getExtras();
    String name = b.getString("name");

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

You can just put r in front of the string with your actual path, which denotes a raw string. For example:

data = open(r"C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener")

Function to calculate distance between two coordinates

I try to make the code a little bit understandable by naming the variables, I hope this can help

function getDistanceFromLatLonInKm(point1, point2) {

  const [lat1, lon1] = point1;
  const [lat2, lon2] = point2;
  const earthRadius = 6371;
  const dLat = convertDegToRad(lat2 - lat1);
  const dLon = convertDegToRad(lon2 - lon1);
  const squarehalfChordLength =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(convertDegToRad(lat1)) * Math.cos(convertDegToRad(lat2)) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);

  const angularDistance = 2 * Math.atan2(Math.sqrt(squarehalfChordLength), Math.sqrt(1 - squarehalfChordLength));
  const distance = earthRadius * angularDistance;
  return distance;

}

What do pty and tty mean?

A tty is a terminal (it stands for teletype - the original terminals used a line printer for output and a keyboard for input!). A terminal is a basically just a user interface device that uses text for input and output.

A pty is a pseudo-terminal - it's a software implementation that appears to the attached program like a terminal, but instead of communicating directly with a "real" terminal, it transfers the input and output to another program.

For example, when you ssh in to a machine and run ls, the ls command is sending its output to a pseudo-terminal, the other side of which is attached to the SSH daemon.

css3 text-shadow in IE9

As IE9 does not support CSS3 text-shadow, I would just use the filter property for IE instead. Live example: http://jsfiddle.net/dmM2S/

text-shadow:1px 1px 1px red; /* CSS3 */

can be replaced with

filter: Shadow(Color=red, Direction=130, Strength=1); /* IE Proprietary Filter*/

You can get the results to be very similar.