Programs & Examples On #Voting system

Unsupported major.minor version 52.0 when rendering in Android Studio

I've all done, setting JAVA_HOME, JAVA8_HOME, ... and i had always the error. For me the solution was to set the version 2.1.0 of gradle to work with Jdk 1.8.0_92 and android studio 2.11

dependencies {
    classpath 'com.android.tools.build:gradle:2.1.0'
    //classpath 'com.android.tools.build:gradle:2.+'
}

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

Javascript - validation, numbers only

Match against /^\d+$/. $ means "end of line", so any non-digit characters after the initial run of digits will cause the match to fail.

Edit:

RobG wisely suggests the more succinct /\D/.test(z). This operation tests the inverse of what you want. It returns true if the input has any non-numeric characters.

Simply omit the negating ! and use if(/\D/.test(z)).

Problems with local variable scope. How to solve it?

I found this approach useful. This way you do not need a class nor final

 btnInsert.addMouseListener(new MouseAdapter() {
        private Statement _statement;

        public MouseAdapter setStatement(Statement _stmnt)
        {
            _statement = _stmnt;
            return this;
        }
        @Override
        public void mouseDown(MouseEvent e) {
            String name = text.getText();
            String from = text_1.getText();
            String to = text_2.getText();
            String price = text_3.getText();

            String query = "INSERT INTO booking (name, fromst, tost, price) VALUES ('"+name+"', '"+from+"', '"+to+"', '"+price+"')";
            try {
                _statement.executeUpdate(query);
            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }.setStatement(statement));

Create sequence of repeated values, in sequence?

Another base R option could be gl():

gl(5, 3)

Where the output is a factor:

 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
Levels: 1 2 3 4 5

If integers are needed, you can convert it:

as.numeric(gl(5, 3))

 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5

What does request.getParameter return?

Both if (one.length() > 0) {} and if (!"".equals(one)) {} will check against an empty foo parameter, and an empty parameter is what you'd get if the the form is submitted with no value in the foo text field.

If there's any chance you can use the Expression Language to handle the parameter, you could access it with empty param.foo in an expression.

<c:if test='${not empty param.foo}'>
    This page code gets rendered.
</c:if>

How to start rails server?

Rails version < 2
From project root run:

./script/server

MySQL CURRENT_TIMESTAMP on create and on update

This is the tiny limitation of Mysql in older version , actually after version 5.6 and later multiple timestamps works...

How to add title to seaborn boxplot

Seaborn box plot returns a matplotlib axes instance. Unlike pyplot itself, which has a method plt.title(), the corresponding argument for an axes is ax.set_title(). Therefore you need to call

sns.boxplot('Day', 'Count', data= gg).set_title('lalala')

A complete example would be:

import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips")
sns.boxplot(x=tips["total_bill"]).set_title("LaLaLa")

plt.show()

Of course you could also use the returned axes instance to make it more readable:

ax = sns.boxplot('Day', 'Count', data= gg)
ax.set_title('lalala')
ax.set_ylabel('lololo')

Spring JSON request getting 406 (not Acceptable)

I was having the same problem because I was missing the @EnableWebMvc annotation. (All of my spring configurations are annotation-based, the XML equivalent would be mvc:annotation-driven)

How to catch an Exception from a thread

AtomicReference is also a solution to pass the error to the main thread .Is same approach like the one of Dan Cruz .

AtomicReference<Throwable> errorReference = new AtomicReference<>();

    Thread thread = new Thread() {
        public void run() {
            throw new RuntimeException("TEST EXCEPTION");

        }
    };
    thread.setUncaughtExceptionHandler((th, ex) -> {
        errorReference.set(ex);
    });
    thread.start();
    thread.join();
    Throwable newThreadError= errorReference.get();
    if (newThreadError!= null) {
        throw newThreadError;
    }  

The only change is that instead of creating a volatile variable you can use AtomicReference which did same thing behind the scenes.

Call a REST API in PHP

You can access any REST API with PHPs cURL Extension. However, the API Documentation (Methods, Parameters etc.) must be provided by your Client!

Example:

// Method: POST, PUT, GET etc
// Data: array("param" => "value") ==> index.php?param=value

function CallAPI($method, $url, $data = false)
{
    $curl = curl_init();

    switch ($method)
    {
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);

            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_PUT, 1);
            break;
        default:
            if ($data)
                $url = sprintf("%s?%s", $url, http_build_query($data));
    }

    // Optional Authentication:
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($curl, CURLOPT_USERPWD, "username:password");

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $result = curl_exec($curl);

    curl_close($curl);

    return $result;
}

AngularJS: How to make angular load script inside ng-include?

The accepted answer won't work from 1.2.0-rc1+ (Github issue).

Here's a quick fix created by endorama:

/*global angular */
(function (ng) {
  'use strict';

  var app = ng.module('ngLoadScript', []);

  app.directive('script', function() {
    return {
      restrict: 'E',
      scope: false,
      link: function(scope, elem, attr) {
        if (attr.type === 'text/javascript-lazy') {
          var code = elem.text();
          var f = new Function(code);
          f();
        }
      }
    };
  });

}(angular));

Simply add this file, load ngLoadScript module as application dependency and use type="text/javascript-lazy" as type for script you which to load lazily in partials:

<script type="text/javascript-lazy">
  console.log("It works!");
</script>

Insert images to XML file

Here's some code taken from Kirk Evans Blog that demonstrates how to encode an image in C#;

//Load the picture from a file
Image picture = Image.FromFile(@"c:\temp\test.gif");

//Create an in-memory stream to hold the picture's bytes
System.IO.MemoryStream pictureAsStream = new System.IO.MemoryStream();
picture.Save(pictureAsStream, System.Drawing.Imaging.ImageFormat.Gif);

//Rewind the stream back to the beginning
pictureAsStream.Position = 0;
//Get the stream as an array of bytes
byte[] pictureAsBytes = pictureAsStream.ToArray();

//Create an XmlTextWriter to write the XML somewhere... here, I just chose
//to stream out to the Console output stream
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Console.Out);

//Write the root element of the XML document and the base64 encoded data
writer.WriteStartElement("w", "binData",
                         "http://schemas.microsoft.com/office/word/2003/wordml");

writer.WriteBase64(pictureAsBytes, 0, pictureAsBytes.Length);

writer.WriteEndElement();
writer.Flush();

php create object without class

you can always use new stdClass(). Example code:

   $object = new stdClass();
   $object->property = 'Here we go';

   var_dump($object);
   /*
   outputs:

   object(stdClass)#2 (1) {
      ["property"]=>
      string(10) "Here we go"
    }
   */

Also as of PHP 5.4 you can get same output with:

$object = (object) ['property' => 'Here we go'];

Location of ini/config files in linux/unix?

For user configuration I've noticed a tendency towards moving away from individual ~/.myprogramrc to a structure below ~/.config. For example, Qt 4 uses ~/.config/<vendor>/<programname> with the default settings of QSettings. The major desktop environments KDE and Gnome use a file structure below a specific folder too (not sure if KDE 4 uses ~/.config, XFCE does use ~/.config).

How to split a string in shell and get the last field

A solution using the read builtin:

IFS=':' read -a fields <<< "1:2:3:4:5"
echo "${fields[4]}"

Or, to make it more generic:

echo "${fields[-1]}" # prints the last item

Xcode iOS 8 Keyboard types not supported

This error had come when your keyboard input type is Number Pad.I got same error than I change my Textfield keyboard input type to Default fix my issue.

Python socket receive - incoming packets always have a different size

That's the nature of TCP: the protocol fills up packets (lower layer being IP packets) and sends them. You can have some degree of control over the MTU (Maximum Transfer Unit).

In other words: you must devise a protocol that rides on top of TCP where your "payload delineation" is defined. By "payload delineation" I mean the way you extract the unit of message your protocol supports. This can be as simple as "every NULL terminated strings".

Remove First and Last Character C++

std::string trimmed(std::string str ) {
if(str.length() == 0 ) { return "" ; }
else if ( str == std::string(" ") ) { return "" ; } 
else {
    while(str.at(0) == ' ') { str.erase(0, 1);}
    while(str.at(str.length()-1) == ' ') { str.pop_back() ; }
    return str ;
    } 
}

Using sessions & session variables in a PHP Login Script

I always do OOP and use this class to maintain the session so u can use the function is_logged_in to check if the user is logged in or not, and if not you do what you wish to.

<?php
class Session
{
private $logged_in=false;
public $user_id;

function __construct() {
    session_start();
    $this->check_login();
if($this->logged_in) {
  // actions to take right away if user is logged in
} else {
  // actions to take right away if user is not logged in
}
}

public function is_logged_in() {
   return $this->logged_in;
}

public function login($user) {
// database should find user based on username/password
if($user){
  $this->user_id = $_SESSION['user_id'] = $user->id;
  $this->logged_in = true;
  }
}

public function logout() {
unset($_SESSION['user_id']);
unset($this->user_id);
$this->logged_in = false;
}

private function check_login() {
if(isset($_SESSION['user_id'])) {
  $this->user_id = $_SESSION['user_id'];
  $this->logged_in = true;
} else {
  unset($this->user_id);
  $this->logged_in = false;
 }
}

}

$session = new Session();
?>

How to match a line not containing a word

This should work:

/^((?!PART).)*$/

If you only wanted to exclude it from the beginning of the line (I know you don't, but just FYI), you could use this:

/^(?!PART)/

Edit (by request): Why this pattern works

The (?!...) syntax is a negative lookahead, which I've always found tough to explain. Basically, it means "whatever follows this point must not match the regular expression /PART/." The site I've linked explains this far better than I can, but I'll try to break this down:

^         #Start matching from the beginning of the string.    
(?!PART)  #This position must not be followed by the string "PART".
.         #Matches any character except line breaks (it will include those in single-line mode).
$         #Match all the way until the end of the string.

The ((?!xxx).)* idiom is probably hardest to understand. As we saw, (?!PART) looks at the string ahead and says that whatever comes next can't match the subpattern /PART/. So what we're doing with ((?!xxx).)* is going through the string letter by letter and applying the rule to all of them. Each character can be anything, but if you take that character and the next few characters after it, you'd better not get the word PART.

The ^ and $ anchors are there to demand that the rule be applied to the entire string, from beginning to end. Without those anchors, any piece of the string that didn't begin with PART would be a match. Even PART itself would have matches in it, because (for example) the letter A isn't followed by the exact string PART.

Since we do have ^ and $, if PART were anywhere in the string, one of the characters would match (?=PART). and the overall match would fail. Hope that's clear enough to be helpful.

Android webview launches browser when calling loadurl

If you see an empty page, enable JavaScript.

webView.setWebViewClient(new WebViewClient());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webView.loadUrl(url);

document.body.appendChild(i)

You could try

document.getElementsByTagName('body')[0].appendChild(i);

Now that won't do you any good if the code is running in the <head>, and running before the <body> has even been seen by the browser. If you don't want to mess with "onload" handlers, try moving your <script> block to the very end of the document instead of the <head>.

iOS download and save image inside app

As other people said, there are many cases in which you should download a picture in the background thread without blocking the user interface

In this cases my favorite solution is to use a convenient method with blocks, like this one: (credit -> iOS: How To Download Images Asynchronously (And Make Your UITableView Scroll Fast))

- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               if ( !error )
                               {
                                   UIImage *image = [[UIImage alloc] initWithData:data];
                                   completionBlock(YES,image);
                               } else{
                                   completionBlock(NO,nil);
                               }
                           }];
}

And call it like

NSURL *imageUrl = //...

[[MyUtilManager sharedInstance] downloadImageWithURL:[NSURL URLWithString:imageURL] completionBlock:^(BOOL succeeded, UIImage *image) {
    //Here you can save the image permanently, update UI and do what you want...
}];

How can I create download link in HTML?

You can download in the various way you can follow my way. Though files may not download due to 'allow-popups' permission is not set but in your environment, this will work perfectly

_x000D_
_x000D_
<div className="col-6">_x000D_
                    <a  download href="https://www.w3schools.com/images/myw3schoolsimage.jpg" >Test Download </a>_x000D_
                </div>
_x000D_
_x000D_
_x000D_

another one this one will also fail due to 'X-Frame-Options' to 'sameorigin'.

_x000D_
_x000D_
<a href="https://www.w3schools.com/images/myw3schoolsimage.jpg" download>_x000D_
  <img src="https://www.w3schools.com/images/myw3schoolsimage.jpg" alt="W3Schools" width="104" height="142">_x000D_
</a>
_x000D_
_x000D_
_x000D_

Send data through routing paths in Angular

Latest version of angular (7.2 +) now has the option to pass additional information using NavigationExtras.

Home component

import {
  Router,
  NavigationExtras
} from '@angular/router';
const navigationExtras: NavigationExtras = {
  state: {
    transd: 'TRANS001',
    workQueue: false,
    services: 10,
    code: '003'
  }
};
this.router.navigate(['newComponent'], navigationExtras);

newComponent

test: string;
constructor(private router: Router) {
  const navigation = this.router.getCurrentNavigation();
  const state = navigation.extras.state as {
    transId: string,
    workQueue: boolean,
    services: number,
    code: string
  };
  this.test = "Transaction Key:" + state.transId + "<br /> Configured:" + state.workQueue + "<br /> Services:" + state.services + "<br /> Code: " + state.code;
}

Output

enter image description here

Hope this would help!

How to make a form close when pressing the escape key?

Button cancelBTN = new Button();
cancelBTN.Size = new Size(0, 0);
cancelBTN.TabStop = false;
this.Controls.Add(cancelBTN);
this.CancelButton = cancelBTN;

Where can I find the Tomcat 7 installation folder on Linux AMI in Elastic Beanstalk?

Following environment variables worked for me on Debian Wheezy 7 and Tomcat 7:

CATALINA_HOME=/usr/share/tomcat7
CATALINA_BASE=/var/lib/tomcat7
CATALINA_TMPDIR=/tmp/tomcat7

(I did create /tmp/tomcat7 manually)

dynamically add and remove view to viewpager

I was looking for simple solution to remove views from viewpager (no fragments) dynamically. So, if you have some info, that your pages belongs to, you can set it to View as tag. Just like that (adapter code):

