Programs & Examples On #Limit

Relates to any sort of limit applied to data or resources, e.g. limiting the size or value of a variable, limiting the rate of incoming traffic or CPU usage. [tag:sql-limit] should be used to refer to the LIMIT keyword in SQL.

MySQL JOIN with LIMIT 1 on joined table

Accepted answer by @goggin13 looks wrong. Other solutions provided to-date will work, but suffer from the n+1 problem and as such, suffer a performance hit.

n+1 problem: If there are 100 categories, then we would have to do 1 select to get the categories, then for each of the 100 categories returned, we would need to do a select to get the products in that category. So 101 SELECT queries would be performed.

My alternative solution solves the n+1 problem and consequently should be significantly more performant as only 2 selects are being performed.

    (SELECT, c.title, AS product_id, p.title
    FROM categories AS c
    JOIN products AS p ON = p.category_id

C#: Limit the length of a string?

foo = foo.Substring(0,5);

How to limit the number of dropzone.js files uploaded?

Alternative solution that worked really well for me:

init: function() {
    this.on("addedfile", function(event) {
        while (this.files.length > this.options.maxFiles) {

Limiting Python input strings to certain characters and lengths

Question 1: Restrict to certain characters

You are right, this is easy to solve with regular expressions:

import re

input_str = raw_input("Please provide some info: ")
if not re.match("^[a-z]*$", input_str):
    print "Error! Only letters a-z allowed!"

Question 2: Restrict to certain length

As Tim mentioned correctly, you can do this by adapting the regular expression in the first example to only allow a certain number of letters. You can also manually check the length like this:

input_str = raw_input("Please provide some info: ")
if len(input_str) > 15:
    print "Error! Only 15 characters allowed!"

Or both in one:

import re

input_str = raw_input("Please provide some info: ")
if not re.match("^[a-z]*$", input_str):
    print "Error! Only letters a-z allowed!"
elif len(input_str) > 15:
    print "Error! Only 15 characters allowed!"

print "Your input was:", input_str

Pagination using MySQL LIMIT, OFFSET

First off, don't have a separate server script for each page, that is just madness. Most applications implement pagination via use of a pagination parameter in the URL. Something like:

You can access the requested page number via $_GET['page'].

This makes your SQL formulation really easy:

// determine page number from $_GET
$page = 1;
if(!empty($_GET['page'])) {
    $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
    if(false === $page) {
        $page = 1;

// set the number of items to display per page
$items_per_page = 4;

// build query
$offset = ($page - 1) * $items_per_page;
$sql = "SELECT * FROM menuitem LIMIT " . $offset . "," . $items_per_page;

So for example if input here was page=2, with 4 rows per page, your query would be"

SELECT * FROM menuitem LIMIT 4,4

So that is the basic problem of pagination. Now, you have the added requirement that you want to understand the total number of pages (so that you can determine if "NEXT PAGE" should be shown or if you wanted to allow direct access to page X via a link).

In order to do this, you must understand the number of rows in the table.

You can simply do this with a DB call before trying to return your actual limited record set (I say BEFORE since you obviously want to validate that the requested page exists).

This is actually quite simple:

$sql = "SELECT your_primary_key_field FROM menuitem";
$result = mysqli_query($con, $sql);
if(false === $result) {
   throw new Exception('Query failed with: ' . mysqli_error());
} else {
   $row_count = mysqli_num_rows($result);
   // free the result set as you don't need it anymore

$page_count = 0;
if (0 === $row_count) {  
    // maybe show some error since there is nothing in your table
} else {
   // determine page_count
   $page_count = (int)ceil($row_count / $items_per_page);
   // double check that request page is in range
   if($page > $page_count) {
        // error to user, maybe set page to 1
        $page = 1;

// make your LIMIT query here as shown above

// later when outputting page, you can simply work with $page and $page_count to output links
// for example
for ($i = 1; $i <= $page_count; $i++) {
   if ($i === $page) { // this is current page
       echo 'Page ' . $i . '<br>';
   } else { // show link to other page   
       echo '<a href="/menuitem.php?page=' . $i . '">Page ' . $i . '</a><br>';

Laravel Eloquent limit and offset

Maybe this

$products = $art->products->take($limit)->skip($offset)->get();

LIMIT 10..20 in SQL Server

If you are using SQL Server 2012+ vote for Martin Smith's answer and use the OFFSET and FETCH NEXT extensions to ORDER BY,

If you are unfortunate enough to be stuck with an earlier version, you could do something like this,

              ROW_NUMBER() OVER (ORDER BY [dbo].[SomeColumn]) [Row]
            , *
    WHERE Row > 10

I believe is functionaly equivalent to


and the best performing way I know of doing it in TSQL, before MS SQL 2012.

If there are very many rows you may get better performance using a temp table instead of a CTE.

How to set a maximum execution time for a mysql query?

pt_kill has an option for such. But it is on-demand, not continually monitoring. It does what @Rafa suggested. However see --sentinel for a hint of how to come close with cron.

PHP: Limit foreach() statement?

You can either use



foreach() if ($tmp++ < 2) {

(the second solution is even worse)

How to fix the "508 Resource Limit is reached" error in WordPress?

I faced to this problem a lot when developing my company's website using WordPress. Finally I found that it happened because me and my colleague update the website at the same time as well as we installed and activated many plugins that we did not use them. The solution for me was we update the website in different time and deactivated and uninstalled those plugins.

What is the email subject length limit?

What's important is which mechanism you are using the send the email. Most modern libraries (i.e. System.Net.Mail) will hide the folding from you. You just put a very long email subject line in without (CR,LF,HTAB). If you start trying to do your own folding all bets are off. It will start reporting errors. So if you are having this issue just filter out the CR,LF,HTAB and let the library do the work for you. You can usually also set the encoding text type as a separate field. No need for iso encoding in the subject line.

MySQL - UPDATE query with LIMIT

You can do it with a LIMIT, just not with a LIMIT and an OFFSET.

Why does the 260 character path length limit exist in Windows?

Quoting this article

Maximum Path Length Limitation

In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is "D:\some 256-character path string<NUL>" where "<NUL>" represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.)

Now we see that it is 1+2+256+1 or [drive][:\][path][null] = 260. One could assume that 256 is a reasonable fixed string length from the DOS days. And going back to the DOS APIs we realize that the system tracked the current path per drive, and we have 26 (32 with symbols) maximum drives (and current directories).

The INT 0x21 AH=0x47 says “This function returns the path description without the drive letter and the initial backslash.” So we see that the system stores the CWD as a pair (drive, path) and you ask for the path by specifying the drive (1=A, 2=B, …), if you specify a 0 then it assumes the path for the drive returned by INT 0x21 AH=0x15 AL=0x19. So now we know why it is 260 and not 256, because those 4 bytes are not stored in the path string.

Why a 256 byte path string, because 640K is enough RAM.

MySQL LIMIT on DELETE statement

There is a workaround to solve this problem by using a derived table.

DELETE t1 FROM test t1 JOIN (SELECT FROM test LIMIT 1) t2 ON =

Because the LIMIT is inside the derived table the join will match only 1 row and thus the query will delete only this row.

How to increase Neo4j's maximum file open limit (ulimit) in Ubuntu?

Try run this command it will create a *_limits.conf file under /etc/security/limits.d

echo "* soft nofile 102400" > /etc/security/limits.d/*_limits.conf && echo "* hard nofile 102400" >> /etc/security/limits.d/*_limits.conf

Just exit from terminal and login again and verify by ulimit -n it will set for * users

Can HTTP POST be limitless?

There is no limit according to the HTTP protocol itself, but implementations will have a practical upper limit. I have sent data exceeding 4 GB using POST to Apache, but some servers did have a limit of 4 GB at the time.

Equivalent of LIMIT for DB2

Try this

    WHERE R BETWEEN 10000 AND 20000

Equivalent of LIMIT and OFFSET for SQL Server?

In SQL server you would use TOP together with ROW_NUMBER()

Google drive limit number of download

Sure Google has a limit of downloads so that you don't abuse the system. These are the limits if you are using Gmail:

The following limits apply for Google Apps for Business or Education editions. Limits for domains during trial are lower. These limits may change without notice in order to protect Google’s infrastructure.

Bandwidth limits

Limit                          Per hour            Per day
Download via web client        750 MB              1250 MB
Upload via web client          300 MB              500 MB
POP and IMAP bandwidth limits

Limit                Per day
Download via IMAP    2500 MB
Download via POP     1250 MB
Upload via IMAP      500 MB

check out this link

Maximum number of records in a MySQL database table

The greatest value of an integer has little to do with the maximum number of rows you can store in a table.

It's true that if you use an int or bigint as your primary key, you can only have as many rows as the number of unique values in the data type of your primary key, but you don't have to make your primary key an integer, you could make it a CHAR(100). You could also declare the primary key over more than one column.

There are other constraints on table size besides number of rows. For instance you could use an operating system that has a file size limitation. Or you could have a 300GB hard drive that can store only 300 million rows if each row is 1KB in size.

The limits of database size is really high:

The MyISAM storage engine supports 232 rows per table, but you can build MySQL with the --with-big-tables option to make it support up to 264 rows per table.

The InnoDB storage engine has an internal 6-byte row ID per table, so there are a maximum number of rows equal to 248 or 281,474,976,710,656.

An InnoDB tablespace also has a limit on table size of 64 terabytes. How many rows fits into this depends on the size of each row.

The 64TB limit assumes the default page size of 16KB. You can increase the page size, and therefore increase the tablespace up to 256TB. But I think you'd find other performance factors make this inadvisable long before you grow a table to that size.

How many files can I put in a directory?

I ran into a similar issue. I was trying to access a directory with over 10,000 files in it. It was taking too long to build the file list and run any type of commands on any of the files.

I thought up a little php script to do this for myself and tried to figure a way to prevent it from time out in the browser.

The following is the php script I wrote to resolve the issue.

Listing Files in a Directory with too many files for FTP

How it helps someone

How can I list (ls) the 5 last modified files in a directory?

Try using head or tail. If you want the 5 most-recently modified files:

ls -1t | head -5

The -1 (that's a one) says one file per line and the head says take the first 5 entries.

If you want the last 5 try

ls -1t | tail -5

Upload failed You need to use a different version code for your APK because you already have one with version code 2

Sometimes the PlayStore encounters a bug when you upload an APK during a Release creation, and you are stuck because you cannot upload the same APK again, for the current draft release. You get the error "Upload failed..."

The solution is to go to the Artifact library menu, under Release management and to delete the draft artifact. Once this is done, you will be able to upload the APK again, and to finish your release.

Hope it will help others...


Converting String to Cstring in C++

.c_str() returns a const char*. If you need a mutable version, you will need to produce a copy yourself.

How to execute the start script with Nodemon

First change your package.json file,

        "start": "node ./bin/www",
        "start-dev": "nodemon ./app.js"

After that, execute command

npm run start-dev

How can I send an HTTP POST request to a server from Excel using VBA?

You can use ServerXMLHTTP in a VBA project by adding a reference to MSXML.

  1. Open the VBA Editor (usually by editing a Macro)
  2. Go to the list of Available References
  3. Check Microsoft XML
  4. Click OK.

(from Referencing MSXML within VBA Projects)

The ServerXMLHTTP MSDN documentation has full details about all the properties and methods of ServerXMLHTTP.

In short though, it works basically like this:

  1. Call open method to connect to the remote server
  2. Call send to send the request.
  3. Read the response via responseXML, responseText, responseStream or responseBody

Select top 1 result using JPA

The easiest way is by using @Query with NativeQuery option like below:

@Query(value="SELECT 1 * FROM table ORDER BY anyField DESC LIMIT 1", nativeQuery = true)

Gradle sync failed: failed to find Build Tools revision 24.0.0 rc1

faced the same problem: Gradle sync failed: failed to find Build Tools revision x.x.x

reason: the build tools for that version was not down loaded properly solution:

  1. Click File > Settings (on a Mac, Android Studio > Preferences) to open the Settings dialog.
  2. Go to Appearance & Behavior > System Settings > Android SDK (Or simply search for Android SDK on the search bar)
  3. Go to SDK Tools tab > Check the Show Package Details checkbox
  4. uncheck the specific version to remove it.
  5. click apply.

then follow the steps 1 to 3 and 6.

  1. Select the specific version of the build tool and click on the Apply button After the installation, sync the project

In Bootstrap open Enlarge image in modal

    <div class="row" style="display:inline-block">

    <div class="col-lg-12">
        <h1 class="page-header">Thumbnail Gallery</h1>

            <div class="col-lg-3 col-md-4 col-xs-6 thumb">
            <a class="thumbnail" href="#" data-image-id="" data-toggle="modal" data-title="This is my title" data-caption="Some lovely red flowers" data-image="" data-target="#image-gallery">
                <img class="img-responsive" src="" alt="Short alt text">
            <div class="col-lg-3 col-md-4 col-xs-6 thumb">
            <a class="thumbnail" href="#" data-image-id="" data-toggle="modal" data-title="The car i dream about" data-caption="If you sponsor me, I can drive this car" data-image="" data-target="#image-gallery">
                <img class="img-responsive" src="" alt="A alt text">
            <div class="col-lg-3 col-md-4 col-xs-6 thumb">
            <a class="thumbnail" href="#" data-image-id="" data-toggle="modal" data-title="Im so nice" data-caption="And if there is money left, my girlfriend will receive this car" data-image="" data-target="#image-gallery">
                <img class="img-responsive" src="" alt="Another alt text">

<div class="modal fade" id="image-gallery" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title" id="image-gallery-title"></h4>
            <div class="modal-body">
                <img id="image-gallery-image" class="img-responsive" src="">
            <div class="modal-footer">

                <div class="col-md-2">
                    <button type="button" class="btn btn-primary" id="show-previous-image">Previous</button>

                <div class="col-md-8 text-justify" id="image-gallery-caption">
                    This text will be overwritten by jQuery

                <div class="col-md-2">
                    <button type="button" id="show-next-image" class="btn btn-default">Next</button>


    loadGallery(true, 'a.thumbnail');

    //This function disables buttons when needed
    function disableButtons(counter_max, counter_current){
        $('#show-previous-image, #show-next-image').show();
        if(counter_max == counter_current){
        } else if (counter_current == 1){

     * @param setIDs        Sets IDs when DOM is loaded. If using a PHP counter, set to false.
     * @param setClickAttr  Sets the attribute for the click handler.

    function loadGallery(setIDs, setClickAttr){
        var current_image,
            counter = 0;

        $('#show-next-image, #show-previous-image').click(function(){
            if($(this).attr('id') == 'show-previous-image'){
            } else {

            selector = $('[data-image-id="' + current_image + '"]');

        function updateGallery(selector) {
            var $sel = selector;
            current_image = $'image-id');
            $('#image-gallery-image').attr('src', $'image'));
            disableButtons(counter, $'image-id'));

        if(setIDs == true){

How does the SQL injection from the "Bobby Tables" XKCD comic work?

Say you naively wrote a student creation method like this:

void createStudent(String name) {
    database.execute("INSERT INTO students (name) VALUES ('" + name + "')");

And someone enters the name Robert'); DROP TABLE STUDENTS; --

What gets run on the database is this query:

INSERT INTO students (name) VALUES ('Robert'); DROP TABLE STUDENTS --')

The semicolon ends the insert command and starts another; the -- comments out the rest of the line. The DROP TABLE command is executed...

This is why bind parameters are a good thing.

Simple timeout in java

Nowadays you can use

try {
    String s = CompletableFuture.supplyAsync(() -> br.readLine())
                                .get(1, TimeUnit.SECONDS);
} catch (TimeoutException e) {
    System.out.println("Time out has occurred");
} catch (InterruptedException | ExecutionException e) {
    // Handle

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

There are two uses for RAISE_APPLICATION_ERROR. The first is to replace generic Oracle exception messages with our own, more meaningful messages. The second is to create exception conditions of our own, when Oracle would not throw them.

The following procedure illustrates both usages. It enforces a business rule that new employees cannot be hired in the future. It also overrides two Oracle exceptions. One is DUP_VAL_ON_INDEX, which is thrown by a unique key on EMP(ENAME). The other is a a user-defined exception thrown when the foreign key between EMP(MGR) and EMP(EMPNO) is violated (because a manager must be an existing employee).

create or replace procedure new_emp
    ( p_name in emp.ename%type
      , p_sal in emp.sal%type
      , p_job in emp.job%type
      , p_dept in emp.deptno%type
      , p_mgr in emp.mgr%type 
      , p_hired in emp.hiredate%type := sysdate )
    invalid_manager exception;
    PRAGMA EXCEPTION_INIT(invalid_manager, -2291);
    dummy varchar2(1);
    -- check hiredate is valid
    if trunc(p_hired) > trunc(sysdate) 
             , 'NEW_EMP::hiredate cannot be in the future'); 
    end if;

    insert into emp
        ( ename
          , sal
          , job
          , deptno
          , mgr 
          , hiredate )
        ( p_name
          , p_sal
          , p_job
          , p_dept
          , p_mgr 
          , trunc(p_hired) );
    when dup_val_on_index then
             , 'NEW_EMP::employee called '||p_name||' already exists'
             , true); 
    when invalid_manager then
             , 'NEW_EMP::'||p_mgr ||' is not a valid manager'); 


How it looks:

SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate+1)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate+1); END;

ERROR at line 1:
ORA-20000: NEW_EMP::hiredate cannot be in the future
ORA-06512: at "APC.NEW_EMP", line 16
ORA-06512: at line 1

SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 8888, sysdate)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 8888, sysdate); END;

ERROR at line 1:
ORA-20002: NEW_EMP::8888 is not a valid manager
ORA-06512: at "APC.NEW_EMP", line 42
ORA-06512: at line 1

SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate)

PL/SQL procedure successfully completed.

SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate); END;

ERROR at line 1:
ORA-20001: NEW_EMP::employee called DUGGAN already exists
ORA-06512: at "APC.NEW_EMP", line 37
ORA-00001: unique constraint (APC.EMP_UK) violated
ORA-06512: at line 1

Note the different output from the two calls to RAISE_APPLICATION_ERROR in the EXCEPTIONS block. Setting the optional third argument to TRUE means RAISE_APPLICATION_ERROR includes the triggering exception in the stack, which can be useful for diagnosis.

There is more useful information in the PL/SQL User's Guide.

How to add to the PYTHONPATH in Windows, so it finds my modules/packages?

Maybe a little late, but this is how you add the path to the Windows Environment Variables.

  1. Go to the Environment Variables tab, you do this by pressing Windows key + Pausa inter.

  2. Go to Advanced System Settings.

  3. Click on Environment Variables.

  4. On the lower window search for the 'Path' value.

  5. Select it

  6. Click on Edit

  7. In the end of the line add your instalation folder and the route to 'Scripts' folder.

  8. Click ok, aceptar etc.

You're done, enter cmd and write python from any location of your drive, it should enter the Python program.

Example with my pc (I have Python34)


Hope it helps.

Greetings from Bogotá

How to use filesaver.js

It works in my react project:

import FileSaver from 'file-saver';
// ...
onTestSaveFile() {
    var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
    FileSaver.saveAs(blob, "hello world.txt");

Difference between Return and Break statements

break is used to exit (escape) the for-loop, while-loop, switch-statement that you are currently executing.

return will exit the entire method you are currently executing (and possibly return a value to the caller, optional).

So to answer your question (as others have noted in comments and answers) you cannot use either break nor return to escape an if-else-statement per se. They are used to escape other scopes.

Consider the following example. The value of x inside the while-loop will determine if the code below the loop will be executed or not:

void f()
   int x = -1;
     if(x == 0)
        break;         // escape while() and jump to execute code after the the loop 
     else if(x == 1)
        return;        // will end the function f() immediately,
                       // no further code inside this method will be executed.

     do stuff and eventually set variable x to either 0 or 1

   code that will be executed on break (but not with return).

Null pointer Exception on .setOnClickListener

android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Because Submit button is inside login_modal so you need to use loginDialog view to access button:

Submit = (Button)loginDialog.findViewById(;

How to force a line break in a long word in a DIV?

Use word-wrap:break-word;

It even works in IE6, which is a pleasant surprise.

word-wrap: break-word has been replaced with overflow-wrap: break-word; which works in every modern browser. IE, being a dead browser, will forever rely on the deprecated and non-standard word-wrap instead.

Existing uses of word-wrap today still work as it is an alias for overflow-wrap per the specification.

Confused about Service vs Factory

For short and simple explanation refer

For detailed explanation refer

Also from angularJs documentation: enter image description here

Update Git branches from master

You have two options:

The first is a merge, but this creates an extra commit for the merge.

Checkout each branch:

git checkout b1

Then merge:

git merge origin/master

Then push:

git push origin b1

Alternatively, you can do a rebase:

git fetch
git rebase origin/master

CSS - center two images in css side by side

I've just done this for a project, and achieved it by using the h6 tag which I wasn't using for anything else:

in html code:

<h6><img alt="small drawing" src="../Images/image1.jpg" width="50%"/> <img alt="small drawing" src="../Images/image2.jpg" width="50%"/><br/>Optional caption text</h6>

The space between the image tags puts a vertical gap between the images. The width argument in each img tag is optional, but it neatly sizes the images to fill the width of the page. Notice that each image must be set to take up only 50% of the width. (Or 33% if you're using 3 images.) The width argument must come after the alt and src arguments or it won't work.

in css code:

/* h6: set presentation of images */
  font-family: "Franklin Gothic Demi", serif;
  font-size: 1.0em;
  font-weight: normal;
  line-height: 1.25em;
  text-align: center;

The text items set the look of the caption text, and the text-align property centers both the images and the caption text.

Download files from server php

Here is a simpler solution to list all files in a directory and to download it.

In your index.php file

$dir = "./";

$allFiles = scandir($dir);
$files = array_diff($allFiles, array('.', '..')); // To remove . and .. 

foreach($files as $file){
     echo "<a href='download.php?file=".$file."'>".$file."</a><br>";

The scandir() function list all files and directories inside the specified path. It works with both PHP 5 and PHP 7.

Now in the download.php

$filename = basename($_GET['file']);
// Specify file path.
$path = ''; // '/uplods/'
$download_file =  $path.$filename;

    // Check file is exists on given path.
      header('Content-Disposition: attachment; filename=' . $filename);  
      echo 'File does not exists on given path';

Python function pointer

I ran into a similar problem while creating a library to handle authentication. I want the app owner using my library to be able to register a callback with the library for checking authorization against LDAP groups the authenticated person is in. The configuration is getting passed in as a file that gets imported and contains a dict with all the config parameters.

I got this to work:

>>> class MyClass(object):
...     def target_func(self):
...         print "made it!"
...     def __init__(self,config):
...         self.config = config
...         self.config['funcname'] = getattr(self,self.config['funcname'])
...         self.config['funcname']()
>>> instance = MyClass({'funcname':'target_func'})
made it!

Is there a pythonic-er way to do this?

How do I break out of a loop in Scala?

Ironically the Scala break in scala.util.control.Breaks is an exception:

def break(): Nothing = { throw breakException }

The best advice is: DO NOT use break, continue and goto! IMO they are the same, bad practice and an evil source of all kind of problems (and hot discussions) and finally "considered be harmful". Code block structured, also in this example breaks are superfluous. Our Edsger W. Dijkstra† wrote:

The quality of programmers is a decreasing function of the density of go to statements in the programs they produce.

MySQL - UPDATE query based on SELECT Query

UPDATE [table_name] AS T1,
      (SELECT [column_name] 
        FROM [table_name] 
        WHERE [column_name] = [value]) AS T2 
  SET T1.[column_name]=T2.[column_name] + 1
WHERE T1.[column_name] = [value];

Monitor the Graphics card usage

If you develop in Visual Studio 2013 and 2015 versions, you can use their GPU Usage tool:

Screenshot from MSDN: enter image description here

Moreover, it seems you can diagnose any application with it, not only Visual Studio Projects:

In addition to Visual Studio projects you can also collect GPU usage data on any loose .exe applications that you have sitting around. Just open the executable as a solution in Visual Studio and then start up a diagnostics session and you can target it with GPU usage. This way if you are using some type of engine or alternative development environment you can still collect data on it as long as you end up with an executable.


How to sum up an array of integers in C#

In one of my apps I used :

public class ClassBlock
    public int[] p;
    public int Sum
        get { int s = 0;  Array.ForEach(p, delegate (int i) { s += i; }); return s; }

Deploying website: 500 - Internal server error

Sometimes, the reason might be one of your .dll assemblies is not registered correctly on the server.

For example, you can successfully run a C# Excel web application on your local machine with Office installed, while getting the 500 error on server deployment, because there is no Office suite installed on the server, and thus you get the server error.

How do I use installed packages in PyCharm?

For me, it was just a matter of marking the directory as a source root.

Transpose a matrix in Python

You can use zip with * to get transpose of a matrix:

>>> A = [[ 1, 2, 3],[ 4, 5, 6]]
>>> zip(*A)
[(1, 4), (2, 5), (3, 6)]
>>> lis  = [[1,2,3], 
... [4,5,6],
... [7,8,9]]
>>> zip(*lis)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

If you want the returned list to be a list of lists:

>>> [list(x) for x in zip(*lis)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
>>> map(list, zip(*lis))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Escaping single quotes in JavaScript string for JavaScript evaluation

strInputString = strInputString.replace(/'/g, "''");

How to add calendar events in Android?

you have to add flag:


or you will cause error with:

startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK

How to clear a textbox once a button is clicked in WPF?

When you run your form and you want showing text in textbox is clear so you put the code : -

textBox1.text = String.Empty;

Where textBox1 is your textbox name.

Why does modern Perl avoid UTF-8 by default?

We're all in agreement that it is a difficult problem for many reasons, but that's precisely the reason to try to make it easier on everybody.

There is a recent module on CPAN, utf8::all, that attempts to "turn on Unicode. All of it".

As has been pointed out, you can't magically make the entire system (outside programs, external web requests, etc.) use Unicode as well, but we can work together to make sensible tools that make doing common problems easier. That's the reason that we're programmers.

If utf8::all doesn't do something you think it should, let's improve it to make it better. Or let's make additional tools that together can suit people's varying needs as well as possible.


JavaScript: Upload file

Pure JS

You can use fetch optionally with await-try-catch

let photo = document.getElementById("image-file").files[0];
let formData = new FormData();
formData.append("photo", photo);
fetch('/upload/image', {method: "POST", body: formData});

async function SavePhoto(inp) 
    let user = { name:'john', age:34 };
    let formData = new FormData();
    let photo = inp.files[0];      
    formData.append("photo", photo);
    formData.append("user", JSON.stringify(user)); 
    const ctrl = new AbortController()    // timeout
    setTimeout(() => ctrl.abort(), 5000);
    try {
       let r = await fetch('/upload/image', 
         {method: "POST", body: formData, signal: ctrl.signal}); 
       console.log('HTTP response code:',r.status); 
    } catch(e) {
       console.log('Huston we have problem...:', e);
<input id="image-file" type="file" onchange="SavePhoto(this)" >
Before selecting the file open chrome console > network tab to see the request details.
<small>Because in this example we send request to the response code will be 404 ofcourse...</small>

(in stack overflow snippets there is problem with error handling, however in <a href="">jsfiddle version</a> for 404 errors 4xx/5xx are <a href="">not throwing</a> at all but we can read response status which contains code)

Old school approach - xhr

let photo = document.getElementById("image-file").files[0];  // file from input
let req = new XMLHttpRequest();
let formData = new FormData();

formData.append("photo", photo);                       "POST", '/upload/image');

function SavePhoto(e) 
    let user = { name:'john', age:34 };
    let xhr = new XMLHttpRequest();
    let formData = new FormData();
    let photo = e.files[0];      
    formData.append("user", JSON.stringify(user));   
    formData.append("photo", photo);
    xhr.onreadystatechange = state => { console.log(xhr.status); } // err handling
    xhr.timeout = 5000;"POST", '/upload/image'); 
<input id="image-file" type="file" onchange="SavePhoto(this)" >
Choose file and open chrome console > network tab to see the request details.
<small>Because in this example we send request to the response code will be 404 ofcourse...</small>

(the stack overflow snippets, has some problem with error handling - the xhr.status is zero (instead of 404) which is similar to situation when we run script from file on <a href="">local disc</a> - so I provide also js fiddle version which shows proper http error code <a href="">here</a>)


  • In server side you can read original file name (and other info) which is automatically included to request by browser in filename formData parameter.
  • You do NOT need to set request header Content-Type to multipart/form-data - this will be set automatically by browser.
  • Instead of /upload/image you can use full address like http://.../upload/image.
  • If you want to send many files in single request use multiple attribute: <input multiple type=... />, and attach all chosen files to formData in similar way (e.g. photo2=...files[2];... formData.append("photo2", photo2);)
  • You can include additional data (json) to request e.g. let user = {name:'john', age:34} in this way: formData.append("user", JSON.stringify(user));
  • You can set timeout: for fetch using AbortController, for old approach by xhr.timeout= milisec
  • This solutions should work on all major browsers.

Disable beep of Linux Bash on Windows 10

Uncommenting set bell-style none in /etc/inputrc and creating a .bash_profile with setterm -blength 0 didn't stop vim from beeping.

What worked for me was creating a .vimrc file in my home directory with set visualbell.


How to unnest a nested list

itertools provides the chain function for that:


def flatten(listOfLists):
    "Flatten one level of nesting"
    return chain.from_iterable(listOfLists)

Note that the result is an iterable, so you may need list(flatten(...)).

Android: Creating a Circular TextView?

Much of the Answer here seems to be hacks to the shape drawable, while android in itself supports this with the shapes functionality. This is something that worked perfectly for me.You can do this in two ways

Using a fixed height and width, that would stay the same regardless of the text that you put it as shown below

<shape xmlns:android=""

<solid android:color="@color/alpha_white" />

    <size android:width="25dp" android:height="25dp"/>

<stroke android:color="@color/color_primary" android:width="1dp"/>


Using Padding which re-adjusts the shape regardless of the text in the textview it as shown below

<solid android:color="@color/alpha_white" />

    android:top="@dimen/semi_standard_margin" />

<stroke android:color="@color/color_primary" android:width="2dp"/>

semi_standard_margin = 4dp

Why do Sublime Text 3 Themes not affect the sidebar?

Just install package Synced?Sidebar?Bg:it will change the sidebar theme based on current color scheme.But it seems that every time you change the color scheme,sidebar will be changed after you open file Preferences.sublime-settings

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

You could also create a custom model field type - see

In this case, you could 'inherit' from the built-in IntegerField and override its validation logic.

The more I think about this, I realize how useful this would be for many Django apps. Perhaps a IntegerRangeField type could be submitted as a patch for the Django devs to consider adding to trunk.

This is working for me:

from django.db import models

class IntegerRangeField(models.IntegerField):
    def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
        self.min_value, self.max_value = min_value, max_value
        models.IntegerField.__init__(self, verbose_name, name, **kwargs)
    def formfield(self, **kwargs):
        defaults = {'min_value': self.min_value, 'max_value':self.max_value}
        return super(IntegerRangeField, self).formfield(**defaults)

Then in your model class, you would use it like this (field being the module where you put the above code):

size = fields.IntegerRangeField(min_value=1, max_value=50)

OR for a range of negative and positive (like an oscillator range):

size = fields.IntegerRangeField(min_value=-100, max_value=100)

What would be really cool is if it could be called with the range operator like this:

size = fields.IntegerRangeField(range(1, 50))

But, that would require a lot more code since since you can specify a 'skip' parameter - range(1, 50, 2) - Interesting idea though...

Very Long If Statement in Python

According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators.

Further to this, if you're using a code style check such as pycodestyle, the next logical line needs to have different indentation to your code block.

For example:

if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
        here_is_another_long_identifier != and_finally_another_long_name):
    # ... your code here ...

How do you do a limit query in JPQL or HQL?

Criteria criteria=curdSession.createCriteria(DTOCLASS.class).addOrder(Order.desc("feild_name"));
                List<DTOCLASS> users = (List<DTOCLASS>) criteria.list();
for (DTOCLASS user : users) {

How to query values from xml nodes?

This works, been tested...

SELECT  n.c.value('OrganizationReportReferenceIdentifier[1]','varchar(128)') AS 'OrganizationReportReferenceNumber',  
        n.c.value('(OrganizationNumber)[1]','varchar(128)') AS 'OrganizationNumber'
FROM    Batches t
Cross   Apply RawXML.nodes('/GrobXmlFile/Grob/ReportHeader') n(c)  

How can I determine the status of a job?

Below script gets job status for every job on the server. It also tells how many steps are there and what is the currently running step and elasped time.

SELECT sj.Name,
        WHEN sja.start_execution_date IS NULL THEN 'Never ran'
        WHEN sja.start_execution_date IS NOT NULL AND sja.stop_execution_date IS NULL THEN 'Running'
        WHEN sja.start_execution_date IS NOT NULL AND sja.stop_execution_date IS NOT NULL THEN 'Not running'
    END AS 'RunStatus',
    CASE WHEN sja.start_execution_date IS NOT NULL AND sja.stop_execution_date IS NULL then js.StepCount else null end As TotalNumberOfSteps,
    CASE WHEN sja.start_execution_date IS NOT NULL AND sja.stop_execution_date IS NULL then ISNULL(sja.last_executed_step_id+1,js.StepCount) else null end as currentlyExecutingStep,
    CASE WHEN sja.start_execution_date IS NOT NULL AND sja.stop_execution_date IS NULL then datediff(minute, sja.run_requested_date, getdate()) ELSE NULL end as ElapsedTime
FROM msdb.dbo.sysjobs sj
JOIN msdb.dbo.sysjobactivity sja
ON sj.job_id = sja.job_id
CROSS APPLY (SELECT COUNT(*) FROM msdb.dbo.sysjobsteps as js WHERE js.job_id = sj.job_id) as js(StepCount)
WHERE session_id = (
    SELECT MAX(session_id) FROM msdb.dbo.sysjobactivity)
ORDER BY RunStatus desc

How to parse freeform street/postal address out of text, and into components

There are many street address parsers. They come in two basic flavors - ones that have databases of place names and street names, and ones that don't.

A regular expression street address parser can get up to about a 95% success rate without much trouble. Then you start hitting the unusual cases. The Perl one in CPAN, "Geo::StreetAddress::US", is about that good. There are Python and Javascript ports of that, all open source. I have an improved version in Python which moves the success rate up slightly by handling more cases. To get the last 3% right, though, you need databases to help with disambiguation.

A database with 3-digit ZIP codes and US state names and abbreviations is a big help. When a parser sees a consistent postal code and state name, it can start to lock on to the format. This works very well for the US and UK.

Proper street address parsing starts from the end and works backwards. That's how the USPS systems do it. Addresses are least ambiguous at the end, where country names, city names, and postal codes are relatively easy to recognize. Street names can usually be isolated. Locations on streets are the most complex to parse; there you encounter things such as "Fifth Floor" and "Staples Pavillion". That's when a database is a big help.

CSS Float: Floating an image to the left of the text

Solution using display: flex (with responsive behavior):


<div class="content">
    <img src="myimage.jpg" alt="" />
    <div class="details">
        <p>Lorem ipsum dolor sit amet...</p>


    display: flex;
    align-items: flex-start;
    justify-content: flex-start;
.content img {
    width: 150px;
.details {
    width: calc(100% - 150px);
@media only screen and (max-width: 480px) {
    .content {
        flex-direction: column;
    .details {
        width: 100%;

What are good examples of genetic algorithms/genetic programming solutions?

Not homework.

My first job as a professional programmer (1995) was writing a genetic-algorithm based automated trading system for S&P500 futures. The application was written in Visual Basic 3 [!] and I have no idea how I did anything back then, since VB3 didn't even have classes.

The application started with a population of randomly-generated fixed-length strings (the "gene" part), each of which corresponded to a specific shape in the minute-by-minute price data of the S&P500 futures, as well as a specific order (buy or sell) and stop-loss and stop-profit amounts. Each string (or "gene") had its profit performance evaluated by a run through 3 years of historical data; whenever the specified "shape" matched the historical data, I assumed the corresponding buy or sell order and evaluated the trade's result. I added the caveat that each gene started with a fixed amount of money and could thus potentially go broke and be removed from the gene pool entirely.

After each evaluation of a population, the survivors were cross-bred randomly (by just mixing bits from two parents), with the likelihood of a gene being selected as a parent being proportional to the profit it produced. I also added the possibility of point mutations to spice things up a bit. After a few hundred generations of this, I ended up with a population of genes that could turn $5000 into an average of about $10000 with no chance of death/brokeness (on the historical data, of course).

Unfortunately, I never got the chance to use this system live, since my boss lost close to $100,000 in less than 3 months trading the traditional way, and he lost his willingness to continue with the project. In retrospect, I think the system would have made huge profits - not because I was necessarily doing anything right, but because the population of genes that I produced happened to be biased towards buy orders (as opposed to sell orders) by about a 5:1 ratio. And as we know with our 20/20 hindsight, the market went up a bit after 1995.

Retrieving values from nested JSON Object

Try this, you can parse nested JSON

public static String getJsonValue(String jsonReq, String key) {
        JSONObject json = new JSONObject(jsonReq);
        boolean exists = json.has(key);
        Iterator<?> keys;
        String nextKeys;
        String val = "";
        if (!exists) {
            keys = json.keys();
            while (keys.hasNext()) {
                nextKeys = (String);
                try {
                    if (json.get(nextKeys) instanceof JSONObject) {
                        return getJsonValue(json.getJSONObject(nextKeys).toString(), key);
                    } else if (json.get(nextKeys) instanceof JSONArray) {
                        JSONArray jsonArray = json.getJSONArray(nextKeys);
                        int i = 0;
                        if (i < jsonArray.length()) do {
                            String jsonArrayString = jsonArray.get(i).toString();
                            JSONObject innerJson = new JSONObject(jsonArrayString);
                            return getJsonValue(innerJson.toString(),key);
                        } while (i < jsonArray.length());
                } catch (Exception e) {
        } else {
            val = json.get(key).toString();
        return val;

invalid use of incomplete type

You need to use a pointer or a reference as the proper type is not known at this time the compiler can not instantiate it.

Instead try:

void action(const typename Subclass::mytype &var) {

Does Ruby have a string.startswith("abc") built in method?

It's called String#start_with?, not String#startswith: In Ruby, the names of boolean-ish methods end with ? and the words in method names are separated with an _. Not sure where the s went, personally, I'd prefer String#starts_with? over the actual String#start_with?

Angular 2 - View not updating after model changes

It might be that the code in your service somehow breaks out of Angular's zone. This breaks change detection. This should work:

import {Component, OnInit, NgZone} from 'angular2/core';

export class RecentDetectionComponent implements OnInit {

    recentDetections: Array<RecentDetection>;

    constructor(private zone:NgZone, // <== added
        private recentDetectionService: RecentDetectionService) {
        this.recentDetections = new Array<RecentDetection>();

    getRecentDetections(): void {
            .subscribe(recent => { 
        => { // <== added
                     this.recentDetections = recent;

    ngOnInit() {
        let timer = Observable.timer(2000, 5000);
        timer.subscribe(() => this.getRecentDetections());

For other ways to invoke change detection see Triggering change detection manually in Angular

Alternative ways to invoke change detection are


to immediately run change detection for the current component and its children


to include the current component the next time Angular runs change detection


to run change detection for the whole application

error LNK2005, already defined?

The linker tells you that you have the variable k defined multiple times. Indeed, you have a definition in A.cpp and another in B.cpp. Both compilation units produce a corresponding object file that the linker uses to create your program. The problem is that in your case the linker does not know whic definition of k to use. In C++ you can have only one defintion of the same construct (variable, type, function).

To fix it, you will have to decide what your goal is

  • If you want to have two variables, both named k, you can use an anonymous namespace in both .cpp files, then refer to k as you are doing now:


namespace {
  int k;
  • You can rename one of the ks to something else, thus avoiding the duplicate defintion.
  • If you want to have only once definition of k and use that in both .cpp files, you need to declare in one as extern int k;, and leave it as it is in the other. This will tell the linker to use the one definition (the unchanged version) in both cases -- extern implies that the variable is defined in another compilation unit.

Getting the source of a specific image element with jQuery

var src = $('img.conversation_img[alt="example"]').attr('src');

If you have multiple matching elements only the src of the first one will be returned.

How to convert JTextField to String and String to JTextField?

// to string
String text = textField.getText();

// to JTextField

You can also create a new text field: new JTextField(text)

Note that this is not conversion. You have two objects, where one has a property of the type of the other one, and you just set/get it.

Reference: javadocs of JTextField

How to float a div over Google Maps?

Try this:

   #wrapper { position: relative; }
   #over_map { position: absolute; top: 10px; left: 10px; z-index: 99; }

<div id="wrapper">
   <div id="google_map">


   <div id="over_map">


Run local java applet in browser (chrome/firefox) "Your security settings have blocked a local application from running"

  1. Make a jar file from your applet class and META-INF/MANIFEST.MF file.
  2. Sign your jar file with your certificate.
  3. Configure your local site permissions as > file:///C:/ or http: //localhost:8080
  4. Then run your html document on Intenet Explorer on Windows.(Not Google Chrome !)

How to add property to a class dynamically?

I suppose I should expand this answer, now that I'm older and wiser and know what's going on. Better late than never.

You can add a property to a class dynamically. But that's the catch: you have to add it to the class.

>>> class Foo(object):
...     pass
>>> foo = Foo()
>>> foo.a = 3
>>> Foo.b = property(lambda self: self.a + 1)
>>> foo.b

A property is actually a simple implementation of a thing called a descriptor. It's an object that provides custom handling for a given attribute, on a given class. Kinda like a way to factor a huge if tree out of __getattribute__.

When I ask for foo.b in the example above, Python sees that the b defined on the class implements the descriptor protocol—which just means it's an object with a __get__, __set__, or __delete__ method. The descriptor claims responsibility for handling that attribute, so Python calls Foo.b.__get__(foo, Foo), and the return value is passed back to you as the value of the attribute. In the case of property, each of these methods just calls the fget, fset, or fdel you passed to the property constructor.

Descriptors are really Python's way of exposing the plumbing of its entire OO implementation. In fact, there's another type of descriptor even more common than property.

>>> class Foo(object):
...     def bar(self):
...         pass
>>> Foo().bar
<bound method of <__main__.Foo object at 0x7f2a439d5dd0>>
>>> Foo().bar.__get__
<method-wrapper '__get__' of instancemethod object at 0x7f2a43a8a5a0>

The humble method is just another kind of descriptor. Its __get__ tacks on the calling instance as the first argument; in effect, it does this:

def __get__(self, instance, owner):
    return functools.partial(self.function, instance)

Anyway, I suspect this is why descriptors only work on classes: they're a formalization of the stuff that powers classes in the first place. They're even the exception to the rule: you can obviously assign descriptors to a class, and classes are themselves instances of type! In fact, trying to read still calls property.__get__; it's just idiomatic for descriptors to return themselves when accessed as class attributes.

I think it's pretty cool that virtually all of Python's OO system can be expressed in Python. :)

Oh, and I wrote a wordy blog post about descriptors a while back if you're interested.

Find number of decimal places in decimal value regardless of culture

Relying on the internal representation of decimals is not cool.

How about this:

    int CountDecimalDigits(decimal n)
        return n.ToString(System.Globalization.CultureInfo.InvariantCulture)
                //.TrimEnd('0') uncomment if you don't want to count trailing zeroes
                .SkipWhile(c => c != '.')

Loop and get key/value pair for JSON array using jQuery

The following should work for a JSON returned string. It will also work for an associative array of data.

for (var key in data)
     alert(key + ' is ' + data[key]);

best practice to generate random token for forgot password

The earlier version of the accepted answer (md5(uniqid(mt_rand(), true))) is insecure and only offers about 2^60 possible outputs -- well within the range of a brute force search in about a week's time for a low-budget attacker:

Since a 56-bit DES key can be brute-forced in about 24 hours, and an average case would have about 59 bits of entropy, we can calculate 2^59 / 2^56 = about 8 days. Depending on how this token verification is implemented, it might be possible to practically leak timing information and infer the first N bytes of a valid reset token.

Since the question is about "best practices" and opens with...

I want to generate identifier for forgot password

...we can infer that this token has implicit security requirements. And when you add security requirements to a random number generator, the best practice is to always use a cryptographically secure pseudorandom number generator (abbreviated CSPRNG).

Using a CSPRNG

In PHP 7, you can use bin2hex(random_bytes($n)) (where $n is an integer larger than 15).

In PHP 5, you can use random_compat to expose the same API.

Alternatively, bin2hex(mcrypt_create_iv($n, MCRYPT_DEV_URANDOM)) if you have ext/mcrypt installed. Another good one-liner is bin2hex(openssl_random_pseudo_bytes($n)).

Separating the Lookup from the Validator

Pulling from my previous work on secure "remember me" cookies in PHP, the only effective way to mitigate the aforementioned timing leak (typically introduced by the database query) is to separate the lookup from the validation.

If your table looks like this (MySQL)...

CREATE TABLE account_recovery (
    token CHAR(64),
    expires DATETIME,

... you need to add one more column, selector, like so:

CREATE TABLE account_recovery (
    selector CHAR(16),
    token CHAR(64),
    expires DATETIME,
    PRIMARY KEY(id),

Use a CSPRNG When a password reset token is issued, send both values to the user, store the selector and a SHA-256 hash of the random token in the database. Use the selector to grab the hash and User ID, calculate the SHA-256 hash of the token the user provides with the one stored in the database using hash_equals().

Example Code

Generating a reset token in PHP 7 (or 5.6 with random_compat) with PDO:

$selector = bin2hex(random_bytes(8));
$token = random_bytes(32);

$urlToEmail = ''.http_build_query([
    'selector' => $selector,
    'validator' => bin2hex($token)

$expires = new DateTime('NOW');
$expires->add(new DateInterval('PT01H')); // 1 hour

$stmt = $pdo->prepare("INSERT INTO account_recovery (userid, selector, token, expires) VALUES (:userid, :selector, :token, :expires);");
    'userid' => $userId, // define this elsewhere!
    'selector' => $selector,
    'token' => hash('sha256', $token),
    'expires' => $expires->format('Y-m-d\TH:i:s')

Verifying the user-provided reset token:

$stmt = $pdo->prepare("SELECT * FROM account_recovery WHERE selector = ? AND expires >= NOW()");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!empty($results)) {
    $calc = hash('sha256', hex2bin($validator));
    if (hash_equals($calc, $results[0]['token'])) {
        // The reset token is valid. Authenticate the user.
    // Remove the token from the DB regardless of success or failure.

These code snippets are not complete solutions (I eschewed the input validation and framework integrations), but they should serve as an example of what to do.

Failed binder transaction when putting an bitmap dynamically in a widget

I have solved this issue by storing images on internal storage and then using .setImageURI() rather than .setBitmap().

What is the difference between max-device-width and max-width for mobile web?

Don't use device-width/height anymore.

device-width, device-height and device-aspect-ratio are deprecated in Media Queries Level 4:

Just use width/height (without min/max) in combination with orientation & (min/max-)resolution to target specific devices. On mobile width/height should be the same as device-width/height.

Copy Paste Values only( xlPasteValues )

You may use this too

Sub CopyPaste()

col = 1
Do Until Sheet2.Cells(1, col) = ""
    col = col + 1

Sheet2.Cells(1, col).PasteSpecial xlPasteValues
End Sub

What is a Memory Heap?

A memory heap is a location in memory where memory may be allocated at random access.
Unlike the stack where memory is allocated and released in a very defined order, individual data elements allocated on the heap are typically released in ways which is asynchronous from one another. Any such data element is freed when the program explicitly releases the corresponding pointer, and this may result in a fragmented heap. In opposition only data at the top (or the bottom, depending on the way the stack works) may be released, resulting in data element being freed in the reverse order they were allocated. cannot identify image file - Python?

Seems like a Permissions Issue. I was facing the same error. But when I ran it from the root account, it worked. So either give the read permission to the file using chmod (in linux) or run your script after logging in as a root user.

How do you use global variables or constant values in Ruby?

Variable scope in Ruby is controlled by sigils to some degree. Variables starting with $ are global, variables with @ are instance variables, @@ means class variables, and names starting with a capital letter are constants. All other variables are locals. When you open a class or method, that's a new scope, and locals available in the previous scope aren't available.

I generally prefer to avoid creating global variables. There are two techniques that generally achieve the same purpose that I consider cleaner:

  1. Create a constant in a module. So in this case, you would put all the classes that need the offset in the module Foo and create a constant Offset, so then all the classes could access Foo::Offset.

  2. Define a method to access the value. You can define the method globally, but again, I think it's better to encapsulate it in a module or class. This way the data is available where you need it and you can even alter it if you need to, but the structure of your program and the ownership of the data will be clearer. This is more in line with OO design principles.

extract part of a string using bash/cut/split

What about sed? That will work in a single command:

sed 's#.*/\([^:]*\).*#\1#' <<<$string
  • The # are being used for regex dividers instead of / since the string has / in it.
  • .*/ grabs the string up to the last backslash.
  • \( .. \) marks a capture group. This is \([^:]*\).
    • The [^:] says any character _except a colon, and the * means zero or more.
  • .* means the rest of the line.
  • \1 means substitute what was found in the first (and only) capture group. This is the name.

Here's the breakdown matching the string with the regular expression:

        /var/cpanel/users/           joebloggs joebloggs
sed 's#.*/                          \([^:]*\)   .*              #\1       #'

"for line in..." results in UnicodeDecodeError: 'utf-8' codec can't decode byte

As suggested by Mark Ransom, I found the right encoding for that problem. The encoding was "ISO-8859-1", so replacing open("u.item", encoding="utf-8") with open('u.item', encoding = "ISO-8859-1") will solve the problem.

How to check if an app is installed from a web-page on an iPhone?

The date solution is much better than others, I had to increment the time on 50 like that this is a Tweeter example:

//on click or your event handler..
var twMessage = "Your Message to share";
var now = new Date().valueOf();
setTimeout(function () {
   if (new Date().valueOf() - now > 100) return;
   var twitterUrl = ""+twMessage;, '_blank');
}, 50);
window.location = "twitter://post?message="+twMessage;

the only problem on Mobile IOS Safari is when you don't have the app installed on device, and so Safari show an alert that autodismiss when the new url is opened, anyway is a good solution for now!

Browse and display files in a git repo without cloning

if you know the remote branch you want to check, you can find out the latest via:

git ls-tree -r <remote_branch> --name-only

Get form data in ReactJS

If you are using Redux in your project you can consider using this higher order component

NSAttributedString add text alignment

In swift 4:

    let paraStyle = NSMutableParagraphStyle.init()
    paraStyle.alignment = .left

    let str = "Test Message"
    let attribute = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 12)]

    let attrMessage = NSMutableAttributedString(string: str, attributes: attribute)

    attrMessage.addAttribute(kCTParagraphStyleAttributeName as NSAttributedStringKey, value: paraStyle, range: NSMakeRange(0, str.count))

Sorting arraylist in alphabetical order (case insensitive)

Unfortunately, all answers so far do not take into account that "a" must not be considered equal to "A" when it comes to sorting.

String[] array = {"b", "A", "C", "B", "a"};

// Approach 1
// array is [A, B, C, a, b]

// Approach 2
Arrays.sort(array, String.CASE_INSENSITIVE_ORDER);
// array is [A, a, b, B, C]

// Approach 3
Arrays.sort(array, java.text.Collator.getInstance());
// array is [a, A, b, B, C]

In approach 1 any lower case letters are considered greater than any upper case letters.

Approach 2 makes it worse, since CASE_INSENSITIVE_ORDER considers "a" and "A" equal (comparation result is 0). This makes sorting non-deterministic.

Approach 3 (using a java.text.Collator) is IMHO the only way of doing it correctly, since it considers "a"and "A" not equal, but puts them in the correct order according to the current (or any other desired) Locale.

Delete all objects in a list

If the goal is to delete the objects a and b themselves (which appears to be the case), forming the list [a, b] is not helpful. Instead, one should keep a list of strings used as the names of those objects. These allow one to delete the objects in a loop, by accessing the globals() dictionary.

c = ['a', 'b']
# create and work with a and b    
for i in c:
    del globals()[i]

Regex to get the words after matching string

But I need the match result to be ... not in a match group...

For what you are trying to do, this should work. \K resets the starting point of the match.

\bObject Name:\s+\K\S+

You can do the same for getting your Security ID matches.

\bSecurity ID:\s+\K\S+

Is there a simple way to convert C++ enum to string?

I do this with separate side-by-side enum wrapper classes which are generated with macros. There are several advantages:

  • Can generate them for enums I don't define (eg: OS platform header enums)
  • Can incorporate range checking into the wrapper class
  • Can do "smarter" formatting with bit field enums

The downside, of course, is that I need to duplicate the enum values in the formatter classes, and I don't have any script to generate them. Other than that, though, it seems to work pretty well.

Here's an example of an enum from my codebase, sans all the framework code which implements the macros and templates, but you can get the idea:

enum EHelpLocation
    HELP_LOCAL_FILE         = 1, 
    HELP_HTML_ONLINE        = 2, 
class CEnumFormatter_EHelpLocation : public CEnumDefaultFormatter< EHelpLocation >
    static inline CString FormatEnum( EHelpLocation eValue )
        switch ( eValue )
            return FormatAsNumber( eValue );
typedef ESmartEnum< EHelpLocation, HELP_LOCATION_UNKNOWN, CEnumFormatter_EHelpLocation, CRangeInfo_EHelpLocation > SEHelpLocation;

The idea then is instead of using EHelpLocation, you use SEHelpLocation; everything works the same, but you get range checking and a 'Format()' method on the enum variable itself. If you need to format a stand-alone value, you can use CEnumFormatter_EHelpLocation::FormatEnum(...).

Hope this is helpful. I realize this also doesn't address the original question about a script to actually generate the other class, but I hope the structure helps someone trying to solve the same problem, or write such a script.

Is it possible to start activity through adb shell?

For example this will start XBMC:

adb shell am start -a android.intent.action.MAIN -n org.xbmc.xbmc/

(More general answers are already posted, but I missed a nice example here.)

Spring 3 RequestMapping: Get path value

Just found that issue corresponding to my problem. Using HandlerMapping constants I was able to wrote a small utility for that purpose:

 * Extract path from a controller mapping. /controllerUrl/** => return matched **
 * @param request incoming request.
 * @return extracted path
public static String extractPathFromPattern(final HttpServletRequest request){

    String path = (String) request.getAttribute(
    String bestMatchPattern = (String ) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);

    AntPathMatcher apm = new AntPathMatcher();
    String finalPath = apm.extractPathWithinPattern(bestMatchPattern, path);

    return finalPath;


What is useState() in React?

The syntax of useState hook is straightforward.

const [value, setValue] = useState(defaultValue)

If you are not familiar with this syntax, go here.

I would recommend you reading the documentation.There are excellent explanations with decent amount of examples.

import { useState } from 'react';_x000D_
function Example() {_x000D_
    // Declare a new state variable, which we'll call "count"_x000D_
    const [count, setCount] = useState(0);_x000D_
  // its up to you how you do it_x000D_
  const buttonClickHandler = e => {_x000D_
   // increment_x000D_
   // setCount(count + 1)_x000D_
   // decrement_x000D_
   // setCount(count -1)_x000D_
   // anything_x000D_
   // setCount(0)_x000D_
  return (_x000D_
          <p>You clicked {count} times</p>_x000D_
         <button onClick={buttonClickHandler}>_x000D_
             Click me_x000D_

Make A List Item Clickable (HTML/CSS)

Ditch the <a href="...">. Put the onclick (all lowercase) handler on the <li> tag itself.

Encrypt and decrypt a password in Java

I recently used Spring Security 3.0 for this (combined with Wicket btw), and am quite happy with it. Here's a good thorough tutorial and documentation. Also take a look at this tutorial which gives a good explanation of the hashing/salting/decoding setup for Spring Security 2.

How do I test for an empty JavaScript object?

In addition to Thevs answer:

var o = {};
alert($.toJSON(o)=='{}'); // true

var o = {a:1};
alert($.toJSON(o)=='{}'); // false

it's jquery + jquery.json

Unknown URL content://downloads/my_downloads

For those who are getting Error Unknown URI: content://downloads/public_downloads. I managed to solve this by getting a hint given by @Commonsware in this answer. I found out the class FileUtils on GitHub. Here InputStream methods are used to fetch file from Download directory.

 // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);

                if (id != null && id.startsWith("raw:")) {
                    return id.substring(4);

                String[] contentUriPrefixesToTry = new String[]{

                for (String contentUriPrefix : contentUriPrefixesToTry) {
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
                    try {
                        String path = getDataColumn(context, contentUri, null, null);
                        if (path != null) {
                            return path;
                    } catch (Exception e) {}

                // path could not be retrieved using ContentResolver, therefore copy file to accessible cache using streams
                String fileName = getFileName(context, uri);
                File cacheDir = getDocumentCacheDir(context);
                File file = generateFileName(fileName, cacheDir);
                String destinationPath = null;
                if (file != null) {
                    destinationPath = file.getAbsolutePath();
                    saveFileFromUri(context, uri, destinationPath);

                return destinationPath;

How to store a datetime in MySQL with timezone info

MySQL stores DATETIME without timezone information. Let's say you store '2019-01-01 20:00:00' into a DATETIME field, when you retrieve that value you're expected to know what timezone it belongs to.

So in your case, when you store a value into a DATETIME field, make sure it is Tanzania time. Then when you get it out, it will be Tanzania time. Yay!

Now, the hairy question is: When I do an INSERT/UPDATE, how do I make sure the value is Tanzania time? Two cases:

  1. You do INSERT INTO table (dateCreated) VALUES (CURRENT_TIMESTAMP or NOW()).

  2. You do INSERT INTO table (dateCreated) VALUES (?), and specify the current time from your application code.


MySQL will take the current time, let's say that is '2019-01-01 20:00:00' Tanzania time. Then MySQL will convert it to UTC, which comes out to '2019-01-01 17:00:00', and store that value into the field.

So how do you get the Tanzania time, which is '20:00:00', to store into the field? It's not possible. Your code will need to expect UTC time when reading from this field.


It depends on what type of value you pass as ?. If you pass the string '2019-01-01 20:00:00', then good for you, that's exactly what will be stored to the DB. If you pass a Date object of some kind, then it'll depend on how the db driver interprets that Date object, and ultimate what 'YYYY-MM-DD HH:mm:ss' string it provides to MySQL for storage. The db driver's documentation should tell you.

How do I use StringUtils in Java?

The mostly used StringUtils class is the Apache Commons Lang StringUtils (org.apache.commons.lang3.StringUtils). To use this class you first have to download the Apache Commons Lang3 package then you have to add it to your project libraries.

You can go to this link to get more details:

How can I determine installed SQL Server instances and their versions?

Here is a simple method: go to Start then Programs then Microsoft SQL Server 2005 then Configuration Tools then SQL Server Configuration Manager then SQL Server 2005 Network Configuration then Here you can locate all the instance installed onto your machine. Validation of viewstate MAC failed


  1. Search the web for "MachineKey generator"

  2. Go to one of the sites found and generate the Machine Key, that will look like... (the numbers are bigger)
    validationKey="0EF6C03C11FC...63EAE6A00F0B6B35DD4B" decryptionKey="2F5E2FD80991C629...3ACA674CD3B5F068" validation="SHA1" decryption="AES" />

  3. Copy and paste into the <system.web> section in the web.config file.

If you want to follow the path I did...
Resolving view state message authentication code (MAC) errors Resolution 3b: Use an explicit <machineKey>
By adding an explicit <machineKey> element to the application's Web.config file, the developer tells ASP.NET not to use the auto-generated cryptographic key. See Appendix A for instructions on how to generate a <machineKey> element.
Easiest way to generate MachineKey - Ahmet Mithat Bostanci - 31 Jul 2012 You can search in Bing for "MachineKey generator" and use an online service. Honestly...

How to save DataFrame directly to Hive?

For Hive external tables I use this function in PySpark:

def save_table(sparkSession, dataframe, database, table_name, save_format="PARQUET"):
    print("Saving result in {}.{}".format(database, table_name))
    output_schema = "," \
        .join(["{} {}".format(, x.dataType) for x in list(dataframe.schema)]) \
        .replace("StringType", "STRING") \
        .replace("IntegerType", "INT") \
        .replace("DateType", "DATE") \
        .replace("LongType", "INT") \
        .replace("TimestampType", "INT") \
        .replace("BooleanType", "BOOLEAN") \
        .replace("FloatType", "FLOAT")\
    output_schema = re.sub(r'DecimalType[(][0-9]+,[0-9]+[)]', 'FLOAT', output_schema)

    sparkSession.sql("DROP TABLE IF EXISTS {}.{}".format(database, table_name))

    query = "CREATE EXTERNAL TABLE IF NOT EXISTS {}.{} ({}) STORED AS {} LOCATION '/user/hive/{}/{}'" \
        .format(database, table_name, output_schema, save_format, database, table_name)
    dataframe.write.insertInto('{}.{}'.format(database, table_name),overwrite = True)

Could not open a connection to your authentication agent

For bash built into Windows 10, I added this to .bash_profile:

if [ -z $SSH_AUTH_SOCK ]; then
    if [ -r ~/.ssh/env ]; then
            source ~/.ssh/env
            if [ `ps -p $SSH_AGENT_PID | wc -l` = 1 ]; then
                    rm ~/.ssh/env
                    unset SSH_AUTH_SOCK

if [ -z $SSH_AUTH_SOCK ]; then
    ssh-agent -s | sed 's/^echo/#echo/'> ~/.ssh/env
    chmod 600 ~/.ssh/env
    source ~/.ssh/env > /dev/null 2>&1

Show empty string when date field is 1/1/1900

Try this code

(case when CONVERT(VARCHAR(10), CreatedDate, 103) = '01/01/1900' then '' else CONVERT(VARCHAR(24), CreatedDate, 121) end) as Date_Resolved

Getting the Username from the HKEY_USERS values

Done it, by a bit of creative programming,

  1. Enum the Keys in HKEY_USERS for those funny number keys...

  2. Enum the keys in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\

and you will find the same numbers.... Now in those keys look at the String value: ProfileImagePath = "SomeValue" where the values are either:

"%systemroot%\system32\config\systemprofile"... not interested in this one... as its not a directory path...

%SystemDrive%\Documents and Settings\LocalService - "Local Services" %SystemDrive%\Documents and Settings\NetworkService "NETWORK SERVICE"


%SystemDrive%\Documents and Settings\USER_NAME, which translates directly to the "USERNAME" values in most un-tampered systems, ie. where the user has not changed the their user name after a few weeks or altered the paths explicitly...

Get the current language in device

If you want to check a current language, use the answer of @Sarpe (@Thorbear):

val language = ConfigurationCompat.getLocales(Resources.getSystem().configuration)?.get(0)?.language
// Check here the language.
val format = if (language == "ru") "d MMMM yyyy ?." else "d MMMM yyyy"
val longDateFormat = SimpleDateFormat(format, Locale.getDefault())

Send JavaScript variable to PHP variable

PHP runs on the server and Javascript runs on the client, so you can't set a PHP variable to equal a Javascript variable without sending the value to the server. You can, however, set a Javascript variable to equal a PHP variable:

<script type="text/javascript">
  var foo = '<?php echo $foo ?>';

To send a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible):

var variableToSend = 'foo';
$.post('file.php', {variable: variableToSend});

On your server, you would need to receive the variable sent in the post:

$variable = $_POST['variable'];

Maximum and minimum values in a textbox

Yes it can! You might consider first to set the value of maxlength to 3 and then write an event handler for the keyup-event.

The function can evaluate the user input using regex or parseInt to validate the user input and set it to any desired value, if the input is incorrect.

Build Eclipse Java Project from Command Line

To complete André's answer, an ant solution could be like the one described in Emacs, JDEE, Ant, and the Eclipse Java Compiler, as in:

           line="-warn:+unused -Xemacs"/>
        <classpath refid="compile.classpath" />

The compilerarg element also allows you to pass in additional command line args to the eclipse compiler.

You can find a full ant script example here which would be invoked in a command line with:

java -cp C:/eclipse-SDK-3.4-win32/eclipse/plugins/org.eclipse.equinox.launcher_1.0.100.v20080509-1800.jar org.eclipse.core.launcher.Main -data "C:\Documents and Settings\Administrator\workspace" -application org.eclipse.ant.core.antRunner -buildfile build.xml -verbose

BUT all that involves ant, which is not what Keith is after.

For a batch compilation, please refer to Compiling Java code, especially the section "Using the batch compiler"

The batch compiler class is located in the JDT Core plug-in. The name of the class is org.eclipse.jdt.compiler.batch.BatchCompiler. It is packaged into plugins/org.eclipse.jdt.core_3.4.0..jar. Since 3.2, it is also available as a separate download. The name of the file is ecj.jar.
Since 3.3, this jar also contains the support for jsr199 (Compiler API) and the support for jsr269 (Annotation processing). In order to use the annotations processing support, a 1.6 VM is required.

Running the batch compiler From the command line would give

java -jar org.eclipse.jdt.core_3.4.0<qualifier>.jar -classpath rt.jar


java -jar ecj.jar -classpath rt.jar

All java compilation options are detailed in that section as well.

The difference with the Visual Studio command line compilation feature is that Eclipse does not seem to directly read its .project and .classpath in a command-line argument. You have to report all information contained in the .project and .classpath in various command-line options in order to achieve the very same compilation result.

So, then short answer is: "yes, Eclipse kind of does." ;)

How to install SQL Server Management Studio 2008 component only

The accepted answer was correct up until July 2011. To get the latest version, including the Service Pack you should find the latest version as described here:

For example, if you check the SP2 CTP and SP1, you'll find the latest version of SQL Server Management Studio under SP1:

Download the 32-bit (x86) or 64-bit (x64) version of the SQLManagementStudio*.exe files as appropriate and install it. You can find out whether your system is 32-bit or 64-bit by right clicking Computer, selecting Properties and looking at the System Type.

Although you could apply the service pack to the base version that results from following the accepted answer, it's easier to just download the latest version of SQL Server Management Studio and simply install it in one step.

make div's height expand with its content

You can use CSS Grid Layout. Support is rather wide at the moment: check it on caniuse.

Here is the example on jsfiddle. Also example with tons of text stuff.

HTML code:

<div class="container">
  <div class="header">
  <div class="content">
  <div class="footer">

CSS Code:

html, body {
  width: 100%;
  height: 100%;
  margin: 0;

.container {
  width: 100%;
  height: 100%;

  display: grid;
  grid-template-rows: 100px auto 150px;
  grid-template-columns: auto;
// style stuff

Understanding Apache's access log

I also don't under stand what the "-" means after the 200 140 section of the log

That value corresponds to the referer as described by Joachim. If you see a dash though, that means that there was no referer value to begin with (eg. the user went straight to a specific destination, like if he/she typed a URL in their browser)


To solve this:

All you need to do is to install Python certificates! A common issue on macOS.

Open these files:

Install Certificates.command
Update Shell Profile.command

Simply Run these two scripts and you wont have this issue any more.

Hope this helps!

Windows 7 - 'make' is not recognized as an internal or external command, operable program or batch file

I am using windows 8. I had the same problem. I added the path "C:\MinGW\bin" to system environment variable named 'path' then it worked. May be, you can try the same. Hope it'll help!

"query function not defined for Select2 undefined error"

use :

try {
catch(err) {


gitx How do I get my 'Detached HEAD' commits back into master

If checkout master was the last thing you did, then the reflog entry HEAD@{1} will contain your commits (otherwise use git reflog or git log -p to find them). Use git merge HEAD@{1} to fast forward them into master.


As noted in the comments, Git Ready has a great article on this.

git reflog and git reflog --all will give you the commit hashes of the mis-placed commits.

Git Ready: Reflog, Your Safety Net


How do I print a double value with full precision using cout?

Most portably...

#include <limits>

using std::numeric_limits;

    cout.precision(numeric_limits<double>::digits10 + 1);
    cout << d;

What is size_t in C?

size_t is an unsigned type. So, it cannot represent any negative values(<0). You use it when you are counting something, and are sure that it cannot be negative. For example, strlen() returns a size_t because the length of a string has to be at least 0.

In your example, if your loop index is going to be always greater than 0, it might make sense to use size_t, or any other unsigned data type.

When you use a size_t object, you have to make sure that in all the contexts it is used, including arithmetic, you want non-negative values. For example, let's say you have:

size_t s1 = strlen(str1);
size_t s2 = strlen(str2);

and you want to find the difference of the lengths of str2 and str1. You cannot do:

int diff = s2 - s1; /* bad */

This is because the value assigned to diff is always going to be a positive number, even when s2 < s1, because the calculation is done with unsigned types. In this case, depending upon what your use case is, you might be better off using int (or long long) for s1 and s2.

There are some functions in C/POSIX that could/should use size_t, but don't because of historical reasons. For example, the second parameter to fgets should ideally be size_t, but is int.

java IO Exception: Stream Closed

Don't call write.close() in writeToFile().

How do I copy the contents of one stream to another?

Since none of the answers have covered an asynchronous way of copying from one stream to another, here is a pattern that I've successfully used in a port forwarding application to copy data from one network stream to another. It lacks exception handling to emphasize the pattern.

const int BUFFER_SIZE = 4096;

static byte[] bufferForRead = new byte[BUFFER_SIZE];
static byte[] bufferForWrite = new byte[BUFFER_SIZE];

static Stream sourceStream = new MemoryStream();
static Stream destinationStream = new MemoryStream();

static void Main(string[] args)
    // Initial read from source stream
    sourceStream.BeginRead(bufferForRead, 0, BUFFER_SIZE, BeginReadCallback, null);

private static void BeginReadCallback(IAsyncResult asyncRes)
    // Finish reading from source stream
    int bytesRead = sourceStream.EndRead(asyncRes);
    // Make a copy of the buffer as we'll start another read immediately
    Array.Copy(bufferForRead, 0, bufferForWrite, 0, bytesRead);
    // Write copied buffer to destination stream
    destinationStream.BeginWrite(bufferForWrite, 0, bytesRead, BeginWriteCallback, null);
    // Start the next read (looks like async recursion I guess)
    sourceStream.BeginRead(bufferForRead, 0, BUFFER_SIZE, BeginReadCallback, null);

private static void BeginWriteCallback(IAsyncResult asyncRes)
    // Finish writing to destination stream

Algorithm: efficient way to remove duplicate integers from an array

An array should obviously be "traversed" right-to-left to avoid unneccessary copying of values back and forth.

If you have unlimited memory, you can allocate a bit array for sizeof(type-of-element-in-array) / 8 bytes to have each bit signify whether you've already encountered corresponding value or not.

If you don't, I can't think of anything better than traversing an array and comparing each value with values that follow it and then if duplicate is found, remove these values altogether. This is somewhere near O(n^2) (or O((n^2-n)/2)).

IBM has an article on kinda close subject.

What is the purpose of XSD files?

The xsd file is the schema of the xml file - it defines which elements may occur and their restrictions (like amount, order, boundaries, relationships,...)

Change Volley timeout duration

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

Something like this:

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

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

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

Converting milliseconds to minutes and seconds with Javascript

There is probably a better way to do this, but it gets the job done:

var ms = 298999;
var min = ms / 1000 / 60;
var r = min % 1;
var sec = Math.floor(r * 60);
if (sec < 10) {
    sec = '0'+sec;
min = Math.floor(min);

Not sure why you have the << operator in your minutes line, I don't think it's needed just floor the minutes before you display.

Getting the remainder of the minutes with % gives you the percentage of seconds elapsed in that minute, so multiplying it by 60 gives you the amount of seconds and flooring it makes it more fit for display although you could also get sub-second precision if you want.

If seconds are less than 10 you want to display them with a leading zero.

Create a CSV File for a user in PHP

The thread is a little old, I know, but for future reference and for noobs as myself:

Everyone else here explain how to create the CSV, but miss a basic part of the question: how to link. In order to link to download of the CSV-file, you just link to the .php-file, which in turn responds as being a .csv-file. The PHP headers do that. This enables cool stuff, like adding variables to the querystring and customize the output:

<a href="my_csv_creator.php?user=23&amp;othervariable=true">Get CSV</a>

my_csv_creator.php can work with the variables given in the querystring and for example use different or customized database queries, change the columns of the CSV, personalize the filename and so on, e.g.:


Tracking changes in Windows registry

A straightforward way to do this with no extra tools is to export the registry to a text file before the install, then export it to another file after. Then, compare the two files.

Having said that, the Sysinternals tools are great for this.

Windows command to convert Unix line endings?

Building on TampaHaze's and MD XF's helpful answers.

This will change all .txt files in place in the current directory from from LF to CRLF in Command Prompt

for /f %f in ('dir /b "*.txt"') do ( type %f | more /p > %f.1 & move %f.1 %f )

If you don't want to verify every single change



move /y

To include subdirectories change

dir /b


dir /b /s

To do all this in a batch file including subdirectories without prompting use below

@echo off
setlocal enabledelayedexpansion

for /f %%f in ('dir /s /b "*.txt"') do (
    type %%f | more /p > %%f.1 
    move /y %%f.1 %%f > nul
    @echo Changing LF-^>CRLF in File %%f

Python Flask, how to set content type

from flask import Flask, render_template, make_response
app = Flask(__name__)

def user_xml():
    resp = make_response(render_template('xml/user.html', username='Ryan'))
    resp.headers['Content-type'] = 'text/xml; charset=utf-8'
    return resp

To the power of in C?

just use pow(a,b),which is exactly 3**4 in python

What is a faster alternative to Python's http.server (or SimpleHTTPServer)?

Also consider devd a small webserver written in go. Binaries for many platforms are available here.

devd -ol path/to/files/to/serve

It's small, fast, and provides some interesting optional features like live-reloading when your files change.

How can I indent multiple lines in Xcode?

The keyboard shortcuts are ?+] for indent and ?+[ for un-indent.

  • In Xcode's preferences window, click the Key Bindings toolbar button. The Key Bindings section is where you customize keyboard shortcuts.

How to change screen resolution of Raspberry Pi

TV Sony Bravia KLV-32T550A Below mention config works greatly You should add the following into the /boot/config.txt to force the output to HDMI and set the

resolution 82   1920x1080   60Hz    1080p


Unique random string generation

I don't think that they really are random, but my guess is those are some hashes.

Whenever I need some random identifier, I usually use a GUID and convert it to its "naked" representation:


How to do something before on submit?

make sure the submit button is not of type "submit", make it a button. Then use the onclick event to trigger some javascript. There you can do whatever you want before you actually post your data.

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

ObservableRangeCollection should pass a test like

public void TestAddRangeWhileBoundToListCollectionView()
    int collectionChangedEventsCounter = 0;
    int propertyChangedEventsCounter = 0;
    var collection = new ObservableRangeCollection<object>();

    collection.CollectionChanged += (sender, e) => { collectionChangedEventsCounter++; };
    (collection as INotifyPropertyChanged).PropertyChanged += (sender, e) => { propertyChangedEventsCounter++; };

    var list = new ListCollectionView(collection);

    collection.AddRange(new[] { new object(), new object(), new object(), new object() });

    Assert.AreEqual(4, collection.Count);
    Assert.AreEqual(1, collectionChangedEventsCounter);
    Assert.AreEqual(2, propertyChangedEventsCounter);

otherwise we get

System.NotSupportedException : Range actions are not supported.

while using with a control.

I do not see an ideal solution, but NotifyCollectionChangedAction.Reset instead of Add/Remove partially solve the problem. See as was mentioned by net_prog

count number of rows in a data frame in R based on group

Using the example data set that Ananda dummied up, here's an example using aggregate(), which is part of core R. aggregate() just needs something to count as function of the different values of MONTH-YEAR. In this case, I used VALUE as the thing to count:

aggregate(cbind(count = VALUE) ~ MONTH.YEAR, 
          data = mydf, 
          FUN = function(x){NROW(x)})

which gives you..

  MONTH.YEAR count
1  FEB. 2012     2
2  JAN. 2012     2
3  MAR. 2012     1

Search a string in a file and delete it from this file by Shell Script

This should do it:

sed -e s/deletethis//g -i *
sed -e "s/deletethis//g" -i.backup *
sed -e "s/deletethis//g" -i .backup *

it will replace all occurrences of "deletethis" with "" (nothing) in all files (*), editing them in place.

In the second form the pattern can be edited a little safer, and it makes backups of any modified files, by suffixing them with ".backup".

The third form is the way some versions of sed like it. (e.g. Mac OS X)

man sed for more information.

How can I download a file from a URL and save it in Rails?

Try this:

require 'open-uri'
open('image.png', 'wb') do |file|
  file << open('').read

Apache Proxy: No protocol handler was valid

This can happen if you don't have mod_proxy_http enabled

sudo a2enmod proxy_http

For me to get my https based load balancer working, i had to enable the following:

sudo a2enmod ssl
sudo a2enmod proxy
sudo a2enmod proxy_balancer
sudo a2enmod proxy_http

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

  • The JPQL Query is not valid.
  • You have not created an association between your entities that the underlying JPQL query can utilize.

When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

public class User {

    private Long idUser;

    private String userName;

    private Area area;

    public Long getIdUser() {
        return idUser;

    public void setIdUser(Long idUser) {
        this.idUser = idUser;

    public String getUserName() {
        return userName;

    public void setUserName(String userName) {
        this.userName = userName;

    public Area getArea() {
        return area;

    public void setArea(Area area) {
        this.area = area;

Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

@Table(name = "area")
public class Area {

    private Long idArea;

    private String areaName;

    @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
    private User user;

    public Long getIdArea() {
        return idArea;

    public void setIdArea(Long idArea) {
        this.idArea = idArea;

    public String getAreaName() {
        return areaName;

    public void setAreaName(String areaName) {
        this.areaName = areaName;

    public User getUser() {
        return user;

    public void setUser(User user) {
        this.user = user;

Sum of two input value by jquery

if in multiple class you want to change additional operation in perticular class that show in below example

var like= $(this).text();
$(this).text(+like + +1);

python: how to get information about a function?

You can use pydoc.

Open your terminal and type python -m pydoc list.append

The advantage of pydoc over help() is that you do not have to import a module to look at its help text. For instance python -m pydoc random.randint.

Also you can start an HTTP server to interactively browse documentation by typing python -m pydoc -b (python 3)

For more information python -m pydoc

Numpy AttributeError: 'float' object has no attribute 'exp'

You convert type, T) to float32 like this:

z=np.array(, T),dtype=np.float32)

def sigmoid(X, T):
    return (1.0 / (1.0 + np.exp(-z)))

Hopefully it will finally work!

Rails: Adding an index after adding column

You can run another migration, just for the index:

class AddIndexToTable < ActiveRecord::Migration
  def change
    add_index :table, :user_id

Gunicorn worker timeout error

On Google Cloud Just add --timeout 90 to entrypoint in app.yaml

entrypoint: gunicorn -b :$PORT main:app --timeout 90

What is the string concatenation operator in Oracle?

It is ||, for example:

select 'Mr ' || ename from emp;

The only "interesting" feature I can think of is that 'x' || null returns 'x', not null as you might perhaps expect.

How do I specify C:\Program Files without a space in it for programs that can't handle spaces in file paths?

You can just create a folder ProgramFiles at local D or local C to install those apps that can be install to a folder name which has a SPACES / Characters on it.

Get environment value in controller

All of the variables listed in .env file will be loaded into the $_ENV PHP super-global when your application receives a request. Check out the Laravel configuration page.


jQuery send HTML data through POST

I don't see why you shouldn't be able to send html content via a post.

if you encounter any issues, you could perhaps use some kind of encoding / decoding - but I don't see that you will.

Issue with background color in JavaFX 8

Try this one in your css document,

-fx-background-color : #ffaadd;


-fx-base : #ffaadd; 

Also, you can set background color on your object with this code directly.

yourPane.setBackground(new Background(new BackgroundFill(Color.DARKGREEN, CornerRadii.EMPTY, Insets.EMPTY)));

Eclipse: Enable autocomplete / content assist

For anyone having this problem with newer versions of Eclipse, head over to Window->Preferences->Java->Editor->Content assist->Advanced and mark Java Proposals and Chain Template Proposals as active.

TypeError : Unhashable type

The real reason because set does not work is the fact, that it uses the hash function to distinguish different values. This means that sets only allows hashable objects. Why a list is not hashable is already pointed out.

Setting transparent images background in IrfanView

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

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

To change the viewing color in Irfanview go to:

Options > Properties/Settings > Viewing > Main window color

Append to string variable

var str1 = "add";
str1 = str1 + " ";

Hope that helps,


What are the differences between struct and class in C++?

Here is a good explanation:

So, one more time: in C++, a struct is identical to a class except that the members of a struct have public visibility by default, but the members of a class have private visibility by default.

Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?

You should use Java's built in serialization mechanism. To use it, you need to do the following:

  1. Declare the Club class as implementing Serializable:

    public class Club implements Serializable {

    This tells the JVM that the class can be serialized to a stream. You don't have to implement any method, since this is a marker interface.

  2. To write your list to a file do the following:

    FileOutputStream fos = new FileOutputStream("t.tmp");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
  3. To read the list from a file, do the following:

    FileInputStream fis = new FileInputStream("t.tmp");
    ObjectInputStream ois = new ObjectInputStream(fis);
    List<Club> clubs = (List<Club>) ois.readObject();

Using app.config in .Net Core

  1. You can use Microsoft.Extensions.Configuration API with any .NET Core app, not only with ASP.NET Core app. Look into sample provided in the link, that shows how to read configs in the console app.

  2. In most cases, the JSON source (read as .json file) is the most suitable config source.

    Note: don't be confused when someone says that config file should be appsettings.json. You can use any file name, that is suitable for you and file location may be different - there are no specific rules.

    But, as the real world is complicated, there are a lot of different configuration providers:

    • File formats (INI, JSON, and XML)
    • Command-line arguments
    • Environment variables

    and so on. You even could use/write a custom provider.

  3. Actually, app.config configuration file was an XML file. So you can read settings from it using XML configuration provider (source on github, nuget link). But keep in mind, it will be used only as a configuration source - any logic how your app behaves should be implemented by you. Configuration Provider will not change 'settings' and set policies for your apps, but only read data from the file.

Set select option 'selected', by value

$('#graphtype option[value=""]').prop("selected", true);

This works well where #graphtype is the id of the select tag.

example select tag:

 <select name="site" id="site" class="form-control" onchange="getgraph1(this.options[this.selectedIndex].value);">
    <option value="" selected>Site</option> 
    <option value="sitea">SiteA</option>
    <option value="siteb">SiteB</option>

Convert UTC/GMT time to local time

Don't forget if you already have a DateTime object and are not sure if it's UTC or Local, it's easy enough to use the methods on the object directly:

DateTime convertedDate = DateTime.Parse(date);
DateTime localDate = convertedDate.ToLocalTime();

How do we adjust for the extra hour?

Unless specified .net will use the local pc settings. I'd have a read of:

By the looks the code might look something like:

DaylightTime daylight = TimeZone.CurrentTimeZone.GetDaylightChanges( year );

And as mentioned above double check what timezone setting your server is on. There are articles on the net for how to safely affect the changes in IIS.

Batchfile to create backup and rename with timestamp

Yes, to make it run in the background create a shortcut to the batch file and go into the properties. I'm on a Linux machine ATM but I believe the option you are wanting is in the advanced tab.

You can also run your batch script through a vbs script like this:

CreateObject("Wscript.Shell").Run "your_batch_file.bat", 0, True

This will execute your batch file with no cmd window shown.

Get user profile picture by Id

To get largest size of the image{userID}?fields=picture.width(720).height(720) 

or anything else you need as size. Based on experience, type=large is not the largest result you can obtain.

Show Error on the tip of the Edit Text Android

I got the solution of my problem Hope this will help others also.I have used onTextChnaged it invokes When an object of a type is attached to an Editable, its methods will be called when the text is changed.

public class MainActivity extends Activity {
    TextView emailId;
    ImageView continuebooking;
    EditText firstName;
    protected void onCreate(Bundle savedInstanceState) {
        emailId = (TextView)findViewById(;
        continuebooking = (ImageView)findViewById(;
        firstName= (EditText)findViewById(;
        emailId.setText("[email protected]");
        continuebooking.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {

                    firstName.setError("Enter FirstName");

        firstName.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence s, int start, int before, int count) {


            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // TODO Auto-generated method stub


            public void afterTextChanged(Editable s) {


Get current user id in ASP.NET Identity 2.0

I had the same issue. I am currently using Core 2.2. I solved this problem with the following piece of code.

using Microsoft.AspNetCore.Identity;
var user = await _userManager.FindByEmailAsync(User.Identity.Name);

I hope this will be useful to someone.

jQuery UI themes and HTML tables

There are a bunch of resources out there:

Plugins with ThemeRoller support:


UPDATE: Here is something I put together that will style the table:

<script type="text/javascript">

    (function ($) {
        $.fn.styleTable = function (options) {
            var defaults = {
                css: 'styleTable'
            options = $.extend(defaults, options);

            return this.each(function () {

                input = $(this);

                input.find("tr").live('mouseover mouseout', function (event) {
                    if (event.type == 'mouseover') {
                    } else {


                input.find("tr").each(function () {

    $(document).ready(function () {


<table id="Table1" class="full">

The CSS:

.styleTable { border-collapse: separate; }
.styleTable TD { font-weight: normal !important; padding: .4em; border-top-width: 0px !important; }
.styleTable TH { text-align: center; padding: .8em .4em; }
.styleTable TD.first, .styleTable TH.first { border-left-width: 0px !important; }

How to fix Error: laravel.log could not be opened?

You could do:

chcon -R -t httpd_sys_rw_content_t storage

Java get last element of a collection

If you have Iterable convert to stream and find last element

 Iterator<String> sourceIterator = Arrays.asList("one", "two", "three").iterator();

 Iterable<String> iterable = () -> sourceIterator;

 String last =, false).reduce((first, second) -> second).orElse(null);

Repository access denied. access via a deployment key is read-only

TLDR: ssh-add ~/.ssh/yourkey

I've just worked through this problem.

And none of the other answers helped.

I did have a ./ssh/config with all the right stuff, also an earlier repository working fine (same bitbucket account, same key). Then I generated a deploy_key, and after that created a new repository.

After that could not clone the new repo.

I wish I knew how/why ssh agent was messing this up, but adding the key solved it. I mean adding the key in my local Ubuntu, not in bitbucket admin. The command is just

    ~/.ssh$ ssh-add myregualrkey

Hope this helps someone.

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {


Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

    A: "a",
    B: "b",
    C: "c"

You can get all the keys (["A", "B", "C"]) like this:


And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():


Makefiles with source files in different directories

The VPATH option might come in handy, which tells make what directories to look in for source code. You'd still need a -I option for each include path, though. An example:

CXXFLAGS=-Ipart1/inc -Ipart2/inc -Ipart3/inc

OutputExecutable: part1api.o part2api.o part3api.o

This will automatically find the matching partXapi.cpp files in any of the VPATH specified directories and compile them. However, this is more useful when your src directory is broken into subdirectories. For what you describe, as others have said, you are probably better off with a makefile for each part, especially if each part can stand alone.

How to set the environmental variable LD_LIBRARY_PATH in linux

The file .bash_profile is only executed by login shells. You may need to put it in ~/.bashrc, or simply logout and login again.

Option to ignore case with .contains method?

private boolean containsIgnoreCase(List<String> list, String soughtFor) {
    for (String current : list) {
        if (current.equalsIgnoreCase(soughtFor)) {
            return true;
    return false;

Add Foreign Key relationship between two Databases

In my experience, the best way to handle this when the primary authoritative source of information for two tables which are related has to be in two separate databases is to sync a copy of the table from the primary location to the secondary location (using T-SQL or SSIS with appropriate error checking - you cannot truncate and repopulate a table while it has a foreign key reference, so there are a few ways to skin the cat on the table updating).

Then add a traditional FK relationship in the second location to the table which is effectively a read-only copy.

You can use a trigger or scheduled job in the primary location to keep the copy updated.

CORS Access-Control-Allow-Headers wildcard being ignored?

I found that Access-Control-Allow-Headers: * should be set ONLY for OPTIONS request. If you return it for POST request then browser cancel the request (at least for chrome)

The following PHP code works for me

// Allow CORS
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');    
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); 
// Access-Control headers are received during OPTIONS requests
    header("Access-Control-Allow-Headers: *");

I found similar questions with some misleading response:

  • Server thread says that this is 2 years bug of chrome: Access-Control-Allow-Headers does not match with localhost. It's wrong: I can use CORS to my local server with Post normally
  • Access-Control-Allow-Headers does accept wildcards. It's also wrong, wildcard works for me (I tested only with Chrome)

This take me half day to figure out the issue.

Happy coding

Windows command prompt log to a file

In cmd when you use > or >> the output will be only written on the file. Is it possible to see the output in the cmd windows and also save it in a file. Something similar if you use teraterm, when you can start saving all the log in a file meanwhile you use the console and view it (only for ssh, telnet and serial).

Disabling same-origin policy in Safari

Later versions of Safari allow you to Disable Cross-Origin Restrictions. Just enable the developer menu from Preferences >> Advanced, and select "Disable Cross-Origin Restrictions" from the develop menu.

If you want local only, then you only need to enable the developer menu, and select "Disable local file restrictions" from the develop menu.

Google Maps Api v3 - find nearest markers

You can use the computeDistanceBetween() method in the google.maps.geometry.spherical namespace.

In React Native, how do I put a view on top of another view, with part of it lying outside the bounds of the view behind?

add the following to the "floating" view

position: 'absolute'

you may also need to add a top and left value for positioning

see this example:

Add a CSS class to <%= f.submit %>

Rails 4 and Bootstrap 3 "primary" button

<%= f.submit nil, :class => 'btn btn-primary' %>

Yields something like:


Custom checkbox image android

Copy the btn_check.xml from android-sdk/platforms/android-#/data/res/drawable to your project's drawable folder and change the 'on' and 'off' image states to your custom images.

Then your xml will just need android:button="@drawable/btn_check"

    android:checked="true" />

If you want to use different default android icons, you can use android:button="@android:drawable/..."

How can one create an overlay in css?

         background-position:top center;


What is the difference between RTP or RTSP in a streaming server?

Some basics:

RTSP server can be used for dead source as well as for live source. RTSP protocols provides you commands (Like your VCR Remote), and functionality depends upon your implementation.

RTP is real time protocol used for transporting audio and video in real time. Transport used can be unicast, multicast or broadcast, depending upon transport address and port. Besides transporting RTP does lots of things for you like packetization, reordering, jitter control, QoS, support for Lip sync.....

In your case if you want broadcasting streaming server then you need both RTSP (for control) as well as RTP (broadcasting audio and video)

To start with you can go through sample code provided by live555

How to export non-exportable private key from store

You might need to uninstall antivirus (in my case I had to get rid of Avast).

This makes sure that crypto::cng command will work. Otherwise it was giving me errors:

mimikatz $ crypto::cng
ERROR kull_m_patch_genericProcessOrServiceFromBuild ; OpenProcess (0x00000005)

After removing Avast:

mimikatz $ crypto::cng
"KeyIso" service patched

Magic. (:


Windows Defender is another program blocking the program to work, so you will need also to disable it for the time of using program at least.

How to add an object to an ArrayList in Java

change Date to Object which is between parenthesis

How to get the latest record in each group using GROUP BY?

You should find out last timestamp values in each group (subquery), and then join this subquery to the table -

SELECT t1.* FROM messages t1
  JOIN (SELECT from_id, MAX(timestamp) timestamp FROM messages GROUP BY from_id) t2
    ON t1.from_id = t2.from_id AND t1.timestamp = t2.timestamp;

Chrome desktop notification example

See also ServiceWorkerRegistration.showNotification

It appears that window.webkitNotifications has already been deprecated and removed. However, there's a new API, and it appears to work in the latest version of Firefox as well.

function notifyMe() {
  // Let's check if the browser supports notifications
  if (!("Notification" in window)) {
    alert("This browser does not support desktop notification");

  // Let's check if the user is okay to get some notification
  else if (Notification.permission === "granted") {
    // If it's okay let's create a notification
    var notification = new Notification("Hi there!");

  // Otherwise, we need to ask the user for permission
  // Note, Chrome does not implement the permission static property
  // So we have to check for NOT 'denied' instead of 'default'
  else if (Notification.permission !== 'denied') {
    Notification.requestPermission(function (permission) {

      // Whatever the user answers, we make sure we store the information
      if(!('permission' in Notification)) {
        Notification.permission = permission;

      // If the user is okay, let's create a notification
      if (permission === "granted") {
        var notification = new Notification("Hi there!");
  } else {
    alert(`Permission is ${Notification.permission}`);


Apply style to only first level of td tags

I think, It will work.

.Myclass tr td:first-child{ }


.Myclass td:first-child { }

Implementing multiple interfaces with Java - is there a way to delegate?

As said, there's no way. However, a bit decent IDE can autogenerate delegate methods. For example Eclipse can do. First setup a template:

public class MultipleInterfaces implements InterFaceOne, InterFaceTwo {
    private InterFaceOne if1;
    private InterFaceTwo if2;

then rightclick, choose Source > Generate Delegate Methods and tick the both if1 and if2 fields and click OK.

See also the following screens:

alt text

alt text

alt text

C# Linq Where Date Between 2 Dates

var appointmentNoShow = from a in appointments
                        from p in properties
                        from c in clients
                        where a.Id == p.OID
                        where a.Start.Date >= startDate.Date
                        where a.Start.Date <= endDate.Date

How to start Fragment from an Activity

You Can Start Activity and attach RecipientsFragment on it , but you cant start Fragment

Set formula to a range of cells

Use FormulaR1C1:

Cells((1,3),(10,3)).FormulaR1C1 = "=RC[-2]+RC[-1]"

Unlike Formula, FormulaR1C1 has relative referencing.

mysql delete under safe mode

I have a far more simple solution, it is working for me; it is also a workaround but might be usable and you dont have to change your settings. I assume you can use value that will never be there, then you use it on your WHERE clause

DELETE FROM MyTable WHERE MyField IS_NOT_EQUAL AnyValueNoItemOnMyFieldWillEverHave

I don't like that solution either too much, that's why I am here, but it works and it seems better than what it has been answered

What is the difference between “int” and “uint” / “long” and “ulong”?

u means unsigned, so ulong is a large number without sign. You can store a bigger value in ulong than long, but no negative numbers allowed.

A long value is stored in 64-bit,with its first digit to show if it's a positive/negative number. while ulong is also 64-bit, with all 64 bit to store the number. so the maximum of ulong is 2(64)-1, while long is 2(63)-1.

TypeError: $(...).DataTable is not a function

if some reason two versions of jQuery are loaded (which is not recommended), calling $.noConflict(true) from the second version will return the globally scoped jQuery variables to those of the first version.

Sometimes it could be issue with older version (or not stable) of JQuery files

Solution use $.noConflict();

<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery.dataTables.js" type="text/javascript"></script>
jQuery( document ).ready(function( $ ) {
// Code that uses other library's $ can follow here.

Can you find all classes in a package using reflection?

I couldn't find a short working snipped for something so simple. So here it is, I made it myself after screwing around for a while:

    Reflections reflections =
        new Reflections(new ConfigurationBuilder()
                .filterInputsBy(new FilterBuilder().includePackage(packagePath))
                .setScanners(new SubTypesScanner(false)));

    Set<String> typeList = reflections.getAllTypes(); 

How to find files recursively by file type and copy them to a directory while in ssh?

Something like this should work.

ssh [email protected] 'find -type f -name "*.pdf" -exec cp {} ./pdfsfolder \;'

addClass - can add multiple classes on same div?

$('.page-address-edit').addClass('test1 test2 test3');

Ref- jQuery

The program can't start because cygwin1.dll is missing... in Eclipse CDT

This error message means that Windows isn't able to find "cygwin1.dll". The Programs that the Cygwin gcc create depend on this DLL. The file is part of cygwin , so most likely it's located in C:\cygwin\bin. To fix the problem all you have to do is add C:\cygwin\bin (or the location where cygwin1.dll can be found) to your system path. Alternatively you can copy cygwin1.dll into your Windows directory.

There is a nice tool called DependencyWalker that you can download from . You can use it to check dependencies of executables, so if you inspect your generated program it tells you which dependencies are missing and which are resolved.

How to create a connection string in c#

Demo :

<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />

Based on your question:

    <add name="itmall" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True" />

Refer links:

Retrive connection string from web.config file:

write the below code in your file where you want;

string connstring=ConfigurationManager.ConnectionStrings["itmall"].ConnectionString;

SqlConnection con = new SqlConnection(connstring);

or you can go in your way like

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["itmall"].ConnectionString);


The "name" which you gave in web.config file and name which you used in connection string must be same(like "itmall" in this solution.)

Remove all the children DOM elements in div

while(node.firstChild) {

Using fonts with Rails asset pipeline

If you have a file called scaffolds.css.scss, then there's a chance that's overriding all the custom things you're doing in the other files. I commented out that file and suddenly everything worked. If there isn't anything important in that file, you might as well just delete it!

What is the difference between window, screen, and document in Javascript?

Well, the window is the first thing that gets loaded into the browser. This window object has the majority of the properties like length, innerWidth, innerHeight, name, if it has been closed, its parents, and more.

What about the document object then? The document object is your html, aspx, php, or other document that will be loaded into the browser. The document actually gets loaded inside the window object and has properties available to it like title, URL, cookie, etc. What does this really mean? That means if you want to access a property for the window it is, if it is document it is which is also available in short as


That seems simple enough. But what happens once an IFRAME is introduced?


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

Eclipse uses it's own internal compiler that can compile to several Java versions.

From Eclipse Help > Java development user guide > Concepts > Java Builder

The Java builder builds Java programs using its own compiler (the Eclipse Compiler for Java) that implements the Java Language Specification.

For Eclipse Mars.1 Release (4.5.1), this can target 1.3 to 1.8 inclusive.

When you configure a project:

[project-name] > Properties > Java Compiler > Compiler compliance level

This configures the Eclipse Java compiler to compile code to the specified Java version, typically 1.8 today.

Host environment variables, eg JAVA_HOME etc, are not used.

The Oracle/Sun JDK compiler is not used.

Laravel whereIn OR whereIn

You could have searched just for whereIn function in the core to see that. Here you are. This must answer all your questions

 * Add a "where in" clause to the query.
 * @param  string  $column
 * @param  mixed   $values
 * @param  string  $boolean
 * @param  bool    $not
 * @return \Illuminate\Database\Query\Builder|static
public function whereIn($column, $values, $boolean = 'and', $not = false)
    $type = $not ? 'NotIn' : 'In';

    // If the value of the where in clause is actually a Closure, we will assume that
    // the developer is using a full sub-select for this "in" statement, and will
    // execute those Closures, then we can re-construct the entire sub-selects.
    if ($values instanceof Closure)
        return $this->whereInSub($column, $values, $boolean, $not);

    $this->wheres[] = compact('type', 'column', 'values', 'boolean');

    $this->bindings = array_merge($this->bindings, $values);

    return $this;

Look that it has a third boolean param. Good luck.

How do I set log4j level on the command line?

With Log4j2, this can be achieved using the following utility method added to your code.

private static void setLogLevel() {
  if (Boolean.getBoolean("log4j.debug")) {
    Configurator.setLevel(System.getProperty("log4j.logger"), Level.DEBUG);

You need these imports

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.config.Configurator;

Now invoke the setLogLevel method in your main() or whereever appropriate and pass command line params -Dlog4j.logger=com.mypackage.Thingie and -Dlog4j.debug=true.

Split array into chunks

Created a npm package for this

var result = [];

for (var i = 0; i < arr.length; i += size) {
  result.push(arr.slice(i, size + i));
return result;

When using a TypedArray

var result = [];

for (var i = 0; i < arr.length; i += size) {
  result.push(arr.subarray(i, size + i));
return result;

What are the differences among grep, awk & sed?

Grep is useful if you want to quickly search for lines that match in a file. It can also return some other simple information like matching line numbers, match count, and file name lists.

Awk is an entire programming language built around reading CSV-style files, processing the records, and optionally printing out a result data set. It can do many things but it is not the easiest tool to use for simple tasks.

Sed is useful when you want to make changes to a file based on regular expressions. It allows you to easily match parts of lines, make modifications, and print out results. It's less expressive than awk but that lends it to somewhat easier use for simple tasks. It has many more complicated operators you can use (I think it's even turing complete), but in general you won't use those features.

Remove all whitespaces from NSString

I prefer using regex like this:

NSString *myString = @"this is a test";
NSString *myNewString = [myString stringByReplacingOccurrencesOfString:@"\\s"
                                          range:NSMakeRange(0, [myStringlength])];
 //myNewString will be @"thisisatest"

You can make yourself a category on NSString to make life even easier:

- (NSString *) removeAllWhitespace
    return [self stringByReplacingOccurrencesOfString:@"\\s" withString:@""
                                                range:NSMakeRange(0, [self length])];


Here is a unit test method on it too:

- (void) testRemoveAllWhitespace
    NSString *testResult = nil;

    NSArray *testStringsArray        = @[@""
                                         ,@"    "
                                         ,@"  basicTest    "
                                         ,@"  another Test \n"
                                         ,@"a b c d e f g"
                                         ,@"\n\tA\t\t \t \nB    \f  C \t  ,d,\ve   F\r\r\r"
                                         ,@"  landscape, portrait,     ,,,up_side-down   ;asdf;  lkjfasdf0qi4jr0213 ua;;;;af!@@##$$ %^^ & *  * ()+  +   "

    NSArray *expectedResultsArray   = @[@""

    for (int i=0; i < [testStringsArray count]; i++)
        testResult = [testStringsArray[i] removeAllWhitespace];
        STAssertTrue([testResult isEqualToString:expectedResultsArray[i]], @"Expected: \"%@\" to become: \"%@\", but result was \"%@\"",
                     testStringsArray[i], expectedResultsArray[i], testResult);

Why doesn't the height of a container element increase if it contains floated elements?

The floated elements do not add to the height of the container element, and hence if you don't clear them, container height won't increase...

I'll show you visually:

enter image description here

enter image description here

enter image description here

More Explanation:

  <div style="float: left;"></div>
  <div style="width: 15px;"></div> <!-- This will shift 
                                        besides the top div. Why? Because of the top div 
                                        is floated left, making the 
                                        rest of the space blank -->

  <div style="clear: both;"></div> 
  <!-- Now in order to prevent the next div from floating beside the top ones, 
       we use `clear: both;`. This is like a wall, so now none of the div's 
       will be floated after this point. The container height will now also include the 
       height of these floated divs -->

You can also add overflow: hidden; on container elements, but I would suggest you use clear: both; instead.

Also if you might like to self-clear an element you can use

.self_clear:after {
  content: "";
  clear: both;
  display: table;

How Does CSS Float Work?

What is float exactly and what does it do?

  • The float property is misunderstood by most beginners. Well, what exactly does float do? Initially, the float property was introduced to flow text around images, which are floated left or right. Here's another explanation by @Madara Uchicha.

    So, is it wrong to use the float property for placing boxes side by side? The answer is no; there is no problem if you use the float property in order to set boxes side by side.

  • Floating an inline or block level element will make the element behave like an inline-block element.


  • If you float an element left or right, the width of the element will be limited to the content it holds, unless width is defined explicitly ...

  • You cannot float an element center. This is the biggest issue I've always seen with beginners, using float: center;, which is not a valid value for the float property. float is generally used to float/move content to the very left or to the very right. There are only four valid values for float property i.e left, right, none (default) and inherit.

  • Parent element collapses, when it contains floated child elements, in order to prevent this, we use clear: both; property, to clear the floated elements on both the sides, which will prevent the collapsing of the parent element. For more information, you can refer my another answer here.

  • (Important) Think of it where we have a stack of various elements. When we use float: left; or float: right; the element moves above the stack by one. Hence the elements in the normal document flow will hide behind the floated elements because it is on stack level above the normal floated elements. (Please don't relate this to z-index as that is completely different.)

Taking a case as an example to explain how CSS floats work, assuming we need a simple 2 column layout with a header, footer, and 2 columns, so here is what the blueprint looks like...

enter image description here

In the above example, we will be floating only the red boxes, either you can float both to the left, or you can float on to left, and another to right as well, depends on the layout, if it's 3 columns, you may float 2 columns to left where another one to the right so depends, though in this example, we have a simplified 2 column layout so will float one to left and the other to the right.

Markup and styles for creating the layout explained further down...

<div class="main_wrap">
    <div class="wrapper clear">
        <div class="floated_left">
            This<br />
            is<br />
            just<br />
            a<br />
            left<br />
            floated<br />
            column<br />
        <div class="floated_right">
            This<br />
            is<br />
            just<br />
            a<br />
            right<br />
            floated<br />
            column<br />

* {
    -moz-box-sizing: border-box;       /* Just for demo purpose */
    -webkkit-box-sizing: border-box;   /* Just for demo purpose */
    box-sizing: border-box;            /* Just for demo purpose */
    margin: 0;
    padding: 0;

.main_wrap {
    margin: 20px;
    border: 3px solid black;
    width: 520px;

header, footer {
    height: 50px;
    border: 3px solid silver;
    text-align: center;
    line-height: 50px;

.wrapper {
    border: 3px solid green;

.floated_left {
    float: left;
    width: 200px;
    border: 3px solid red;

.floated_right {
    float: right;
    width: 300px;
    border: 3px solid red;

.clear:after {
    clear: both;
    content: "";
    display: table;

Let's go step by step with the layout and see how float works..

First of all, we use the main wrapper element, you can just assume that it's your viewport, then we use header and assign a height of 50px so nothing fancy there. It's just a normal non floated block level element which will take up 100% horizontal space unless it's floated or we assign inline-block to it.

The first valid value for float is left so in our example, we use float: left; for .floated_left, so we intend to float a block to the left of our container element.

Column floated to the left

And yes, if you see, the parent element, which is .wrapper is collapsed, the one you see with a green border didn't expand, but it should right? Will come back to that in a while, for now, we have got a column floated to left.

Coming to the second column, lets it float this one to the right

Another column floated to the right

Here, we have a 300px wide column which we float to the right, which will sit beside the first column as it's floated to the left, and since it's floated to the left, it created empty gutter to the right, and since there was ample of space on the right, our right floated element sat perfectly beside the left one.

Still, the parent element is collapsed, well, let's fix that now. There are many ways to prevent the parent element from getting collapsed.

  • Add an empty block level element and use clear: both; before the parent element ends, which holds floated elements, now this one is a cheap solution to clear your floating elements which will do the job for you but, I would recommend not to use this.

Add, <div style="clear: both;"></div> before the .wrapper div ends, like

<div class="wrapper clear">
    <!-- Floated columns -->
    <div style="clear: both;"></div>


Well, that fixes very well, no collapsed parent anymore, but it adds unnecessary markup to the DOM, so some suggest, to use overflow: hidden; on the parent element holding floated child elements which work as intended.

Use overflow: hidden; on .wrapper

.wrapper {
    border: 3px solid green;
    overflow: hidden;


That saves us an element every time we need to clear float but as I tested various cases with this, it failed in one particular one, which uses box-shadow on the child elements.

Demo (Can't see the shadow on all 4 sides, overflow: hidden; causes this issue)

So what now? Save an element, no overflow: hidden; so go for a clear fix hack, use the below snippet in your CSS, and just as you use overflow: hidden; for the parent element, call the class below on the parent element to self-clear.

.clear:after {
    clear: both;
    content: "";
    display: table;

<div class="wrapper clear">
    <!-- Floated Elements -->


Here, shadow works as intended, also, it self-clears the parent element which prevents to collapse.

And lastly, we use footer after we clear the floated elements.


When is float: none; used anyways, as it is the default, so any use to declare float: none;?

Well, it depends, if you are going for a responsive design, you will use this value a lot of times, when you want your floated elements to render one below another at a certain resolution. For that float: none; property plays an important role there.

Few real-world examples of how float is useful.

  • The first example we already saw is to create one or more than one column layouts.
  • Using img floated inside p which will enable our content to flow around.

Demo (Without floating img)

Demo 2 (img floated to the left)

  • Using float for creating horizontal menu - Demo

Float second element as well, or use `margin`

Last but not the least, I want to explain this particular case where you float only single element to the left but you do not float the other, so what happens?

Suppose if we remove float: right; from our .floated_right class, the div will be rendered from extreme left as it isn't floated.


So in this case, either you can float the to the left as well


You can use margin-left which will be equal to the size of the left floated column i.e 200px wide.

How to get the first column of a pandas DataFrame as a Series?


where i is the position/number of the column(starting from 0).

So, i = 0 is for the first column.

You can also get the last column using i = -1

What is a database transaction?

I think a transaction is an atomic action in terms of DBMS.

that means it cannot be seperated. yes, in a transction, there may be several instructions for the system to execute. but they are binded together to finished a single basic task.

for example. you need to walk through a bridge (let's treat this as a transction), and to do this, say, you need 100 steps. overall, these steps cannot be seperated. when you've done half of them, there is only two choice for you: continue to finish them all, and go back to the start point. it's just like the to result of a transaction: success( committed ) and fail( rollback )

How to implement history.back() in angular.js

Or you can simply use code :



<a class="back" ng-class="icons">
   <img src="../media/icons/right_circular.png" onClick="javascript:history.go(-1);" />

How do I get the classes of all columns in a data frame?

You can simple make use of lapply or sapply builtin functions.

lapply will return you a list -


while sapply will take the best possible return type ex. Vector etc -


Both the commands will return you all the column names with their respective class.

Example: Communication between Activity and Service using Messaging

Great tutorial, fantastic presentation. Neat, simple, short and very explanatory. Although, notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent); method is no more. As trante stated here, good approach would be:

private static final int NOTIFICATION_ID = 45349;

private void showNotification() {
    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this)
                    .setContentTitle("My Notification Title")
                    .setContentText("Something interesting happened");

    Intent targetIntent = new Intent(this, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    _nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

public void onDestroy() {
    if (_timer != null) {_timer.cancel();}
    _nManager.cancel(NOTIFICATION_ID); // Cancel the persistent notification.
    Log.i("PlaybackService", "Service Stopped.");
    _isRunning = false;

Checked myself, everything works like a charm (activity and service names may differ from original).

Update a local branch with the changes from a tracked remote branch

You don't use the : syntax - pull always modifies the currently checked-out branch. Thus:

git pull origin my_remote_branch

while you have my_local_branch checked out will do what you want.

Since you already have the tracking branch set, you don't even need to specify - you could just do...

git pull

while you have my_local_branch checked out, and it will update from the tracked branch.

How do I check if a PowerShell module is installed?

Here is the code to check if AZ module is installed or not:

$checkModule = "AZ"

$Installedmodules = Get-InstalledModule

if ($ -contains $checkModule)

    "$checkModule is installed "


else {

    "$checkModule is not installed"


How to use JavaScript with Selenium WebDriver Java

I had a similar situation and solved it like this:

WebElement webElement = driver.findElement(By.xpath(""));

How to add parameters to HttpURLConnection using POST using NameValuePair

If you don't need the ArrayList<NameValuePair> for parameters, this is a shorter solution that builds the query string using the Uri.Builder class:

URL url = new URL("");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

Uri.Builder builder = new Uri.Builder()
        .appendQueryParameter("firstParam", paramValue1)
        .appendQueryParameter("secondParam", paramValue2)
        .appendQueryParameter("thirdParam", paramValue3);
String query =;

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));