@Override
public Object instantiateItem(ViewGroup collection, int position)
{
    ImageView iv = new ImageView(mContext);
    MediaMessage msg = mMessages.get(position);
    ...

    iv.setTag(media);
    return iv;
}

@Override
public int getItemPosition (Object object)
{
    View o = (View) object;
    int index = mMessages.indexOf(o.getTag());
    if (index == -1)
        return POSITION_NONE;
    else
        return index;
}

You just need remove your info from mMessages, and then call notifyDataSetChanged() for your adapter. Bad news there is no animation in this case.

how to check if a form is valid programmatically using jQuery Validation Plugin

For Magento, you check validation of form by something like below.

You can try this:

require(["jquery"], function ($) {
    $(document).ready(function () {
        $('#my-button-name').click(function () { // The button type should be "button" and not submit
            if ($('#form-name').valid()) {
                alert("Validation pass");
                return false;
            }else{
                alert("Validation failed");
                return false;
            }
        });
    });
});

Hope this may help you!

Creating a file name as a timestamp in a batch job

This will ensure that the output is a 2-digit value...you can rearrange the output to your liking and test by un-commenting the diagnostics section. Enjoy!

(I borrowed a lot of this from other forums...)

:: ------------------ Date and Time Modifier ------------------------

@echo off
setlocal

:: THIS CODE WILL DISPLAY A 2-DIGIT TIMESTAMP FOR USE IN APPENDING FILENAMES

:: CREATE VARIABLE %TIMESTAMP%

for /f "tokens=1-8 delims=.:/-, " %%i in ('echo exit^|cmd /q /k"prompt $D $T"') do (
   for /f "tokens=2-4 skip=1 delims=/-,()" %%a in ('echo.^|date') do (
set dow=%%i
set %%a=%%j
set %%b=%%k
set %%c=%%l
set hh=%%m
set min=%%n
set sec=%%o
set hsec=%%p
)
)

:: ensure that hour is always 2 digits

if %hh%==0 set hh=00
if %hh%==1 set hh=01
if %hh%==2 set hh=02
if %hh%==3 set hh=03
if %hh%==4 set hh=04
if %hh%==5 set hh=05
if %hh%==6 set hh=06
if %hh%==7 set hh=07
if %hh%==8 set hh=08
if %hh%==9 set hh=09


:: --------- TIME STAMP DIAGNOSTICS -------------------------

:: Un-comment these lines to test output

:: echo dayOfWeek = %dow%
:: echo year = %yy%
:: echo month = %mm%
:: echo day = %dd%
:: echo hour = %hh%
:: echo minute = %min%
:: echo second = %sec%
:: echo hundredthsSecond = %hsec%
:: echo.
:: echo Hello! 
:: echo Today is %dow%, %mm%/%dd%. 
:: echo.
:: echo. 
:: echo.
:: echo.
:: pause

:: --------- END TIME STAMP DIAGNOSTICS ----------------------

:: assign timeStamp:
:: Add the date and time parameters as necessary - " yy-mm-dd-dow-min-sec-hsec "

endlocal & set timeStamp=%yy%%mm%%dd%_%hh%-%min%-%sec%
echo %timeStamp%

Validating input using java.util.Scanner

Overview of Scanner.hasNextXXX methods

java.util.Scanner has many hasNextXXX methods that can be used to validate input. Here's a brief overview of all of them:

Scanner is capable of more, enabled by the fact that it's regex-based. One important feature is useDelimiter(String pattern), which lets you define what pattern separates your tokens. There are also find and skip methods that ignores delimiters.

The following discussion will keep the regex as simple as possible, so the focus remains on Scanner.


Example 1: Validating positive ints

Here's a simple example of using hasNextInt() to validate positive int from the input.

Scanner sc = new Scanner(System.in);
int number;
do {
    System.out.println("Please enter a positive number!");
    while (!sc.hasNextInt()) {
        System.out.println("That's not a number!");
        sc.next(); // this is important!
    }
    number = sc.nextInt();
} while (number <= 0);
System.out.println("Thank you! Got " + number);

Here's an example session:

Please enter a positive number!
five
That's not a number!
-3
Please enter a positive number!
5
Thank you! Got 5

Note how much easier Scanner.hasNextInt() is to use compared to the more verbose try/catch Integer.parseInt/NumberFormatException combo. By contract, a Scanner guarantees that if it hasNextInt(), then nextInt() will peacefully give you that int, and will not throw any NumberFormatException/InputMismatchException/NoSuchElementException.

Related questions


Example 2: Multiple hasNextXXX on the same token

Note that the snippet above contains a sc.next() statement to advance the Scanner until it hasNextInt(). It's important to realize that none of the hasNextXXX methods advance the Scanner past any input! You will find that if you omit this line from the snippet, then it'd go into an infinite loop on an invalid input!

This has two consequences:

  • If you need to skip the "garbage" input that fails your hasNextXXX test, then you need to advance the Scanner one way or another (e.g. next(), nextLine(), skip, etc).
  • If one hasNextXXX test fails, you can still test if it perhaps hasNextYYY!

Here's an example of performing multiple hasNextXXX tests.

Scanner sc = new Scanner(System.in);
while (!sc.hasNext("exit")) {
    System.out.println(
        sc.hasNextInt() ? "(int) " + sc.nextInt() :
        sc.hasNextLong() ? "(long) " + sc.nextLong() :  
        sc.hasNextDouble() ? "(double) " + sc.nextDouble() :
        sc.hasNextBoolean() ? "(boolean) " + sc.nextBoolean() :
        "(String) " + sc.next()
    );
}

Here's an example session:

5
(int) 5
false
(boolean) false
blah
(String) blah
1.1
(double) 1.1
100000000000
(long) 100000000000
exit

Note that the order of the tests matters. If a Scanner hasNextInt(), then it also hasNextLong(), but it's not necessarily true the other way around. More often than not you'd want to do the more specific test before the more general test.


Example 3 : Validating vowels

Scanner has many advanced features supported by regular expressions. Here's an example of using it to validate vowels.

Scanner sc = new Scanner(System.in);
System.out.println("Please enter a vowel, lowercase!");
while (!sc.hasNext("[aeiou]")) {
    System.out.println("That's not a vowel!");
    sc.next();
}
String vowel = sc.next();
System.out.println("Thank you! Got " + vowel);

Here's an example session:

Please enter a vowel, lowercase!
5
That's not a vowel!
z
That's not a vowel!
e
Thank you! Got e

In regex, as a Java string literal, the pattern "[aeiou]" is what is called a "character class"; it matches any of the letters a, e, i, o, u. Note that it's trivial to make the above test case-insensitive: just provide such regex pattern to the Scanner.

API links

Related questions

References


Example 4: Using two Scanner at once

Sometimes you need to scan line-by-line, with multiple tokens on a line. The easiest way to accomplish this is to use two Scanner, where the second Scanner takes the nextLine() from the first Scanner as input. Here's an example:

Scanner sc = new Scanner(System.in);
System.out.println("Give me a bunch of numbers in a line (or 'exit')");
while (!sc.hasNext("exit")) {
    Scanner lineSc = new Scanner(sc.nextLine());
    int sum = 0;
    while (lineSc.hasNextInt()) {
        sum += lineSc.nextInt();
    }
    System.out.println("Sum is " + sum);
}

Here's an example session:

Give me a bunch of numbers in a line (or 'exit')
3 4 5
Sum is 12
10 100 a million dollar
Sum is 110
wait what?
Sum is 0
exit

In addition to Scanner(String) constructor, there's also Scanner(java.io.File) among others.


Summary

  • Scanner provides a rich set of features, such as hasNextXXX methods for validation.
  • Proper usage of hasNextXXX/nextXXX in combination means that a Scanner will NEVER throw an InputMismatchException/NoSuchElementException.
  • Always remember that hasNextXXX does not advance the Scanner past any input.
  • Don't be shy to create multiple Scanner if necessary. Two simple Scanner is often better than one overly complex Scanner.
  • Finally, even if you don't have any plans to use the advanced regex features, do keep in mind which methods are regex-based and which aren't. Any Scanner method that takes a String pattern argument is regex-based.
    • Tip: an easy way to turn any String into a literal pattern is to Pattern.quote it.

angular2 submit form by pressing enter without submit button

Most answers here suggest using something like:

<form [formGroup]="form" (ngSubmit)="yourMethod()" (keyup.enter)="yourMethod()">

</form>

This approach does not result in the form object being marked as submitted. You might not care for this, but if you're using something like @ngspot/ngx-errors (shameless self-promotion) for displaying validation errors, you gonna want to fix that. Here's how:

<form [formGroup]="form" (ngSubmit)="yourMethod()" (keyup.enter)="submitBtn.click()">
  <button #submitBtn>Submit</button>
</form>

Composer Update Laravel

The following works for me:

composer update --no-scripts

Tools: replace not replacing in Android manifest

I just experienced the same behavior of tools:replace=... as described by the OP.

It turned out that the root cause for tools:replace being ignored by the manifest merger is a bug described here. It basically means that if you have a library in your project that contains a manifest with an <application ...> node containing a tools:ignore=... attribute, it can happen that the tools:replace=... attribute in the manifest of your main module will be ignored.

The tricky point here is that it can happen, but does not have to. In my case I had two libraries, library A with the tools:ignore=... attribute, library B with the attributes to be replaced in the respective manifests and the tools:replace=... attribute in the manifest of the main module. If the manifest of B was merged into the main manifest before the manifest of A everything worked as expected. In opposite merge order the error appeared.

The order in which these merges happen seems to be somewhat random. In my case changing the order in the dependencies section of build.gradle had no effect but changing the name of the flavor did it.

So, the only reliable workaround seems to be to unpack the problem causing library, remove the tools:ignore=... tag (which should be no problem as it is a hint for lint only) and pack the library again.

And vote for the bug to be fixed, of cause.

iOS: set font size of UILabel Programmatically

Objective-C:

[label setFont: [label.font fontWithSize: sizeYouWant]];

Swift:

label.font = label.font.fontWithSize(sizeYouWant)

just changes font size of a UILabel.

How to get on scroll events?

You could use a @HostListener decorator. Works with Angular 4 and up.

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

@HostListener("window:scroll", []) onWindowScroll() {
    // do some stuff here when the window is scrolled
    const verticalOffset = window.pageYOffset 
          || document.documentElement.scrollTop 
          || document.body.scrollTop || 0;
}

Build android release apk on Phonegap 3.x CLI

i got this to work by copy pasting the signed app in the same dir as zipalign. It seems that aapt.exe could not find the source file even when given the path. i.e. this did not work zipalign -f -v 4 C:...\CordovaApp-release-unsigned.apk C:...\destination.apk it reached aapt.exeCordovaApp-release-unsigned.apk , froze and upon hitting return 'aapt.exeCordovaApp-release-unsigned.apk' is not recognized as an internal or external command, operable program or batch file. And this did zipalign -f -v 4 CordovaApp-release-unsigned.apk myappname.apk

How to get folder path from file path with CMD

In order to assign these to variables, be sure not to add spaces in front or after the equals sign:

set filepath=%~dp1
set filename=%~nx1

Then you should have no issues.

SQLite Query in Android to count rows

int nombr = 0;
Cursor cursor = sqlDatabase.rawQuery("SELECT column FROM table WHERE column = Value", null);
nombr = cursor.getCount();

What is the difference between private and protected members of C++ classes?

Private member can be accessed only in same class where it has declared where as protected member can be accessed in class where it is declared along with the classes which are inherited by it .

Making view resize to its parent when added with addSubview

Swift 4 extension using explicit constraints:

import UIKit.UIView

extension UIView {
    public func addSubview(_ subview: UIView, stretchToFit: Bool = false) {
        addSubview(subview)
        if stretchToFit {
            subview.translatesAutoresizingMaskIntoConstraints = false
            leftAnchor.constraint(equalTo: subview.leftAnchor).isActive = true
            rightAnchor.constraint(equalTo: subview.rightAnchor).isActive = true
            topAnchor.constraint(equalTo: subview.topAnchor).isActive = true
            bottomAnchor.constraint(equalTo: subview.bottomAnchor).isActive = true
        }
    }
}

Usage:

parentView.addSubview(childView) // won't resize (default behavior unchanged)
parentView.addSubview(childView, stretchToFit: false) // won't resize
parentView.addSubview(childView, stretchToFit: true) // will resize

How do I hide an element when printing a web page?

The best thing to do is to create a "print-only" version of the page.

Oh, wait... this isn't 1999 anymore. Use a print CSS with "display: none".

How do you turn a Mongoose document into a plain object?

The lean option tells Mongoose to skip hydrating the result documents. This makes queries faster and less memory intensive, but the result documents are plain old JavaScript objects (POJOs), not Mongoose documents.

const leanDoc = await MyModel.findOne().lean();

not necessary to use JSON.parse() method

How can I check if an InputStream is empty without reading from it?

You can use the available() method to ask the stream whether there is any data available at the moment you call it. However, that function isn't guaranteed to work on all types of input streams. That means that you can't use available() to determine whether a call to read() will actually block or not.

How to split a number into individual digits in c#?

I'd use modulus and a loop.

int[] GetIntArray(int num)
{
    List<int> listOfInts = new List<int>();
    while(num > 0)
    {
        listOfInts.Add(num % 10);
        num = num / 10;
    }
    listOfInts.Reverse();
    return listOfInts.ToArray();
}

Git Cherry-pick vs Merge Workflow

Rebase and Cherry-pick is the only way you can keep clean commit history. Avoid using merge and avoid creating merge conflict. If you are using gerrit set one project to Merge if necessary and one project to cherry-pick mode and try yourself.

How to Get XML Node from XDocument

The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:

XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
                    where xml2.Element("ID").Value == variable
                    select xml2).FirstOrDefault();

This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.

Marc

Cannot find "Package Explorer" view in Eclipse

The simplest, and best long-term solution

Go to the main menu on top of Eclipse and locate Window next to Run and expand it.

 Window->Reset Perspective... to restore all views to their defaults

It will reset the default setting.

How to count lines in a document?

I've been using this:

cat myfile.txt | wc -l

I prefer it over the accepted answer because it does not print the filename, and you don't have to use awk to fix that. Accepted answer:

wc -l myfile.txt

But I think the best one is GGB667's answer:

wc -l < myfile.txt

I will probably be using that from now on. It's slightly shorter than my way. I am putting up my old way of doing it in case anyone prefers it. The output is the same with those two methods.

Cannot set property 'innerHTML' of null

The JavaScript part needs to run once the page is loaded, therefore it is advised to place JavaScript script at the end of the body tag.

_x000D_
_x000D_
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Example</title>

</head>
<body>
<div id="hello"></div>
<script type ="text/javascript">
    what();
    function what(){
        document.getElementById('hello').innerHTML = 'hi';
    };
</script>  
</body>
</html>
_x000D_
_x000D_
_x000D_

Only numbers. Input number in React

Solution

Today I find use parseInt() is also a good and clean practice. A onChange(e) example is below.

Code

onChange(e){
    this.setState({[e.target.id]: parseInt(e.target.value) ? parseInt(e.target.value) : ''})
}

Explanation

  1. parseInt() would return NaN if the parameter is not a number.
  2. parseInt('12a') would return 12.

How to insert text into the textarea at the current cursor position?

Use selectionStart/selectionEnd properties of the input element (works for <textarea> as well)

function insertAtCursor(myField, myValue) {
    //IE support
    if (document.selection) {
        myField.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
    }
    //MOZILLA and others
    else if (myField.selectionStart || myField.selectionStart == '0') {
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos)
            + myValue
            + myField.value.substring(endPos, myField.value.length);
    } else {
        myField.value += myValue;
    }
}

invalid conversion from 'const char*' to 'char*'

First of all this code snippet

char *addr=NULL;
strcpy(addr,retstring().c_str());

is invalid because you did not allocate memory where you are going to copy retstring().c_str().

As for the error message then it is clear enough. The type of expression data.str().c_str() is const char * but the third parameter of the function is declared as char *. You may not assign an object of type const char * to an object of type char *. Either the function should define the third parameter as const char * if it does not change the object pointed by the third parameter or you may not pass argument of type const char *.

Which version of Python do I have installed?

When I open Python (command line) the first thing it tells me is the version.

Return None if Dictionary key is not available

If you can do it with False, then, there's also the hasattr built-in funtion:

e=dict()
hasattr(e, 'message'):
>>> False

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

I encountered the same problem with:

Spring Boot version = 1.5.10
Spring Security version = 4.2.4


The problem occurred on the endpoints, where the ModelAndView viewName was defined with a preceding forward slash. Example:

ModelAndView mav = new ModelAndView("/your-view-here");

If I removed the slash it worked fine. Example:

ModelAndView mav = new ModelAndView("your-view-here");

I also did some tests with RedirectView and it seemed to work with a preceding forward slash.

How to re import an updated package while in Python Interpreter?

In Python 3, the behaviour changes.

>>> import my_stuff

... do something with my_stuff, then later:

>>>> import imp
>>>> imp.reload(my_stuff)

and you get a brand new, reloaded my_stuff.

Swift - How to detect orientation changes

let const = "Background" //image name
let const2 = "GreyBackground" // image name
    @IBOutlet weak var imageView: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()

        imageView.image = UIImage(named: const)
        // Do any additional setup after loading the view.
    }

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        if UIDevice.current.orientation.isLandscape {
            print("Landscape")
            imageView.image = UIImage(named: const2)
        } else {
            print("Portrait")
            imageView.image = UIImage(named: const)
        }
    }

CodeIgniter removing index.php from url

Minor thing: (Optional)

Try restarting your Apache after updating the rewrite engine status in vhosts as Rewrite ON.

One critical thing to notice:

In Apache vhosts file, check whether you have this script line AllowOverride None If yes, please remove/comment this line.

My vhosts file script: (Before)

<VirtualHost *:80>
    DocumentRoot "/path/to/workspace"
    ServerName ciproject
    ErrorLog "/path/to/workspace/error.log"
    CustomLog "/path/to/workspace/access.log" common
    Directory   "/path/to/workspace">
        Options Indexes FollowSymLinks
        AllowOverride None
        Order allow,deny
        Allow from all
    </Directory> 
</VirtualHost>

My vhosts file script: (After)

<VirtualHost *:80>
    DocumentRoot "/path/to/workspace"
    ServerName ciproject
    ErrorLog "/path/to/workspace/error.log"
    CustomLog "/path/to/workspace/access.log" common
    Directory   "/path/to/workspace">
        Options Indexes FollowSymLinks
        #AllowOverride None
        Order allow,deny
        Allow from all
    </Directory> 
</VirtualHost>

I faced the same problem, struggled for around 1 day, all were fine. Later, by trial and error method, found this thing. After removing this, my job was accomplished. The URL now does not look up for index.php :)

Get generic type of class at runtime

Here is working solution!!!

@SuppressWarnings("unchecked")
    private Class<T> getGenericTypeClass() {
        try {
            String className = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0].getTypeName();
            Class<?> clazz = Class.forName(className);
            return (Class<T>) clazz;
        } catch (Exception e) {
            throw new IllegalStateException("Class is not parametrized with generic type!!! Please use extends <> ");
        }
    } 

NOTES: Can be used only as superclass
1. Has to be extended with typed class (Child extends Generic<Integer>)
OR

2. Has to be created as anonymous implementation (new Generic<Integer>() {};)

How should I escape strings in JSON?

org.json.JSONObject quote(String data) method does the job

import org.json.JSONObject;
String jsonEncodedString = JSONObject.quote(data);

Extract from the documentation:

Encodes data as a JSON string. This applies quotes and any necessary character escaping. [...] Null will be interpreted as an empty string

Android ImageView setImageResource in code

you may try this:-

myImgView.setImageDrawable(getResources().getDrawable(R.drawable.image_name));

Get a substring of a char*

You can use strstr. Example code here.

Note that the returned result is not null terminated.

How to clear the Entry widget after a button is pressed in Tkinter?

real gets the value ent.get() which is just a string. It has no idea where it came from, and no way to affect the widget.

Instead of real.delete(), call .delete() on the entry widget itself:

def res(ent, real, secret):
    if secret == eval(real):
        showinfo(message='that is right!')
    ent.delete(0, END)

def guess():
    ...
    btn = Button(ge, text="Enter", command=lambda: res(ent, ent.get(), secret))

Google Maps Android API v2 Authorization failure

I had the same issue. After about two hours of googling, retries, regenerating API Key many times, etc. i discovered that i enabled the wrong service in the Google APis Console. I enabled Google Maps API v2 Service, but for Android Apps you have to use Google Maps Android API v2. After enabling the right service all started working.

How to limit the maximum value of a numeric field in a Django model?

You can use Django's built-in validators

from django.db.models import IntegerField, Model
from django.core.validators import MaxValueValidator, MinValueValidator

class CoolModelBro(Model):
    limited_integer_field = IntegerField(
        default=1,
        validators=[
            MaxValueValidator(100),
            MinValueValidator(1)
        ]
     )

Edit: When working directly with the model, make sure to call the model full_clean method before saving the model in order to trigger the validators. This is not required when using ModelForm since the forms will do that automatically.

Create a Bitmap/Drawable from file path

Create bitmap from file path:

File sd = Environment.getExternalStorageDirectory();
File image = new File(sd+filePath, imageName);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);
imageView.setImageBitmap(bitmap);

If you want to scale the bitmap to the parent's height and width then use Bitmap.createScaledBitmap function.

I think you are giving the wrong file path. :) Hope this helps.

Differences between cookies and sessions?

Sessions are server-side files that contain user information, while Cookies are client-side files that contain user information. Sessions have a unique identifier that maps them to specific users. This identifier can be passed in the URL or saved into a session cookie.

Most modern sites use the second approach, saving the identifier in a Cookie instead of passing it in a URL (which poses a security risk). You are probably using this approach without knowing it, and by deleting the cookies you effectively erase their matching sessions as you remove the unique session identifier contained in the cookies.

How to lazy load images in ListView in Android

Update: Note that this answer is pretty ineffective now. The Garbage Collector acts aggressively on SoftReference and WeakReference, so this code is NOT suitable for new apps. (Instead, try libraries like Universal Image Loader suggested in other answers.)

Thanks to James for the code, and Bao-Long for the suggestion of using SoftReference. I implemented the SoftReference changes on James' code. Unfortunately SoftReferences caused my images to be garbage collected too quickly. In my case it was fine without the SoftReference stuff, because my list size is limited and my images are small.

There's a discussion from a year ago regarding the SoftReferences on google groups: link to thread. As a solution to the too-early garbage collection, they suggest the possibility of manually setting the VM heap size using dalvik.system.VMRuntime.setMinimumHeapSize(), which is not very attractive to me.

public DrawableManager() {
    drawableMap = new HashMap<String, SoftReference<Drawable>>();
}

public Drawable fetchDrawable(String urlString) {
    SoftReference<Drawable> drawableRef = drawableMap.get(urlString);
    if (drawableRef != null) {
        Drawable drawable = drawableRef.get();
        if (drawable != null)
            return drawable;
        // Reference has expired so remove the key from drawableMap
        drawableMap.remove(urlString);
    }

    if (Constants.LOGGING) Log.d(this.getClass().getSimpleName(), "image url:" + urlString);
    try {
        InputStream is = fetch(urlString);
        Drawable drawable = Drawable.createFromStream(is, "src");
        drawableRef = new SoftReference<Drawable>(drawable);
        drawableMap.put(urlString, drawableRef);
        if (Constants.LOGGING) Log.d(this.getClass().getSimpleName(), "got a thumbnail drawable: " + drawable.getBounds() + ", "
                + drawable.getIntrinsicHeight() + "," + drawable.getIntrinsicWidth() + ", "
                + drawable.getMinimumHeight() + "," + drawable.getMinimumWidth());
        return drawableRef.get();
    } catch (MalformedURLException e) {
        if (Constants.LOGGING) Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
        return null;
    } catch (IOException e) {
        if (Constants.LOGGING) Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
        return null;
    }
}

public void fetchDrawableOnThread(final String urlString, final ImageView imageView) {
    SoftReference<Drawable> drawableRef = drawableMap.get(urlString);
    if (drawableRef != null) {
        Drawable drawable = drawableRef.get();
        if (drawable != null) {
            imageView.setImageDrawable(drawableRef.get());
            return;
        }
        // Reference has expired so remove the key from drawableMap
        drawableMap.remove(urlString);
    }

    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message message) {
            imageView.setImageDrawable((Drawable) message.obj);
        }
    };

    Thread thread = new Thread() {
        @Override
        public void run() {
            //TODO : set imageView to a "pending" image
            Drawable drawable = fetchDrawable(urlString);
            Message message = handler.obtainMessage(1, drawable);
            handler.sendMessage(message);
        }
    };
    thread.start();
}

close fancy box from function from within open 'fancybox'

For those who spent hours like me to find out the solution for inline type: window.setTimeout(function(){$.fancybox.close()},10);

Can't open and lock privilege tables: Table 'mysql.user' doesn't exist

You have to initialize the data directory by running the following command

mysqld --initialize [with random root password]

mysqld --initialize-insecure [with blank root password]

How to execute raw queries with Laravel 5.1?

you can run raw query like this way too.

DB::table('setting_colleges')->first();

How does one convert a HashMap to a List in Java?

Collection Interface has 3 views

  • keySet
  • values
  • entrySet

Other have answered to to convert Hashmap into two lists of key and value. Its perfectly correct

My addition: How to convert "key-value pair" (aka entrySet)into list.

      Map m=new HashMap();
          m.put(3, "dev2");
          m.put(4, "dev3");

      List<Entry> entryList = new ArrayList<Entry>(m.entrySet());

      for (Entry s : entryList) {
        System.out.println(s);
      }

ArrayList has this constructor.

Sequelize OR condition object

See the docs about querying.

It would be:

$or: [{a: 5}, {a: 6}]  // (a = 5 OR a = 6)

Can't use SURF, SIFT in OpenCV

Just change the version of opencv to 3.4.2.16 .Since it is patented it is not available in newer version.

python numpy vector math

You can just use numpy arrays. Look at the numpy for matlab users page for a detailed overview of the pros and cons of arrays w.r.t. matrices.

As I mentioned in the comment, having to use the dot() function or method for mutiplication of vectors is the biggest pitfall. But then again, numpy arrays are consistent. All operations are element-wise. So adding or subtracting arrays and multiplication with a scalar all work as expected of vectors.

Edit2: Starting with Python 3.5 and numpy 1.10 you can use the @ infix-operator for matrix multiplication, thanks to pep 465.

Edit: Regarding your comment:

  1. Yes. The whole of numpy is based on arrays.

  2. Yes. linalg.norm(v) is a good way to get the length of a vector. But what you get depends on the possible second argument to norm! Read the docs.

  3. To normalize a vector, just divide it by the length you calculated in (2). Division of arrays by a scalar is also element-wise.

    An example in ipython:

    In [1]: import math
    
    In [2]: import numpy as np
    
    In [3]: a = np.array([4,2,7])
    
    In [4]: np.linalg.norm(a)
    Out[4]: 8.3066238629180749
    
    In [5]: math.sqrt(sum([n**2 for n in a]))
    Out[5]: 8.306623862918075
    
    In [6]: b = a/np.linalg.norm(a)
    
    In [7]: np.linalg.norm(b)
    Out[7]: 1.0
    

    Note that In [5] is an alternative way to calculate the length. In [6] shows normalizing the vector.

/exclude in xcopy just for a file type

For excluding multiple file types, you can use '+' to concatenate other lists. For example:

xcopy /r /d /i /s /y /exclude:excludedfileslist1.txt+excludedfileslist2.txt C:\dev\apan C:\web\apan

Source: http://www.tech-recipes.com/rx/2682/xcopy_command_using_the_exclude_flag/

How to run a hello.js file in Node.js on windows?

type node js command prompt in start screen. and use it. OR set PATH of node in environment variable.

Why does git say "Pull is not possible because you have unmerged files"?

When a merge conflict occurs , you can open individual file. You will get "<<<<<<< or >>>>>>>" symbols. These refer to your changes and the changes present on remote. You can manually edit the part that is requires. after that save the file and then do : git add

The merge conflicts will be resolved.

What is the difference between AF_INET and PF_INET in socket programming?

  • AF = Address Family
  • PF = Protocol Family

Meaning, AF_INET refers to addresses from the internet, IP addresses specifically. PF_INET refers to anything in the protocol, usually sockets/ports.

Consider reading the man pages for socket(2) and bind(2). For the sin_addr field, just do something like the following to set it:

struct sockaddr_in addr;
inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr); 

Can someone explain how to implement the jQuery File Upload plugin?

For the UI plugin, with jsp page and Spring MVC..

Sample html. Needs to be within a form element with an id attribute of fileupload

    <!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
<div class="fileupload-buttonbar">
    <div>
        <!-- The fileinput-button span is used to style the file input field as button -->
        <span class="btn btn-success fileinput-button">
            <i class="glyphicon glyphicon-plus"></i>
            <span>Add files</span>
            <input id="fileuploadInput" type="file" name="files[]" multiple>
        </span>
        <%-- https://stackoverflow.com/questions/925334/how-is-the-default-submit-button-on-an-html-form-determined --%>
        <button type="button" class="btn btn-primary start">
            <i class="glyphicon glyphicon-upload"></i>
            <span>Start upload</span>
        </button>
        <button type="reset" class="btn btn-warning cancel">
            <i class="glyphicon glyphicon-ban-circle"></i>
            <span>Cancel upload</span>
        </button>
        <!-- The global file processing state -->
        <span class="fileupload-process"></span>
    </div>
    <!-- The global progress state -->
    <div class="fileupload-progress fade">
        <!-- The global progress bar -->
        <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
            <div class="progress-bar progress-bar-success" style="width:0%;"></div>
        </div>
        <!-- The extended global progress state -->
        <div class="progress-extended">&nbsp;</div>
    </div>
</div>
<!-- The table listing the files available for upload/download -->
<table role="presentation" class="table table-striped"><tbody class="files"></tbody></table>

<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/css/jquery.fileupload.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/css/jquery.fileupload-ui.css">

<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/vendor/jquery.ui.widget.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/jquery.iframe-transport.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/jquery.fileupload.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/jquery.fileupload-process.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/jquery.fileupload-validate.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/jquery.fileupload-ui.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
            var maxFileSizeBytes = ${maxFileSizeBytes};
        if (maxFileSizeBytes < 0) {
            //-1 or any negative value means no size limit
            //set to undefined
            //https://stackoverflow.com/questions/5795936/how-to-set-a-javascript-var-as-undefined
            maxFileSizeBytes = void 0;
        }

        //https://github.com/blueimp/jQuery-File-Upload/wiki/Options
        //https://stackoverflow.com/questions/34063348/jquery-file-upload-basic-plus-ui-and-i18n
        //https://stackoverflow.com/questions/11337897/how-to-customize-upload-download-template-of-blueimp-jquery-file-upload
        $('#fileupload').fileupload({
            url: '${pageContext.request.contextPath}/app/uploadResources.do',
            fileInput: $('#fileuploadInput'),
            acceptFileTypes: /(\.|\/)(jrxml|png|jpe?g)$/i,
            maxFileSize: maxFileSizeBytes,
            messages: {
                acceptFileTypes: '${fileTypeNotAllowedText}',
                maxFileSize: '${fileTooLargeMBText}'
            },
            filesContainer: $('.files'),
            uploadTemplateId: null,
            downloadTemplateId: null,
            uploadTemplate: function (o) {
                var rows = $();
                $.each(o.files, function (index, file) {
                    var row = $('<tr class="template-upload fade">' +
                            '<td><p class="name"></p>' +
                            '<strong class="error text-danger"></strong>' +
                            '</td>' +
                            '<td><p class="size"></p>' +
                            '<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">' +
                            '<div class="progress-bar progress-bar-success" style="width:0%;"></div></div>' +
                            '</td>' +
                            '<td>' +
                            (!index && !o.options.autoUpload ?
                                    '<button class="btn btn-primary start" disabled>' +
                                    '<i class="glyphicon glyphicon-upload"></i> ' +
                                    '<span>${startText}</span>' +
                                    '</button>' : '') +
                            (!index ? '<button class="btn btn-warning cancel">' +
                                    '<i class="glyphicon glyphicon-ban-circle"></i> ' +
                                    '<span>${cancelText}</span>' +
                                    '</button>' : '') +
                            '</td>' +
                            '</tr>');
                    row.find('.name').text(file.name);
                    row.find('.size').text(o.formatFileSize(file.size));
                    if (file.error) {
                        row.find('.error').text(file.error);
                    }
                    rows = rows.add(row);
                });
                return rows;
            },
            downloadTemplate: function (o) {
                var rows = $();
                $.each(o.files, function (index, file) {
                    var row = $('<tr class="template-download fade">' +
                            '<td><p class="name"></p>' +
                            (file.error ? '<strong class="error text-danger"></strong>' : '') +
                            '</td>' +
                            '<td><span class="size"></span></td>' +
                            '<td>' +
                            (file.deleteUrl ? '<button class="btn btn-danger delete">' +
                                    '<i class="glyphicon glyphicon-trash"></i> ' +
                                    '<span>${deleteText}</span>' +
                                    '</button>' : '') +
                            '<button class="btn btn-warning cancel">' +
                            '<i class="glyphicon glyphicon-ban-circle"></i> ' +
                            '<span>${clearText}</span>' +
                            '</button>' +
                            '</td>' +
                            '</tr>');
                    row.find('.name').text(file.name);
                    row.find('.size').text(o.formatFileSize(file.size));
                    if (file.error) {
                        row.find('.error').text(file.error);
                    }
                    if (file.deleteUrl) {
                        row.find('button.delete')
                                .attr('data-type', file.deleteType)
                                .attr('data-url', file.deleteUrl);
                    }
                    rows = rows.add(row);
                });
                return rows;
            }
        });

    });
</script>

Sample upload and delete request handlers

    @PostMapping("/app/uploadResources")
public @ResponseBody
Map<String, List<FileUploadResponse>> uploadResources(MultipartHttpServletRequest request,
        Locale locale) {
    //https://github.com/jdmr/fileUpload/blob/master/src/main/java/org/davidmendoza/fileUpload/web/ImageController.java
    //https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#using-jquery-file-upload-ui-version-with-a-custom-server-side-upload-handler
    Map<String, List<FileUploadResponse>> response = new HashMap<>();
    List<FileUploadResponse> fileList = new ArrayList<>();

    String deleteUrlBase = request.getContextPath() + "/app/deleteResources.do?filename=";

    //http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/multipart/MultipartRequest.html
    Iterator<String> itr = request.getFileNames();
    while (itr.hasNext()) {
        String htmlParamName = itr.next();
        MultipartFile file = request.getFile(htmlParamName);
        FileUploadResponse fileDetails = new FileUploadResponse();
        String filename = file.getOriginalFilename();
        fileDetails.setName(filename);
        fileDetails.setSize(file.getSize());
        try {
            String message = saveFile(file);
            if (message != null) {
                String errorMessage = messageSource.getMessage(message, null, locale);
                fileDetails.setError(errorMessage);
            } else {
                //save successful
                String encodedFilename = URLEncoder.encode(filename, "UTF-8");
                String deleteUrl = deleteUrlBase + encodedFilename;
                fileDetails.setDeleteUrl(deleteUrl);
            }
        } catch (IOException ex) {
            logger.error("Error", ex);
            fileDetails.setError(ex.getMessage());
        }

        fileList.add(fileDetails);
    }

    response.put("files", fileList);

    return response;
}

@PostMapping("/app/deleteResources")
public @ResponseBody
Map<String, List<Map<String, Boolean>>> deleteResources(@RequestParam("filename") List<String> filenames) {
    Map<String, List<Map<String, Boolean>>> response = new HashMap<>();
    List<Map<String, Boolean>> fileList = new ArrayList<>();

    String templatesPath = Config.getTemplatesPath();
    for (String filename : filenames) {
        Map<String, Boolean> fileDetails = new HashMap<>();

        String cleanFilename = ArtUtils.cleanFileName(filename);
        String filePath = templatesPath + cleanFilename;

        File file = new File(filePath);
        boolean deleted = file.delete();

        if (deleted) {
            fileDetails.put(cleanFilename, true);
        } else {
            fileDetails.put(cleanFilename, false);
        }

        fileList.add(fileDetails);
    }

    response.put("files", fileList);

    return response;
}

Sample class for generating the required json response

    public class FileUploadResponse {
    //https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#using-jquery-file-upload-ui-version-with-a-custom-server-side-upload-handler

    private String name;
    private long size;
    private String error;
    private String deleteType = "POST";
    private String deleteUrl;

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the size
     */
    public long getSize() {
        return size;
    }

    /**
     * @param size the size to set
     */
    public void setSize(long size) {
        this.size = size;
    }

    /**
     * @return the error
     */
    public String getError() {
        return error;
    }

    /**
     * @param error the error to set
     */
    public void setError(String error) {
        this.error = error;
    }

    /**
     * @return the deleteType
     */
    public String getDeleteType() {
        return deleteType;
    }

    /**
     * @param deleteType the deleteType to set
     */
    public void setDeleteType(String deleteType) {
        this.deleteType = deleteType;
    }

    /**
     * @return the deleteUrl
     */
    public String getDeleteUrl() {
        return deleteUrl;
    }

    /**
     * @param deleteUrl the deleteUrl to set
     */
    public void setDeleteUrl(String deleteUrl) {
        this.deleteUrl = deleteUrl;
    }

}

See https://pitipata.blogspot.co.ke/2017/01/using-jquery-file-upload-ui.html

Is it possible to save HTML page as PDF using JavaScript or jquery?

Ya its very easy to do with javascript. Hope this code is useful to you.

You'll need the JSpdf library.

<div id="content">
     <h3>Hello, this is a H3 tag</h3>

    <p>a pararaph</p>
</div>
<div id="editor"></div>
<button id="cmd">Generate PDF</button>

<script>
    var doc = new jsPDF();
    var specialElementHandlers = {
        '#editor': function (element, renderer) {
            return true;
        }
    };

    $('#cmd').click(function () {
        doc.fromHTML($('#content').html(), 15, 15, {
            'width': 170,
                'elementHandlers': specialElementHandlers
        });
        doc.save('sample-file.pdf');
    });

    // This code is collected but useful, click below to jsfiddle link.
</script>

jsfiddle link here

Extract value of attribute node via XPath

//Parent/Children[@  Attribute='value']/@Attribute

This is the case which can be used where element is having 2 attribute and we can get the one attribute with the help of another one.

How to list all files in a directory and its subdirectories in hadoop hdfs

Have you tried this:

import java.io.*;
import java.util.*;
import java.net.*;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.*;

public class cat{
    public static void main (String [] args) throws Exception{
        try{
            FileSystem fs = FileSystem.get(new Configuration());
            FileStatus[] status = fs.listStatus(new Path("hdfs://test.com:9000/user/test/in"));  // you need to pass in your hdfs path

            for (int i=0;i<status.length;i++){
                BufferedReader br=new BufferedReader(new InputStreamReader(fs.open(status[i].getPath())));
                String line;
                line=br.readLine();
                while (line != null){
                    System.out.println(line);
                    line=br.readLine();
                }
            }
        }catch(Exception e){
            System.out.println("File not found");
        }
    }
}

jQuery UI Sortable Position

Use update instead of stop

http://api.jqueryui.com/sortable/

update( event, ui )

Type: sortupdate

This event is triggered when the user stopped sorting and the DOM position has changed.

.

stop( event, ui )

Type: sortstop

This event is triggered when sorting has stopped. event Type: Event

Piece of code:

http://jsfiddle.net/7a1836ce/

<script type="text/javascript">

var sortable    = new Object();
sortable.s1     = new Array(1, 2, 3, 4, 5);
sortable.s2     = new Array(1, 2, 3, 4, 5);
sortable.s3     = new Array(1, 2, 3, 4, 5);
sortable.s4     = new Array(1, 2, 3, 4, 5);
sortable.s5     = new Array(1, 2, 3, 4, 5);

sortingExample();

function sortingExample()
{
    // Init vars

    var tDiv    = $('<div></div>');
    var tSel    = '';

    // ul
    for (var tName in sortable)
    {

        // Creating ul list
        tDiv.append(createUl(sortable[tName], tName));
        // Add selector id
        tSel += '#' + tName + ',';

    }

    $('body').append('<div id="divArrayInfo"></div>');
    $('body').append(tDiv);

    // ul sortable params

    $(tSel).sortable({connectWith:tSel,
       start: function(event, ui) 
       {
            ui.item.startPos = ui.item.index();
       },
        update: function(event, ui)
        {
            var a   = ui.item.startPos;
            var b   = ui.item.index();
            var id = this.id;

            // If element moved to another Ul then 'update' will be called twice
            // 1st from sender list
            // 2nd from receiver list
            // Skip call from sender. Just check is element removed or not

            if($('#' + id + ' li').length < sortable[id].length)
            {
                return;
            }

            if(ui.sender === null)
            {
                sortArray(a, b, this.id, this.id);
            }
            else
            {
                sortArray(a, b, $(ui.sender).attr('id'), this.id);
            }

            printArrayInfo();

        }
    }).disableSelection();;

// Add styles

    $('<style>')
    .attr('type', 'text/css')
    .html(' body {background:black; color:white; padding:50px;} .sortableClass { clear:both; display: block; overflow: hidden; list-style-type: none; } .sortableClass li { border: 1px solid grey; float:left; clear:none; padding:20px; }')
    .appendTo('head');


    printArrayInfo();

}

function printArrayInfo()
{

    var tStr = '';

    for ( tName in sortable)
    {

        tStr += tName + ': ';

        for(var i=0; i < sortable[tName].length; i++)
        {

            // console.log(sortable[tName][i]);
            tStr += sortable[tName][i] + ', ';

        }

        tStr += '<br>';

    }

    $('#divArrayInfo').html(tStr);

}


function createUl(tArray, tId)
{

    var tUl = $('<ul>', {id:tId, class:'sortableClass'})

    for(var i=0; i < tArray.length; i++)
    {

        // Create Li element
        var tLi = $('<li>' + tArray[i] + '</li>');
        tUl.append(tLi);

    }

    return tUl;
}

function sortArray(a, b, idA, idB)
{
    var c;

    c = sortable[idA].splice(a, 1);
    sortable[idB].splice(b, 0, c);      

}
</script>

How to write html code inside <?php ?>, I want write html code within the PHP script so that it can be echoed from Backend

Try it like,

<?php 
    $name='your name';
    echo '<table>
       <tr><th>Name</th></tr>
       <tr><td>'.$name.'</td></tr>
    </table>';
?>

Updated

<?php 
    echo '<table>
       <tr><th>Rst</th><th>Marks</th></tr>
       <tr><td>'.$rst4.'</td><td>'.$marks4.'</td></tr>
    </table>';
?>

VarBinary vs Image SQL Server Data Type to Store Binary Data?

varbinary(max) is the way to go (introduced in SQL Server 2005)

WPF Application that only has a tray icon

I recently had this same problem. Unfortunately, NotifyIcon is only a Windows.Forms control at the moment, if you want to use it you are going to have to include that part of the framework. I guess that depends how much of a WPF purist you are.

If you want a quick and easy way of getting started check out this WPF NotifyIcon control on the Code Project which does not rely on the WinForms NotifyIcon at all. A more recent version seems to be available on the author's website and as a NuGet package. This seems like the best and cleanest way to me so far.

  • Rich ToolTips rather than text
  • WPF context menus and popups
  • Command support and routed events
  • Flexible data binding
  • Rich balloon messages rather than the default messages provides by the OS

Check it out. It comes with an amazing sample app too, very easy to use, and you can have great looking Windows Live Messenger style WPF popups, tooltips, and context menus. Perfect for displaying an RSS feed, I am using it for a similar purpose.

Fastest Convert from Collection to List<T>

Since 3.5, anything inherited from System.Collection.IEnumerable has the convenient extension method OfType available.

If your collection is from ICollection or IEnumerable, you can just do this:

List<ManagementObject> managementList = ManagementObjectCollection.OfType<ManagementObject>().ToList();

Can't find any way simpler. : )

Could not load file or assembly ... The parameter is incorrect

Clear out the temporary framework files for your project in:-

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\

What does the servlet <load-on-startup> value signify

Servlet Life Cycle

The lifecycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps.

  1. If an instance of the servlet does not exist, the web container:

    a. Loads the servlet class

    b. Creates an instance of the servlet class

    c. Initializes the servlet instance by calling the init method (initialization is covered in Creating and Initializing a Servlet)

  2. The container invokes the service method, passing request and response objects. Service methods are discussed in Writing Service Methods.

A 0 value on load-on-startup means that point 1 is executed when a request comes to that servlet. Other values means that point 1 is executed at container startup.

"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?

In my case, none of the other suggestions worked, however recloning my repository made this issue disappear.

Build Step Progress Bar (css and jquery)

I had the same requirements to create a kind of step progress tracker so I created a JavaScript plugin for that purpose. Here is the JsFiddle for the demo for this step progress tracker. You can access its code on GitHub as well.

What it basically does is, it takes the json data(in a particular format described below) as input and creates the progress tracker based on that. Highlighted steps indicates the completed steps.

It's html will somewhat look like shown below with default CSS but you can customize it as per the theme of your application. There is an option to show tool-tip text for each steps as well.

Here is some code snippet for that:

//container div 
<div id="tracker1" style="width: 700px">
</div>

//sample JSON data
var sampleJson1 = {
ToolTipPosition: "bottom",
data: [{ order: 1, Text: "Foo", ToolTipText: "Step1-Foo", highlighted: true },
    { order: 2, Text: "Bar", ToolTipText: "Step2-Bar", highlighted: true },
    { order: 3, Text: "Baz", ToolTipText: "Step3-Baz", highlighted: false },
    { order: 4, Text: "Quux", ToolTipText: "Step4-Quux", highlighted: false }]
};    

//Invoking the plugin
$(document).ready(function () {
        $("#tracker1").progressTracker(sampleJson1);
    });

Hopefully it will be useful for somebody else as well!

enter image description here

Linux command to translate DomainName to IP

You can use:

nslookup www.example.com

How do I make an input field accept only letters in javaScript?

If you want only letters - so from a to z, lower case or upper case, excluding everything else (numbers, blank spaces, symbols), you can modify your function like this:

function validate() {
    if (document.myForm.name.value == "") {
        alert("Enter a name");
        document.myForm.name.focus();
        return false;
    }
    if (!/^[a-zA-Z]*$/g.test(document.myForm.name.value)) {
        alert("Invalid characters");
        document.myForm.name.focus();
        return false;
    }
}

How to get the current directory in a C program?

Use getcwd

#include <stdio.h>  /* defines FILENAME_MAX */
//#define WINDOWS  /* uncomment this line to use it for windows.*/
#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif

int main(){
  char buff[FILENAME_MAX];
  GetCurrentDir( buff, FILENAME_MAX );
  printf("Current working dir: %s\n", buff);
  return 1;
}

OR

#include<stdio.h>
#include<unistd.h> 
#include<stdlib.h>

main() {
char *buf;
buf=(char *)malloc(100*sizeof(char));
getcwd(buf,100);
printf("\n %s \n",buf);
}

VHDL - How should I create a clock in a testbench?

Concurrent signal assignment:

library ieee;
use ieee.std_logic_1164.all;

entity foo is
end;
architecture behave of foo is
    signal clk: std_logic := '0';
begin
CLOCK:
clk <=  '1' after 0.5 ns when clk = '0' else
        '0' after 0.5 ns when clk = '1';
end;

ghdl -a foo.vhdl
ghdl -r foo --stop-time=10ns --wave=foo.ghw
ghdl:info: simulation stopped by --stop-time
gtkwave foo.ghw

enter image description here

Simulators simulate processes and it would be transformed into the equivalent process to your process statement. Simulation time implies the use of wait for or after when driving events for sensitivity clauses or sensitivity lists.

How to query GROUP BY Month in a Year

You can use:

    select FK_Items,Sum(PoiQuantity) Quantity  from PurchaseOrderItems POI
    left join PurchaseOrder PO ON po.ID_PurchaseOrder=poi.FK_PurchaseOrder
    group by FK_Items,DATEPART(MONTH, TransDate)

How can I generate an MD5 hash?

Here is how I use it:

final MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.reset();
messageDigest.update(string.getBytes(Charset.forName("UTF8")));
final byte[] resultByte = messageDigest.digest();
final String result = new String(Hex.encodeHex(resultByte));

where Hex is: org.apache.commons.codec.binary.Hex from the Apache Commons project.

Convert datatable to JSON in C#

Convert datatable to JSON using C#.net

 public static object DataTableToJSON(DataTable table)
    {
        var list = new List<Dictionary<string, object>>();

        foreach (DataRow row in table.Rows)
        {
            var dict = new Dictionary<string, object>();

            foreach (DataColumn col in table.Columns)
            {
                dict[col.ColumnName] = (Convert.ToString(row[col]));
            }
            list.Add(dict);
        }
        JavaScriptSerializer serializer = new JavaScriptSerializer();

        return serializer.Serialize(list);
    }

Detecting iOS / Android Operating system

Solution 1: User Agent Sniffing

For Android and iPhone:

if( /Android|webOS|iPhone|iPad|iPod|Opera Mini/i.test(navigator.userAgent) ) {
 // run your code here
}

If you wanna detect all mobile devices including blackberry and Windows phone then you can use this comprehensive version:

var deviceIsMobile = false; //At the beginning we set this flag as false. If we can detect the device is a mobile device in the next line, then we set it as true.


if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent) 
    || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0,4))) {
   deviceIsMobile = true;
}

if(deviceIsMobile){
    // run your code here
}

Cons: User agent strings are changing and getting updated as new phones and brands are coming day by day. So you need to keep this list updated if you wanna support all mobile devices.

Solution 2: mobile detect JS library

You can use the mobile detect JS library to do this.

Cons: These JavaScript-based device detection features may ONLY work for the newest generation of smartphones, such as the iPhone, Android and Palm WebOS devices. These device detection features may NOT work for older smartphones which had poor support for JavaScript, including older BlackBerry, PalmOS, and Windows Mobile devices.

Fastest way to determine if record exists

For MySql you can use LIMIT like below (Example shows in PHP)

  $sql = "SELECT column_name FROM table_name WHERE column_name = 'your_value' LIMIT 1";
  $result = $conn->query($sql);
  if ($result -> num_rows > 0) {
      echo "Value exists" ;
  } else {
      echo "Value not found";
  }

git pull while not in a git directory

For anyone like me that was trying to do this via a drush (Drupal shell) command on a remote server, you will not be able to use the solution that requires you to CD into the working directory:

Instead you need to use the solution that breaks up the pull into a fetch & merge:

drush @remote exec git --git-dir=/REPO/PATH --work-tree=/REPO/WORKDIR-PATH fetch origin
drush @remote exec git --git-dir=/REPO/PATH --work-tree=/REPO/WORKDIR-PATH merge origin/branch

How to detect query which holds the lock in Postgres?

One thing I find that is often missing from these is an ability to look up row locks. At least on the larger databases I have worked on, row locks are not shown in pg_locks (if they were, pg_locks would be much, much larger and there isn't a real data type to show the locked row in that view properly).

I don't know that there is a simple solution to this but usually what I do is look at the table where the lock is waiting and search for rows where the xmax is less than the transaction id present there. That usually gives me a place to start, but it is a bit hands-on and not automation friendly.

Note that shows you uncommitted writes on rows on those tables. Once committed, the rows are not visible in the current snapshot. But for large tables, that is a pain.

How can I find all the subsets of a set, with exactly n elements?

Here's some pseudocode - you can cut same recursive calls by storing the values for each call as you go and before recursive call checking if the call value is already present.

The following algorithm will have all the subsets excluding the empty set.

list * subsets(string s, list * v) {

    if(s.length() == 1) {
        list.add(s);    
        return v;
    }
    else
    {
        list * temp = subsets(s[1 to length-1], v);
        int length = temp->size();

        for(int i=0;i<length;i++) {
            temp.add(s[0]+temp[i]);
        }

        list.add(s[0]);
        return temp;
    }
}

So, for example if s = "123" then output is:

1
2
3
12
13
23
123

Reverse Contents in Array

Procedure :

 1.Take an array.

 2.Then by default function reverse(array_name, array_name + size) .
  reverse(array_name, array_name + size) function exits in algorithm.h header file.

 3.Now print the array. 

 N.B  Here we use new and delete for dynamic memory allocation.

C++ implementation :


#include<bits/stdc++.h>
using namespace std;


int main()
{
   int n;
   cin>>n;

   int *arr = new int[n];


   for(int i=0; i<n; i++)  cin>>arr[i];

   reverse(arr, arr+n);

   for(int i=0; i<n; i++)    cout<<arr[i]<<" ";

   delete[] arr;

   return 0;
}

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

Go to the following setting:

Window -> Preferences -> Java-Compiler-Errors/Warnings-Deprecated and restricted API-Forbidden reference (access rules)

Set it to Warning or Ignore.

<code> vs <pre> vs <samp> for inline and block code snippets

Consider Prism.js: https://prismjs.com/#examples

It makes <pre><code> work and is attractive.

Elasticsearch : Root mapping definition has unsupported parameters index : not_analyzed

As of ES 7, mapping types have been removed. You can read more details here

If you are using Ruby On Rails this means that you may need to remove document_type from your model or concern.

As an alternative to mapping types one solution is to use an index per document type.

Before:

module Searchable
  extend ActiveSupport::Concern

  included do
    include Elasticsearch::Model
    include Elasticsearch::Model::Callbacks
    index_name [Rails.env, Rails.application.class.module_parent_name.underscore].join('_')
    document_type self.name.downcase
  end
end

After:

module Searchable
  extend ActiveSupport::Concern

  included do
    include Elasticsearch::Model
    include Elasticsearch::Model::Callbacks
    index_name [Rails.env, Rails.application.class.module_parent_name.underscore, self.name.downcase].join('_')
  end
end

How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

I want to mention here a very, VERY, interesting technique that is being used in huge projects like jQuery and Modernizr for concatenate things.

Both of this projects are entirely developed with requirejs modules (you can see that in their github repos) and then they use the requirejs optimizer as a very smart concatenator. The interesting thing is that, as you can see, nor jQuery neither Modernizr needs on requirejs to work, and this happen because they erase the requirejs syntatic ritual in order to get rid of requirejs in their code. So they end up with a standalone library that was developed with requirejs modules! Thanks to this they are able to perform cutsom builds of their libraries, among other advantages.

For all those interested in concatenation with the requirejs optimizer, check out this post

Also there is a small tool that abstracts all the boilerplate of the process: AlbanilJS

load external css file in body tag

No, it is not okay to put a link element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):

“This element defines a link. Unlike A, it may only appear in the HEAD section of a document, although it may appear any number of times.”

Remove accents/diacritics in a string in JavaScript

There's a lot out there, but I think this one is simple and good enough:

 function remove_accents(strAccents) {
    var strAccents = strAccents.split('');
    var strAccentsOut = new Array();
    var strAccentsLen = strAccents.length;
    var accents =    "ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž";
    var accentsOut = "AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUuuuuNnSsYyyZz";
    for (var y = 0; y < strAccentsLen; y++) {
        if (accents.indexOf(strAccents[y]) != -1) {
            strAccentsOut[y] = accentsOut.substr(accents.indexOf(strAccents[y]), 1);
        } else
            strAccentsOut[y] = strAccents[y];
    }
    strAccentsOut = strAccentsOut.join('');

    return strAccentsOut;
}

If you also want to remove special characters and transform spaces and hyphens in underscores, do this:

string = remove_accents(string);
string = string.replace(/[^a-z0-9\s]/gi, '').replace(/[-\s]/g, '_');

Custom exception type

From WebReference:

throw { 
  name:        "System Error", 
  level:       "Show Stopper", 
  message:     "Error detected. Please contact the system administrator.", 
  htmlMessage: "Error detected. Please contact the <a href=\"mailto:[email protected]\">system administrator</a>.",
  toString:    function(){return this.name + ": " + this.message;} 
}; 

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

How to make php display \t \n as tab and new line instead of characters

"\n" = new line
'\n' = \n
"\t" = tab
'\t' = \t

Anaconda export Environment file

The easiest way to save the packages from an environment to be installed in another computer is:

$ conda list -e > req.txt

then you can install the environment using

$ conda create -n <environment-name> --file req.txt

if you use pip, please use the following commands: reference https://pip.pypa.io/en/stable/reference/pip_freeze/

$ env1/bin/pip freeze > requirements.txt
$ env2/bin/pip install -r requirements.txt

Can't get value of input type="file"?

$('input[type=file]').val()

That'll get you the file selected.

However, you can't set the value yourself.

Tried to Load Angular More Than Once

I had this same problem ("Tried to Load Angular More Than Once") because I had included twice angularJs file (without perceive) in my index.html.

<script src="angular.js">
<script src="angular.min.js">

How do I install Python packages in Google's Colab?

Joining the party late, but just as a complement, I ran into some problems with Seaborn not so long ago, because CoLab installed a version with !pip that wasn't updated. In my specific case, I couldn't use Scatterplot, for example. The answer to this is below:

To install the module, all you need is:

!pip install seaborn

To upgrade it to the most updated version:

!pip install --upgrade seaborn

If you want to install a specific version

!pip install seaborn==0.9.0

I believe all the rules common to pip apply normally, so that pretty much should work.

jQuery .ready in a dynamically inserted iframe

Using jQuery 1.3.2 the following worked for me:

$('iframe').ready(function() {
  $('body', $('iframe').contents()).html('Hello World!');
});

REVISION:! Actually the above code sometimes looks like it works in Firefox, never looks like it works in Opera.

Instead I implemented a polling solution for my purposes. Simplified down it looks like this:

$(function() {
  function manipIframe() {
    el = $('body', $('iframe').contents());
    if (el.length != 1) {
      setTimeout(manipIframe, 100);
      return;
    }
    el.html('Hello World!');
  }
  manipIframe();
});

This doesn't require code in the called iframe pages. All code resides and executes from the parent frame/window.

How can I use threading in Python?

Using the blazing new concurrent.futures module

def sqr(val):
    import time
    time.sleep(0.1)
    return val * val

def process_result(result):
    print(result)

def process_these_asap(tasks):
    import concurrent.futures

    with concurrent.futures.ProcessPoolExecutor() as executor:
        futures = []
        for task in tasks:
            futures.append(executor.submit(sqr, task))

        for future in concurrent.futures.as_completed(futures):
            process_result(future.result())
        # Or instead of all this just do:
        # results = executor.map(sqr, tasks)
        # list(map(process_result, results))

def main():
    tasks = list(range(10))
    print('Processing {} tasks'.format(len(tasks)))
    process_these_asap(tasks)
    print('Done')
    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main())

The executor approach might seem familiar to all those who have gotten their hands dirty with Java before.

Also on a side note: To keep the universe sane, don't forget to close your pools/executors if you don't use with context (which is so awesome that it does it for you)

Create a list with initial capacity in Python

From what I understand, Python lists are already quite similar to ArrayLists. But if you want to tweak those parameters I found this post on the Internet that may be interesting (basically, just create your own ScalableList extension):

http://mail.python.org/pipermail/python-list/2000-May/035082.html

java.net.SocketException: Connection reset by peer: socket write error When serving a file

This problem is usually caused by writing to a connection that had already been closed by the peer. In this case it could indicate that the user cancelled the download for example.

Setting a minimum/maximum character count for any character using a regular expression

If you also want to match newlines, then you might want to use "^[\s\S]{1,35}$" (depending on the regex engine). Otherwise, as others have said, you should used "^.{1,35}$"

C# error: "An object reference is required for the non-static field, method, or property"

It looks like you want:

public static string GetRandomBits()

Without static, you would need an object before you can call the GetRandomBits() method. However, since the implementation of GetRandomBits() does not depend on the state of any Program object, it's best to declare it static.

How to do an Integer.parseInt() for a decimal number?

String s = "0.01";
double d = Double.parseDouble(s);
int i = (int) d;

The reason for the exception is that an integer does not hold rational numbers (= basically fractions). So, trying to parse 0.3 to a int is nonsense. A double or a float datatype can hold rational numbers.

The way Java casts a double to an int is done by removing the part after the decimal separator by rounding towards zero.

int i = (int) 0.9999;

i will be zero.

How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

I faced similar problem on windows server 2012 STD 64 bit , my problem is resolved after updating windows with all available windows updates.

How can I echo the whole content of a .html file in PHP?

Just use:

<?php
    include("/path/to/file.html");
?>

That will echo it as well. This also has the benefit of executing any PHP in the file.

If you need to do anything with the contents, use file_get_contents(),

For example,

<?php
    $pagecontents = file_get_contents("/path/to/file.html");

    echo str_replace("Banana", "Pineapple", $pagecontents);

?>

This doesn't execute code in that file, so be careful if you expect that to work.

I usually use:

include($_SERVER['DOCUMENT_ROOT']."/path/to/file/as/in/url.html");

as then I can move files without breaking the includes.

How do I convert an Array to a List<object> in C#?

private List<object> ConvertArrayToList(object[] array)
{
  List<object> list = new List<object>();

  foreach(object obj in array)
    list.add(obj);

  return list;
}

Passing std::string by Value or Reference

I believe the normal answer is that it should be passed by value if you need to make a copy of it in your function. Pass it by const reference otherwise.

Here is a good discussion: http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/

How do I find the duplicates in a list and create another list with them?

one-liner, for fun, and where a single statement is required.

(lambda iterable: reduce(lambda (uniq, dup), item: (uniq, dup | {item}) if item in uniq else (uniq | {item}, dup), iterable, (set(), set())))(some_iterable)

How to upload image in CodeIgniter?

Below code for an uploading a single file at a time. This is correct and perfect to upload a single file. Read all commented instructions and follow the code. Definitely, it is worked.

public function upload_file() {
    ***// Upload folder location***
    $config['upload_path'] = './public/upload/';

    ***// Allowed file type***
    $config['allowed_types'] = 'jpg|jpeg|png|pdf';

    ***// Max size, i will set 2MB***
    $config['max_size'] = '2024';

    $config['max_width'] = '1024';
    $config['max_height'] = '768';

    ***// load upload library***            
    $this->load->library('upload', $config);

    ***// do_upload is the method, to send the particular image and file on that 
       // particular 
       // location that is detail in $config['upload_path']. 
       // In bracks will set name upload, here you need to set input name attribute 
       // value.***

    if($this->upload->do_upload('upload')) {
       $data = $this->upload->data();
       $post['upload'] = $data['file_name'];
    } else {
      $error = array('error' => $this->upload->display_errors());
    }
 }

How to Round to the nearest whole number in C#

I was looking for this, but my example was to take a number, such as 4.2769 and drop it in a span as just 4.3. Not exactly the same, but if this helps:

Model.Statistics.AverageReview   <= it's just a double from the model

Then:

@Model.Statistics.AverageReview.ToString("n1")   <=gives me 4.3
@Model.Statistics.AverageReview.ToString("n2")   <=gives me 4.28

etc...

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

There are differences with some exceptions, e.g. KeyboardInterrupt.

Reading PEP8:

A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:).

How to implement the --verbose or -v option into a script?

It might be cleaner if you have a function, say called vprint, that checks the verbose flag for you. Then you just call your own vprint function any place you want optional verbosity.

Getting multiple keys of specified value of a generic Dictionary?

A dictionary doesn't keep an hash of the values, only the keys, so any search over it using a value is going to take at least linear time. Your best bet is to simply iterate over the elements in the dictionary and keep track of the matching keys or switch to a different data structure, perhaps maintain two dictionary mapping key->value and value->List_of_keys. If you do the latter you will trade storage for look up speed. It wouldn't take much to turn @Cybis example into such a data structure.

Speed up rsync with Simultaneous/Concurrent File Transfers?

There are a number of alternative tools and approaches for doing this listed arround the web. For example:

  • The NCSA Blog has a description of using xargs and find to parallelize rsync without having to install any new software for most *nix systems.

  • And parsync provides a feature rich Perl wrapper for parallel rsync.

Differences between fork and exec

enter image description herefork():

It creates a copy of running process. The running process is called parent process & newly created process is called child process. The way to differentiate the two is by looking at the returned value:

  1. fork() returns the process identifier (pid) of the child process in the parent

  2. fork() returns 0 in the child.

exec():

It initiates a new process within a process. It loads a new program into the current process, replacing the existing one.

fork() + exec():

When launching a new program is to firstly fork(), creating a new process, and then exec() (i.e. load into memory and execute) the program binary it is supposed to run.

int main( void ) 
{
    int pid = fork();
    if ( pid == 0 ) 
    {
        execvp( "find", argv );
    }

    //Put the parent to sleep for 2 sec,let the child finished executing 
    wait( 2 );

    return 0;
}

What is the current choice for doing RPC in Python?

There are some attempts at making SOAP work with python, but I haven't tested it much so I can't say if it is good or not.

SOAPy is one example.

Python interpreter error, x takes no arguments (1 given)

Your updateVelocity() method is missing the explicit self parameter in its definition.

Should be something like this:

def updateVelocity(self):    
    for x in range(0,len(self.velocity)):
        self.velocity[x] = 2*random.random()*(self.pbestx[x]-self.current[x]) + 2 \
          * random.random()*(self.gbest[x]-self.current[x])

Your other methods (except for __init__) have the same problem.

No provider for Http StaticInjectorError

I am on an angular project that (unfortunately) uses source code inclusion via tsconfig.json to connect different collections of code. I came across a similar StaticInjector error for a service (e.g.RestService in the top example) and I was able to fix it by listing the service dependencies in the deps array when providing the affected service in the module, for example:

import { HttpClient } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { RestService } from 'mylib/src/rest/rest.service';
...
@NgModule({
  imports: [
    ...
    HttpModule,
    ...
  ],
  providers: [
    {
      provide: RestService,
      useClass: RestService,
      deps: [HttpClient] /* the injected services in the constructor for RestService */
    },
  ]
  ...

..The underlying connection was closed: An unexpected error occurred on a receive

None of the solutions out there worked for me. What I eventually discovered was the following combination:

  • Client system: Windows XP Pro SP3
  • Client system has .NET Framework 2 SP1, 3, 3.5 installed
  • Software targeting .NET 2 using classic web services (.asmx)
  • Server: IIS6
  • Web site "Secure Communications" set to:
    • Require Secure Channel
    • Accept client certificates

enter image description here

Apparently, it was this last option that was causing the issue. I discovered this by trying to open the web service URL directly in Internet Explorer. It just hung indefinitely trying to load the page. Disabling "Accept client certificates" allowed the page to load normally. I am not sure if it was a problem with this specific system (maybe a glitched client certificate?) Since I wasn't using client certificates this option worked for me.

How to write inside a DIV box with javascript

_x000D_
_x000D_
document.getElementById('log').innerHTML += '<br>Some new content!';
_x000D_
<div id="log">initial content</div>
_x000D_
_x000D_
_x000D_

Why is my Spring @Autowired field null?

I think you have missed to instruct spring to scan classes with annotation.

You can use @ComponentScan("packageToScan") on the configuration class of your spring application to instruct spring to scan.

@Service, @Component etc annotations add meta description.

Spring only injects instances of those classes which are either created as bean or marked with annotation.

Classes marked with annotation need to be identified by spring before injecting, @ComponentScan instruct spring look for the classes marked with annotation. When Spring finds @Autowired it searches for the related bean, and injects the required instance.

Adding annotation only, does not fix or facilitate the dependency injection, Spring needs to know where to look for.

Unzip a file with php

Simply try this yourDestinationDir is the destination to extract to or remove -d yourDestinationDir to extract to root dir.

$master = 'someDir/zipFileName';
$data = system('unzip -d yourDestinationDir '.$master.'.zip');

Count multiple columns with group by in one query

One solution is to wrap it in a subquery

SELECT *
FROM
(
    SELECT COUNT(column1),column1 FROM table GROUP BY column1
    UNION ALL
    SELECT COUNT(column2),column2 FROM table GROUP BY column2
    UNION ALL
    SELECT COUNT(column3),column3 FROM table GROUP BY column3
) s

Convert NVARCHAR to DATETIME in SQL Server 2008

SELECT CONVERT(NVARCHAR, LoginDate, 105)+' '+CONVERT(NVARCHAR, LoginDate, 108) AS LoginDate FROM YourTable

Output
-------------------
29-08-2013 13:55:48

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

I was having this problem with Android Studio when I'm behind a proxy. I was using Crashlytics that tries to upload the mapping file during a build.

I added the missing proxy certificate to the truststore located at /Users/[username]/Documents/Android Studio.app/Contents/jre/jdk/Contents/Home/jre/lib/security/cacerts

with the following command: keytool -import -trustcacerts -keystore cacerts -storepass [password] -noprompt -alias [alias] -file [my_certificate_location]

for example with the default truststore password keytool -import -trustcacerts -keystore cacerts -storepass changeit -noprompt -alias myproxycert -file /Users/myname/Downloads/MyProxy.crt

Facebook Javascript SDK Problem: "FB is not defined"

Have you set the appId property to your current application ID?

How do I run a Python script from C#?

If you're willing to use IronPython, you can execute scripts directly in C#:

using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

private static void doPython()
{
    ScriptEngine engine = Python.CreateEngine();
    engine.ExecuteFile(@"test.py");
}

Get IronPython here.

Replace only some groups with Regex

You can do this using lookahead and lookbehind:

var pattern = @"(?<=-)\d+(?=-)";
var replaced = Regex.Replace(text, pattern, "AA"); 

How to make an executable JAR file?

Here it is in one line:

jar cvfe myjar.jar package.MainClass *.class

where MainClass is the class with your main method, and package is MainClass's package.

Note you have to compile your .java files to .class files before doing this.

c  create new archive
v  generate verbose output on standard output
f  specify archive file name
e  specify application entry point for stand-alone application bundled into an executable jar file

This answer inspired by Powerslave's comment on another answer.

How to create a secure random AES key in Java?

I would use your suggested code, but with a slight simplification:

KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256); // for example
SecretKey secretKey = keyGen.generateKey();

Let the provider select how it plans to obtain randomness - don't define something that may not be as good as what the provider has already selected.

This code example assumes (as Maarten points out below) that you've configured your java.security file to include your preferred provider at the top of the list. If you want to manually specify the provider, just call KeyGenerator.getInstance("AES", "providerName");.

For a truly secure key, you need to be using a hardware security module (HSM) to generate and protect the key. HSM manufacturers will typically supply a JCE provider that will do all the key generation for you, using the code above.

Converting JavaScript object with numeric keys into array

Nothing hard here. Loop over your object elements and assign them to the array

var obj = {"0":"1","1":"2","2":"3","3":"4"};
var arr = [];
for (elem in obj) {
   arr.push(obj[elem]);
}

http://jsfiddle.net/Qq2aM/

'mvn' is not recognized as an internal or external command,

On my Windows 7 machine I have the following environment variables:

  • JAVA_HOME=C:\Program Files\Java\jdk1.7.0_07

  • M2_HOME=C:\apache-maven-3.0.3

On my PATH variable, I have (among others) the following:

  • %JAVA_HOME%\bin;%M2_HOME%\bin

I tried doing what you've done with %M2% having the nested %M2_HOME% and it also works.

On Duplicate Key Update same as insert

you can use insert ignore for such case, it will ignore if it gets duplicate records INSERT IGNORE ... ; -- without ON DUPLICATE KEY

PHP: How do you determine every Nth iteration of a loop?

every 3 posts?

if($counter % 3 == 0){
    echo IMAGE;
}

Get single listView SelectedItem

If you want to select single listview item no mouse click over it try this.

private void timeTable_listView_MouseUp(object sender, MouseEventArgs e)
        {
            Point mousePos = timeTable_listView.PointToClient(Control.MousePosition);
            ListViewHitTestInfo hitTest = timeTable_listView.HitTest(mousePos);



            try
            {
            int columnIndex = hitTest.Item.SubItems.IndexOf(hitTest.SubItem);
            edit_textBox.Text = timeTable_listView.SelectedItems[0].SubItems[columnIndex].Text;
            }
            catch(Exception)
            {

            }



        }

How can I check whether Google Maps is fully loaded?

Where the variable map is an object of type GMap2:

    GEvent.addListener(map, "tilesloaded", function() {
      console.log("Map is fully loaded");
    });

Draw line in UIView

You can user UIBezierPath Class for this:

And can draw as many lines as you want:

I have subclassed UIView :

    @interface MyLineDrawingView()
    {
       NSMutableArray *pathArray;
       NSMutableDictionary *dict_path;
       CGPoint startPoint, endPoint;
    }

       @property (nonatomic,retain)   UIBezierPath *myPath;
    @end

And initialized the pathArray and dictPAth objects which will be used for line drawing. I am writing the main portion of the code from my own project:

- (void)drawRect:(CGRect)rect
{

    for(NSDictionary *_pathDict in pathArray)
    {
        [((UIColor *)[_pathDict valueForKey:@"color"]) setStroke]; // this method will choose the color from the receiver color object (in this case this object is :strokeColor)
        [[_pathDict valueForKey:@"path"] strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
    }

    [[dict_path objectForKey:@"color"] setStroke]; // this method will choose the color from the receiver color object (in this case this object is :strokeColor)
    [[dict_path objectForKey:@"path"] strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];

}

touchesBegin method :

UITouch *touch = [touches anyObject];
startPoint = [touch locationInView:self];
myPath=[[UIBezierPath alloc]init];
myPath.lineWidth = currentSliderValue*2;
dict_path = [[NSMutableDictionary alloc] init];

touchesMoved Method:

UITouch *touch = [touches anyObject];
endPoint = [touch locationInView:self];

 [myPath removeAllPoints];
        [dict_path removeAllObjects];// remove prev object in dict (this dict is used for current drawing, All past drawings are managed by pathArry)

    // actual drawing
    [myPath moveToPoint:startPoint];
    [myPath addLineToPoint:endPoint];

    [dict_path setValue:myPath forKey:@"path"];
    [dict_path setValue:strokeColor forKey:@"color"];

    //                NSDictionary *tempDict = [NSDictionary dictionaryWithDictionary:dict_path];
    //                [pathArray addObject:tempDict];
    //                [dict_path removeAllObjects];
    [self setNeedsDisplay];

touchesEnded Method:

        NSDictionary *tempDict = [NSDictionary dictionaryWithDictionary:dict_path];
        [pathArray addObject:tempDict];
        [dict_path removeAllObjects];
        [self setNeedsDisplay];

rails simple_form - hidden field - create?

try this

= f.input :title, :as => :hidden, :input_html => { :value => "some value" }

console.log not working in Angular2 Component (Typescript)

The console.log should be wrapped in a function , the "default" function for every class is its constructor so it should be declared there.

import { Component } from '@angular/core';
console.log("Hello1");

 @Component({
  selector: 'hello-console',
})
    export class App {
     s: string = "Hello2";
    constructor(){
     console.log(s); 
    }

}

Send a file via HTTP POST with C#

     public string SendFile(string filePath)
            {
                WebResponse response = null;
                try
                {
                    string sWebAddress = "Https://www.address.com";

                    string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
                    byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
                    HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(sWebAddress);
                    wr.ContentType = "multipart/form-data; boundary=" + boundary;
                    wr.Method = "POST";
                    wr.KeepAlive = true;
                    wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
                    Stream stream = wr.GetRequestStream();
                    string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";

                    stream.Write(boundarybytes, 0, boundarybytes.Length);
                    byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(filePath);
                    stream.Write(formitembytes, 0, formitembytes.Length);
                    stream.Write(boundarybytes, 0, boundarybytes.Length);
                    string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
                    string header = string.Format(headerTemplate, "file", Path.GetFileName(filePath), Path.GetExtension(filePath));
                    byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                    stream.Write(headerbytes, 0, headerbytes.Length);

                    FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    byte[] buffer = new byte[4096];
                    int bytesRead = 0;
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                        stream.Write(buffer, 0, bytesRead);
                    fileStream.Close();

                    byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                    stream.Write(trailer, 0, trailer.Length);
                    stream.Close();

                    response = wr.GetResponse();
                    Stream responseStream = response.GetResponseStream();
                    StreamReader streamReader = new StreamReader(responseStream);
                    string responseData = streamReader.ReadToEnd();
                    return responseData;
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
                finally
                {
                    if (response != null)
                        response.Close();
                }
            }

How to search for file names in Visual Studio?

With Visual Studio 2017 Community edition on mac, the shortcut is:

  • Cmd+Shift+D: Find by file name
  • Cmd+Shift+T: Find by type name

To see these commands, navigate to the top menu: Search > Go To

How to check if element has any children in Javascript?

Late but document fragment could be a node:

function hasChild(el){
    var child = el && el.firstChild;
    while (child) {
        if (child.nodeType === 1 || child.nodeType === 11) {
            return true;
        }
        child = child.nextSibling;
    }
    return false;
}
// or
function hasChild(el){
    for (var i = 0; el && el.childNodes[i]; i++) {
        if (el.childNodes[i].nodeType === 1 || el.childNodes[i].nodeType === 11) {
            return true;
        }
    }
    return false;
}

See:
https://github.com/k-gun/so/blob/master/so.dom.js#L42
https://github.com/k-gun/so/blob/master/so.dom.js#L741

Android ViewPager with bottom dots

I created a library to address the need for a page indicator in a ViewPager. My library contains a View called DotIndicator. To use my library, add compile 'com.matthew-tamlin:sliding-intro-screen:3.2.0' to your gradle build file.

The View can be added to your layout by adding the following:

    <com.matthewtamlin.sliding_intro_screen_library.indicators.DotIndicator
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:numberOfDots=YOUR_INT_HERE
            app:selectedDotIndex=YOUR_INT_HERE/>

The above code perfectly replicates the functionality of the dots on the Google Launcher homescreen, however if you want to further customise it then the following attributes can be added:

  • app:unselectedDotDiameter and app:selectedDotDiameter to set the diameters of the dots
  • app:unselectedDotColor and app:selectedDotColor to set the colors of the dots
  • app:spacingBetweenDots to change the distance between the dots
  • app:dotTransitionDuration to set the time for animating the change from small to big (and back)

Additionally, the view can be created programatically using:

DotIndicator indicator = new DotIndicator(context);

Methods exist to modify the properties, similar to the attributes. To update the indicator to show a different page as selected, just call method indicator.setSelectedItem(int, true) from inside ViewPager.OnPageChangeListener.onPageSelected(int).

Here's an example of it in use:

enter image description here

If you're interested, the library was actually designed to make intro screens like the one shown in the above gif.

Github source available here: https://github.com/MatthewTamlin/SlidingIntroScreen

Submitting the value of a disabled input field

I know this is old but I just ran into this problem and none of the answers are suitable. nickf's solution works but it requires javascript. The best way is to disable the field and still pass the value is to use a hidden input field to pass the value to the form. For example,

<input type="text" value="22.2222" disabled="disabled" />
<input type="hidden" name="lat" value="22.2222" />

This way the value is passed but the user sees the greyed out field. The readonly attribute does not gray it out.

Thread Safe C# Singleton Pattern

In almost every case (that is: all cases except the very first ones), instance won't be null. Acquiring a lock is more costly than a simple check, so checking once the value of instance before locking is a nice and free optimization.

This pattern is called double-checked locking: http://en.wikipedia.org/wiki/Double-checked_locking

Java Enum return Int

Font.PLAIN is not an enum. It is just an int. If you need to take the value out of an enum, you can't avoid calling a method or using a .value, because enums are actually objects of its own type, not primitives.

If you truly only need an int, and you are already to accept that type-safety is lost the user may pass invalid values to your API, you may define those constants as int also:

public final class DownloadType {
    public static final int AUDIO = 0;
    public static final int VIDEO = 1;
    public static final int AUDIO_AND_VIDEO = 2;

    // If you have only static members and want to simulate a static
    // class in Java, then you can make the constructor private.
    private DownloadType() {}
}

By the way, the value field is actually redundant because there is also an .ordinal() method, so you could define the enum as:

enum DownloadType { AUDIO, VIDEO, AUDIO_AND_VIDEO }

and get the "value" using

DownloadType.AUDIO_AND_VIDEO.ordinal()

Edit: Corrected the code.. static class is not allowed in Java. See this SO answer with explanation and details on how to define static classes in Java.

Java: is there a map function?

This is another functional lib with which you may use map: http://code.google.com/p/totallylazy/

sequence(1, 2).map(toString); // lazily returns "1", "2"

What is the shortest function for reading a cookie by name in JavaScript?

(edit: posted the wrong version first.. and a non-functional one at that. Updated to current, which uses an unparam function that is much like the second example.)

Nice idea in the first example cwolves. I built on both for a fairly compact cookie reading/writing function that works across multiple subdomains. Figured I'd share in case anyone else runs across this thread looking for that.

(function(s){
  s.strToObj = function (x,splitter) {
    for ( var y = {},p,a = x.split (splitter),L = a.length;L;) {
      p = a[ --L].split ('=');
      y[p[0]] = p[1]
    }
    return y
  };
  s.rwCookie = function (n,v,e) {
    var d=document,
        c= s.cookies||s.strToObj(d.cookie,'; '),
        h=location.hostname,
        domain;
    if(v){
      domain = h.slice(h.lastIndexOf('.',(h.lastIndexOf('.')-1))+1);
      d.cookie = n + '=' + (c[n]=v) + (e ? '; expires=' + e : '') + '; domain=.' + domain + '; path=/'
    }
    return c[n]||c
  };
})(some_global_namespace)
  • If you pass rwCookie nothing, it will get all cookies into cookie storage
  • Passed rwCookie a cookie name, it gets that cookie's value from storage
  • Passed a cookie value, it writes the cookie and places the value in storage
  • Expiration defaults to session unless you specify one

How to change MySQL data directory?

This solution works in Windows 7 using Workbench. You will need Administrator privileges to do this. It creates a junction (like a shortcut) to wherever you really want to store your data

Open Workbench and select INSTANCE - Startup / Shutdown Stop the server

Install Junction Master from https://bitsum.com/junctionmaster.php

Navigate to C:\ProgramData\MySQL\MySQL Server 5.6

Right click on Data and select "MOVE and then LINK folder to ..." Accept the warning Point destination to "Your new data directory here without the quotes" Click MOVE AND LINK

Now go to "Your new data directory here without the quotes"

Right click on Data Go to the security tab Click Edit Click Add Type NETWORK SERVICE then Check Names Click OK Click the Allow Full Control checkbox and then OK

Go back to Workbench and Start the server

This method worked for me using MySQL Workbench 6.2 on Windows 7 Enterprise.

New to unit testing, how to write great tests?

Unit testing is about the output you get from a function/method/application. It does not matter at all how the result is produced, it just matters that it is correct. Therefore, your approach of counting calls to inner methods and such is wrong. What I tend to do is sit down and write what a method should return given certain input values or a certain environment, then write a test which compares the actual value returned with what I came up with.

How do you change the launcher logo of an app in Android Studio?

Here is another solution which I feel is more sensible for those working on Android Studio:

  1. Expand the project root folder in the Project View
  2. Right Click on the app folder
  3. In the Context Menu go to New->Image Asset
  4. In the pop up that appears select the the new logo you would like to have(image/clip art/text).
  5. If you were selecting the image radio button (as is the default choice), if you clicked on the 3-buttons to show the path tree to locate your .png image file, most probably you might not be seeing it, so drag it from the Windows Explorer (if Windows) and drop it in the tree, and it will appear and ready for being selected.

That is it! You have a new logo for you app now.

Using a BOOL property

Apple recommends for stylistic purposes.If you write this code:

@property (nonatomic,assign) BOOL working;

Then you can not use [object isWorking].
It will show an error. But if you use below code means

@property (assign,getter=isWorking) BOOL working;

So you can use [object isWorking] .

Using Pairs or 2-tuples in Java

Android Tuple Utils

This object provides a sensible implementation of equals(), returning true if equals() is true on each of the contained objects.

Clear MySQL query cache without restarting server

I believe you can use...

RESET QUERY CACHE;

...if the user you're running as has reload rights. Alternatively, you can defragment the query cache via...

FLUSH QUERY CACHE;

See the Query Cache Status and Maintenance section of the MySQL manual for more information.

What does the variable $this mean in PHP?

The best way to learn about the $this variable in PHP is to try it against the interpreter in various contexts:

print isset($this);              //true,   $this exists
print gettype($this);            //Object, $this is an object 
print is_array($this);           //false,  $this isn't an array
print get_object_vars($this);    //true,   $this's variables are an array
print is_object($this);          //true,   $this is still an object
print get_class($this);          //YourProject\YourFile\YourClass
print get_parent_class($this);   //YourBundle\YourStuff\YourParentClass
print gettype($this->container); //object
print_r($this);                  //delicious data dump of $this
print $this->yourvariable        //access $this variable with ->

So the $this pseudo-variable has the Current Object's method's and properties. Such a thing is useful because it lets you access all member variables and member methods inside the class. For example:

Class Dog{
    public $my_member_variable;                             //member variable

    function normal_method_inside_Dog() {                   //member method

        //Assign data to member variable from inside the member method
        $this->my_member_variable = "whatever";

        //Get data from member variable from inside the member method.
        print $this->my_member_variable;
    }
}

$this is reference to a PHP Object that was created by the interpreter for you, that contains an array of variables.

If you call $this inside a normal method in a normal class, $this returns the Object (the class) to which that method belongs.

It's possible for $this to be undefined if the context has no parent Object.

php.net has a big page talking about PHP object oriented programming and how $this behaves depending on context. https://www.php.net/manual/en/language.oop5.basic.php

How to get base url with jquery or javascript?

This is not possible from javascript, because this is a server-side property. Javascript on the client cannot know where joomla is installed. The best option is to somehow include the value of $this->baseurl into the page javascript and then use this value (phpBaseUrl).

You can then build the url like this:

var loc = window.location;
var baseUrl = loc.protocol + "//" + loc.hostname + (loc.port? ":"+loc.port : "") + "/" + phpBaseUrl;

Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)

Pass a UTC timezone object to datetime.now() instead of using datetime.utcnow():

from datetime import datetime, timezone

datetime.now(timezone.utc)
>>> datetime.datetime(2020, 1, 8, 6, 6, 24, 260810, tzinfo=datetime.timezone.utc)

datetime.now(timezone.utc).isoformat()
>>> '2020-01-08T06:07:04.492045+00:00'

That looks good, so let's see what Django and dateutil think:

from django.utils.timezone import is_aware

is_aware(datetime.now(timezone.utc))
>>> True

from dateutil.parser import isoparse

is_aware(isoparse(datetime.now(timezone.utc).isoformat()))
>>> True

Note that you need to use isoparse() because the Python documentation for datetime.fromisoformat() says it "does not support parsing arbitrary ISO 8601 strings".

Okay, the Python datetime object and the ISO 8601 string are both UTC "aware". Now let's look at what JavaScript thinks of the datetime string. Borrowing from this answer we get:

let date= '2020-01-08T06:07:04.492045+00:00';
const dateParsed = new Date(Date.parse(date))

document.write(dateParsed);
document.write("\n");
// Tue Jan 07 2020 22:07:04 GMT-0800 (Pacific Standard Time)

document.write(dateParsed.toISOString());
document.write("\n");
// 2020-01-08T06:07:04.492Z

document.write(dateParsed.toUTCString());
document.write("\n");
// Wed, 08 Jan 2020 06:07:04 GMT

Notes:

I approached this problem with a few goals:

  • generate a UTC "aware" datetime string in ISO 8601 format
  • use only Python Standard Library functions for datetime object and string creation
  • validate the datetime object and string with the Django timezone utility function and the dateutil parser
  • use JavaScript functions to validate that the ISO 8601 datetime string is UTC aware

Note that this approach does not include a Z suffix and does not use utcnow(). But it's based on the recommendation in the Python documentation and it passes muster with both Django and JavaScript.

See also:

What are the ways to make an html link open a folder

Hope it will help someone someday. I was making a small POC and came across this. A button, onClick display contents of the folder. Below is the HTML,

<input type=button onClick="parent.location='file:///C:/Users/' " value='Users'>

Initial size for the ArrayList

You're confusing the size of the array list with its capacity:

  • the size is the number of elements in the list;
  • the capacity is how many elements the list can potentially accommodate without reallocating its internal structures.

When you call new ArrayList<Integer>(10), you are setting the list's initial capacity, not its size. In other words, when constructed in this manner, the array list starts its life empty.

One way to add ten elements to the array list is by using a loop:

for (int i = 0; i < 10; i++) {
  arr.add(0);
}

Having done this, you can now modify elements at indices 0..9.

Angular 5 Service to read local .json file

First You have to inject HttpClient and Not HttpClientModule, second thing you have to remove .map((res:any) => res.json()) you won't need it any more because the new HttpClient will give you the body of the response by default , finally make sure that you import HttpClientModule in your AppModule :

import { HttpClient } from '@angular/common/http'; 
import { Observable } from 'rxjs';

@Injectable()
export class AppSettingsService {

   constructor(private http: HttpClient) {
        this.getJSON().subscribe(data => {
            console.log(data);
        });
    }

    public getJSON(): Observable<any> {
        return this.http.get("./assets/mydata.json");
    }
}

to add this to your Component:

@Component({
    selector: 'mycmp',
    templateUrl: 'my.component.html',
    styleUrls: ['my.component.css']
})
export class MyComponent implements OnInit {
    constructor(
        private appSettingsService : AppSettingsService 
    ) { }

   ngOnInit(){
       this.appSettingsService.getJSON().subscribe(data => {
            console.log(data);
        });
   }
}

C - split string into an array of strings

Since you've already looked into strtok just continue down the same path and split your string using space (' ') as a delimiter, then use something as realloc to increase the size of the array containing the elements to be passed to execvp.

See the below example, but keep in mind that strtok will modify the string passed to it. If you don't want this to happen you are required to make a copy of the original string, using strcpy or similar function.

char    str[]= "ls -l";
char ** res  = NULL;
char *  p    = strtok (str, " ");
int n_spaces = 0, i;


/* split string and append tokens to 'res' */

while (p) {
  res = realloc (res, sizeof (char*) * ++n_spaces);

  if (res == NULL)
    exit (-1); /* memory allocation failed */

  res[n_spaces-1] = p;

  p = strtok (NULL, " ");
}

/* realloc one extra element for the last NULL */

res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;

/* print the result */

for (i = 0; i < (n_spaces+1); ++i)
  printf ("res[%d] = %s\n", i, res[i]);

/* free the memory allocated */

free (res);

res[0] = ls
res[1] = -l
res[2] = (null)

Naming returned columns in Pandas aggregate function?

If you want to have a behavior similar to JMP, creating column titles that keep all info from the multi index you can use:

newidx = []
for (n1,n2) in df.columns.ravel():
    newidx.append("%s-%s" % (n1,n2))
df.columns=newidx

It will change your dataframe from:

    I                       V
    mean        std         first
V
4200.0  25.499536   31.557133   4200.0
4300.0  25.605662   31.678046   4300.0
4400.0  26.679005   32.919996   4400.0
4500.0  26.786458   32.811633   4500.0

to

    I-mean      I-std       V-first
V
4200.0  25.499536   31.557133   4200.0
4300.0  25.605662   31.678046   4300.0
4400.0  26.679005   32.919996   4400.0
4500.0  26.786458   32.811633   4500.0

Using scanner.nextLine()

Rather than placing an extra scanner.nextLine() each time you want to read something, since it seems you want to accept each input on a new line, you might want to instead changing the delimiter to actually match only newlines (instead of any whitespace, as is the default)

import java.util.Scanner;

class ScannerTest {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        scanner.useDelimiter("\\n");

        System.out.print("Enter an index: ");
        int index = scanner.nextInt();

        System.out.print("Enter a sentence: ");
        String sentence = scanner.next();

        System.out.println("\nYour sentence: " + sentence);
        System.out.println("Your index: " + index);
    }
}

Thus, to read a line of input, you only need scanner.next() that has the same behavior delimiter-wise of next{Int, Double, ...}

The difference with the "nextLine() every time" approach, is that the latter will accept, as an index also <space>3, 3<space> and 3<space>whatever while the former only accepts 3 on a line on its own

How to customize listview using baseadapter

public class ListElementAdapter extends BaseAdapter{

    String[] data;
    Context context;
    LayoutInflater layoutInflater;


    public ListElementAdapter(String[] data, Context context) {
        super();
        this.data = data;
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {

        return data.length;
    }

    @Override
    public Object getItem(int position) {

        return null;
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {


        convertView= layoutInflater.inflate(R.layout.item, null);

        TextView txt=(TextView)convertView.findViewById(R.id.text);

        txt.setText(data[position]);



        return convertView;
    }
}

Just call ListElementAdapter in your Main Activity and set Adapter to ListView.

Can you break from a Groovy "each" closure?

Replace each loop with any closure.

def list = [1, 2, 3, 4, 5]
list.any { element ->
    if (element == 2)
        return // continue

    println element

    if (element == 3)
        return true // break
}

Output

1
3

Confused by python file mode "w+"

I suspect there are two ways to handle what I think you'r trying to achieve.

1) which is obvious, is open the file for reading only, read it into memory then open the file with t, then write your changes.

2) use the low level file handling routines:

# Open file in RW , create if it doesn't exist. *Don't* pass O_TRUNC
 fd = os.open(filename, os.O_RDWR | os.O_CREAT)

Hope this helps..

Qt 5.1.1: Application failed to start because platform plugin "windows" is missing

I created a platforms directory next to my exe location and put qwindows.dll inside, but I still received the "Failed to load platform plugin "windows". Available platforms are: windows" error.

I had copied qwindows.dll from C:\Qt\Qt5.1.1\Tools\QtCreator\bin\plugins\platforms, which is not the right location. I looked at the debug log from running in Qt Creator and found that my app was looking in C:\Qt\Qt5.1.1\5.1.1\mingw48_32\plugins\platforms when it ran in the debugger.

When I copied from C:\Qt\Qt5.1.1\5.1.1\mingw48_32\plugins\platforms, everything worked fine.

What is a constant reference? (not a reference to a constant)

As it mentioned in another answers, a reference is inherently const.

int &ref = obj;

Once you initialized a reference with an object, you can't unbound this reference with its object it refers to. A reference works just like an alias.

When you declare a const reference, it is nothing but a reference which refers to a const object.

const int &ref = obj;

The declarative sentences above like const and int is determining the available features of the object which will be referenced by the reference. To be more clear, I want to show you the pointer equivalent of a const reference;

const int *const ptr = &obj;

So the above line of code is equivalent to a const reference in its working way. Additionally, there is a one last point which I want to mention;

A reference must be initialized only with an object

So when you do this, you are going to get an error;

int  &r = 0; // Error: a nonconst reference cannot be initialized to a literal

This rule has one exception. If the reference is declared as const, then you can initialize it with literals as well;

const int  &r = 0; // a valid approach

Delete statement in SQL is very slow

I read this article it was really helpful for troubleshooting any kind of inconveniences

https://support.microsoft.com/en-us/kb/224453

this is a case of waitresource KEY: 16:72057595075231744 (ab74b4daaf17)

-- First SQL Provider to find the SPID (Session ID)

-- Second Identify problem, check Status, Open_tran, Lastwaittype, waittype, and waittime
-- iMPORTANT Waitresource select * from sys.sysprocesses where spid = 57

select * from sys.databases where database_id=16

-- with Waitresource check this to obtain object id 
select * from sys.partitions where hobt_id=72057595075231744

select * from sys.objects where object_id=2105058535

What do Clustered and Non clustered index actually mean?

Let me offer a textbook definition on "clustering index", which is taken from 15.6.1 from Database Systems: The Complete Book:

We may also speak of clustering indexes, which are indexes on an attribute or attributes such that all of tuples with a fixed value for the search key of this index appear on roughly as few blocks as can hold them.

To understand the definition, let's take a look at Example 15.10 provided by the textbook:

A relation R(a,b) that is sorted on attribute a and stored in that order, packed into blocks, is surely clusterd. An index on a is a clustering index, since for a given a-value a1, all the tuples with that value for a are consecutive. They thus appear packed into blocks, execept possibly for the first and last blocks that contain a-value a1, as suggested in Fig.15.14. However, an index on b is unlikely to be clustering, since the tuples with a fixed b-value will be spread all over the file unless the values of a and b are very closely correlated.

Fig 15.14

Note that the definition does not enforce the data blocks have to be contiguous on the disk; it only says tuples with the search key are packed into as few data blocks as possible.

A related concept is clustered relation. A relation is "clustered" if its tuples are packed into roughly as few blocks as can possibly hold those tuples. In other words, from a disk block perspective, if it contains tuples from different relations, then those relations cannot be clustered (i.e., there is a more packed way to store such relation by swapping the tuples of that relation from other disk blocks with the tuples the doesn't belong to the relation in the current disk block). Clearly, R(a,b) in example above is clustered.

To connect two concepts together, a clustered relation can have a clustering index and nonclustering index. However, for non-clustered relation, clustering index is not possible unless the index is built on top of the primary key of the relation.

"Cluster" as a word is spammed across all abstraction levels of database storage side (three levels of abstraction: tuples, blocks, file). A concept called "clustered file", which describes whether a file (an abstraction for a group of blocks (one or more disk blocks)) contains tuples from one relation or different relations. It doesn't relate to the clustering index concept as it is on file level.

However, some teaching material likes to define clustering index based on the clustered file definition. Those two types of definitions are the same on clustered relation level, no matter whether they define clustered relation in terms of data disk block or file. From the link in this paragraph,

An index on attribute(s) A on a file is a clustering index when: All tuples with attribute value A = a are stored sequentially (= consecutively) in the data file

Storing tuples consecutively is the same as saying "tuples are packed into roughly as few blocks as can possibly hold those tuples" (with minor difference on one talking about file, the other talking about disk). It's because storing tuple consecutively is the way to achieve "packed into roughly as few blocks as can possibly hold those tuples".