Programs & Examples On #Scriptlet

A Scriptlet is a piece of raw Java code embedded in a JSP file which get executed in line with the JSP output.

How do I pass JavaScript values to Scriptlet in JSP?

Its not possible as you are expecting. But you can do something like this. Pass the your java script value to the servlet/controller, do your processing and then pass this value to the jsp page by putting it into some object's as your requirement. Then you can use this value as you want.

I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error

@skaffman nailed it down. They live each in its own context. However, I wouldn't consider using scriptlets as the solution. You'd like to avoid them. If all you want is to concatenate strings in EL and you discovered that the + operator fails for strings in EL (which is correct), then just do:

<c:out value="abc${test}" />

Or if abc is to obtained from another scoped variable named ${resp}, then do:

<c:out value="${resp}${test}" />

How can I avoid Java code in JSP files, using JSP 2?

  1. Make your values and parameters inside your servlet classes
  2. Fetch those values and parameters within your JSP using JSTL/Taglib

The good thing about this approach is that your code is also HTML like code!

Using if-else in JSP

Instead of if-else condition use if in both conditions. it will work that way but not sure why.

How to hide "Showing 1 of N Entries" with the dataTables.js library

try this for hide

$('#table_id').DataTable({
  "info": false
});

and try this for change label

$('#table_id').DataTable({
 "oLanguage": {
               "sInfo" : "Showing _START_ to _END_ of _TOTAL_ entries",// text you want show for info section
            },

});

Visual Studio Code pylint: Unable to import 'protorpc'

I've not played around with all possibilities, but at least I had the impression that this could be a python version related issue. No idea why, I just trusted my gut.

Thus I just changed the pythonPath to python3 (default: python):

"python.pythonPath": "python3"

I reinstalled the dependencies (including pylint!!!) with

pip3 install <package> --user

... and after restarting vs code, everything looked fine.

HTH Kai

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

I solved the same issue by following steps:

Check the angular version: Using command: ng version My angular version is: Angular CLI: 7.3.10

After that I have support version of ngx bootstrap from the link: https://www.npmjs.com/package/ngx-bootstrap

In package.json file update the version: "bootstrap": "^4.5.3", "@ng-bootstrap/ng-bootstrap": "^4.2.2",

Now after updating package.json, use the command npm update

After this use command ng serve and my error got resolved

Connect multiple devices to one device via Bluetooth

I don't think it's possible with bluetooth, but you could try looking into WiFi Peer-to-Peer,
which allows one-to-many connections.

How do you select the entire excel sheet with Range using VBA?

you can use all cells as a object like this :

Dim x as Range
Set x = Worksheets("Sheet name").Cells

X is now a range object that contains the entire worksheet

Select max value of each group

select name, value 
from( select name, value, ROW_NUMBER() OVER(PARTITION BY name ORDER BY value desc) as rn
from out_pumptable ) as a
where rn = 1

How to "properly" print a list?

Instead of using map, I'd recommend using a generator expression with the capability of join to accept an iterator:

def get_nice_string(list_or_iterator):
    return "[" + ", ".join( str(x) for x in list_or_iterator) + "]"

Here, join is a member function of the string class str. It takes one argument: a list (or iterator) of strings, then returns a new string with all of the elements concatenated by, in this case, ,.

'"SDL.h" no such file or directory found' when compiling

Having a similar case and I couldn't use StackAttacks solution as he's referring to SDL2 which is for the legacy code I'm using too new.

Fortunately our friends from askUbuntu had something similar:

Download SDL

tar xvf SDL-1.2.tar.gz
cd SDL-1.2
./configure
make
sudo make install

How do you share code between projects/solutions in Visual Studio?

You would simply create a separate Class Library project to contain the common code. It need not be part of any solution that uses it. Reference the class library from any project that needs it.

The only trick at all is that you will need to use a file reference to reference the project, since it will not be part of the solutions that refer to it. This means that the actual output assembly will have to be placed in a location that can be accessed by anyone building a project that references it. This can be done by placing the assembly on a share, for instance.

JSON array get length

have you tried size() ? Something like :

jar.size();

Hope it helps.

How do I properly clean up Excel interop objects?

Tested with Microsoft Excel 2016

A really tested solution.

To C# Reference please see: https://stackoverflow.com/a/1307180/10442623

To VB.net Reference please see: https://stackoverflow.com/a/54044646/10442623

1 include the class job

2 implement the class to handle the apropiate dispose of excel proces

How do I scroll to an element within an overflowed Div?

The above answers will position the inner element at the top of the overflow element even if it's in view inside the overflow element. I didn't want that so I modified it to not change the scroll position if the element is in view.

jQuery.fn.scrollTo = function(elem, speed) {
    var $this = jQuery(this);
    var $this_top = $this.offset().top;
    var $this_bottom = $this_top + $this.height();
    var $elem = jQuery(elem);
    var $elem_top = $elem.offset().top;
    var $elem_bottom = $elem_top + $elem.height();

    if ($elem_top > $this_top && $elem_bottom < $this_bottom) {
        // in view so don't do anything
        return;
    }
    var new_scroll_top;
    if ($elem_top < $this_top) {
        new_scroll_top = {scrollTop: $this.scrollTop() - $this_top + $elem_top};
    } else {
        new_scroll_top = {scrollTop: $elem_bottom - $this_bottom + $this.scrollTop()};
    }
    $this.animate(new_scroll_top, speed === undefined ? 100 : speed);
    return this;
};

User GETDATE() to put current date into SQL variable

SELECT @LastChangeDate = GETDATE()

Remove element of a regular array

The nature of arrays is that their length is immutable. You can't add or delete any of the array items.

You will have to create a new array that is one element shorter and copy the old items to the new array, excluding the element you want to delete.

So it is probably better to use a List instead of an array.

How to convert date to timestamp in PHP?

Using strtotime() function you can easily convert date to timestamp

<?php
// set default timezone
date_default_timezone_set('America/Los_Angeles');

//define date and time
$date = date("d M Y H:i:s");

// output
echo strtotime($date);
?> 

More info: http://php.net/manual/en/function.strtotime.php

Online conversion tool: http://freeonlinetools24.com/

CSS: Change image src on img:hover

What you could do is cheat a little bit by setting width and height to 0 to hide the actual image and apply some CSS to do what you want:

#aks {
    width:0px;
    height:0px;
    background:url('http://dummyimage.com/100x100/000/fff');
    padding:50px;
}

#aks:hover {
    background: url('http://dummyimage.com/100x100/eb00eb/fff');
}

And the padding making the img tag the size you want it to have (half the size of your actual image).

Fiddle

How to add option to select list in jQuery

Your code fails because you are executing a method (addOption) on the jQuery object (and this object does not support the method)

You can use the standard Javascript function like this:

$("#dropListBuilding")[0].options.add( new Option("My Text","My Value") )

How do I trim() a string in angularjs?

Why don't you simply use JavaScript's trim():

str.trim() //Will work everywhere irrespective of any framework.

For compatibility with <IE9 use:

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

Found it Here

Word count from a txt file program

#!/usr/bin/python
file=open("D:\\zzzz\\names2.txt","r+")
wordcount={}
for word in file.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1
for k,v in wordcount.items():
    print k, v

Putting a password to a user in PhpMyAdmin in Wamp

Get back to the default setting by following this step:

Instead of

$cfg['Servers'][$i]['AllowNoPassword'] = false;

change it to:

$cfg['Servers'][$i]['AllowNoPassword'] = true;

in your config.inc.php file.

Do not specify any password and put the user name as it was before, which means root.

E.g.

$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';

This worked for me after i had edited my config.inc.php file.

Convert timestamp to date in Oracle SQL

If the datatype is timestamp then the visible format is irrelevant.

You should avoid converting the data to date or use of to_char. Instead compare the timestamp data to timestamp values using TO_TIMESTAMP()

WHERE start_ts >= TO_TIMESTAMP('2016-05-13', 'YYYY-MM-DD')
   AND start_ts < TO_TIMESTAMP('2016-05-14', 'YYYY-MM-DD')

AWK to print field $2 first, then field $1

Use a dot or a pipe as the field separator:

awk -v FS='[.|]' '{
    printf "%s%s %s.%s\n", toupper(substr($4,1,1)), substr($4,2), $1, $2
}' << END
[email protected]|com.emailclient.account
[email protected]|com.socialsite.auth.account
END

gives:

Emailclient [email protected]
Socialsite [email protected]

Why doesn't java.util.Set have get(int index)?

Actually this is a recurring question when writing JavaEE applications which use Object-Relational Mapping (for example with Hibernate); and from all the people who replied here, Andreas Petersson is the only one who understood the real issue and offered the correct answer to it: Java is missing a UniqueList! (or you can also call it OrderedSet, or IndexedSet).

Maxwing mentioned this use-case (in which you need ordered AND unique data) and he suggested the SortedSet, but this is not what Marty Pitt really needed.

This "IndexedSet" is NOT the same as a SortedSet - in a SortedSet the elements are sorted by using a Comparator (or using their "natural" ordering).

But instead it is closer to a LinkedHashSet (which others also suggested), or even more so to an (also inexistent) "ArrayListSet", because it guarantees that the elements are returned in the same order as they were inserted.

But the LinkedHashSet is an implementation, not an interface! What is needed is an IndexedSet (or ListSet, or OrderedSet, or UniqueList) interface! This will allow the programmer to specify that he needs a collection of elements that have a specific order and without duplicates, and then instantiate it with any implementation (for example an implementation provided by Hibernate).

Since JDK is open-source, maybe this interface will be finally included in Java 7...

What is the use of the @ symbol in PHP?

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

If you have set a custom error handler function with set_error_handler() then it will still get called, but this custom error handler can (and should) call error_reporting() which will return 0 when the call that triggered the error was preceded by an @.

<?php
/* Intentional file error */
$my_file = @file ('non_existent_file') or
    die ("Failed opening file: error was '$php_errormsg'");

// this works for any expression, not just functions:
$value = @$cache[$key];
// will not issue a notice if the index $key doesn't exist.

?>

Note:-

1) The @-operator works only on expressions.

2) A simple rule of thumb is: if you can take the value of something, you can prepend the @ operator to it. For instance, you can prepend it to variables, function and include calls, constants, and so forth. You cannot prepend it to function or class definitions, or conditional structures such as if and foreach, and so forth.

Warning:-

Currently the "@" error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use "@" to suppress errors from a certain function and either it isn't available or has been mistyped, the script will die right there with no indication as to why.

AngularJS : Custom filters and ng-repeat

If you still want a custom filter you can pass in the search model to the filter:

<article data-ng-repeat="result in results | cartypefilter:search" class="result">

Where definition for the cartypefilter can look like this:

app.filter('cartypefilter', function() {
  return function(items, search) {
    if (!search) {
      return items;
    }

    var carType = search.carType;
    if (!carType || '' === carType) {
      return items;
    }

    return items.filter(function(element, index, array) {
      return element.carType.name === search.carType;
    });

  };
});

http://plnkr.co/edit/kBcUIayO8tQsTTjTA2vO?p=preview

REST API Token-based Authentication

In the web a stateful protocol is based on having a temporary token that is exchanged between a browser and a server (via cookie header or URI rewriting) on every request. That token is usually created on the server end, and it is a piece of opaque data that has a certain time-to-live, and it has the sole purpose of identifying a specific web user agent. That is, the token is temporary, and becomes a STATE that the web server has to maintain on behalf of a client user agent during the duration of that conversation. Therefore, the communication using a token in this way is STATEFUL. And if the conversation between client and server is STATEFUL it is not RESTful.

The username/password (sent on the Authorization header) is usually persisted on the database with the intent of identifying a user. Sometimes the user could mean another application; however, the username/password is NEVER intended to identify a specific web client user agent. The conversation between a web agent and server based on using the username/password in the Authorization header (following the HTTP Basic Authorization) is STATELESS because the web server front-end is not creating or maintaining any STATE information whatsoever on behalf of a specific web client user agent. And based on my understanding of REST, the protocol states clearly that the conversation between clients and server should be STATELESS. Therefore, if we want to have a true RESTful service we should use username/password (Refer to RFC mentioned in my previous post) in the Authorization header for every single call, NOT a sension kind of token (e.g. Session tokens created in web servers, OAuth tokens created in authorization servers, and so on).

I understand that several called REST providers are using tokens like OAuth1 or OAuth2 accept-tokens to be be passed as "Authorization: Bearer " in HTTP headers. However, it appears to me that using those tokens for RESTful services would violate the true STATELESS meaning that REST embraces; because those tokens are temporary piece of data created/maintained on the server side to identify a specific web client user agent for the valid duration of a that web client/server conversation. Therefore, any service that is using those OAuth1/2 tokens should not be called REST if we want to stick to the TRUE meaning of a STATELESS protocol.

Rubens

Multiple file upload in php

this simple script worked for me.

<?php

foreach($_FILES as $file){
  //echo $file['name']; 
  echo $file['tmp_name'].'</br>'; 
  move_uploaded_file($file['tmp_name'], "./uploads/".$file["name"]);
}

?>

How does Task<int> become an int?

No requires converting the Task to int. Simply Use The Task Result.

int taskResult = AccessTheWebAndDouble().Result;

public async Task<int> AccessTheWebAndDouble()
{
    int task = AccessTheWeb();
    return task;
}

It will return the value if available otherwise it return 0.

How to make two plots side-by-side using Python?

You can use - matplotlib.gridspec.GridSpec

Check - https://matplotlib.org/stable/api/_as_gen/matplotlib.gridspec.GridSpec.html

The below code displays a heatmap on right and an Image on left.

#Creating 1 row and 2 columns grid
gs = gridspec.GridSpec(1, 2) 
fig = plt.figure(figsize=(25,3))

#Using the 1st row and 1st column for plotting heatmap
ax=plt.subplot(gs[0,0])
ax=sns.heatmap([[1,23,5,8,5]],annot=True)

#Using the 1st row and 2nd column to show the image
ax1=plt.subplot(gs[0,1])
ax1.grid(False)
ax1.set_yticklabels([])
ax1.set_xticklabels([])

#The below lines are used to display the image on ax1
image = io.imread("https://images-na.ssl-images- amazon.com/images/I/51MvhqY1qdL._SL160_.jpg")

plt.imshow(image)
plt.show()

Output image

Location of the android sdk has not been setup in the preferences in mac os?

I had the same problem: when click on the "Opens the Android SDK Manager", a pop out error message says “Location of the Android SDK has not been setup in the preference”. The delete and add again update address in "install new software" doesn't work for me.

I went to the ../android/android-sdk-windows and click the SDK Manager.exe. This works for me.

So I think after I updated the SDK, the eclipse cannot trigger the SDK Manager currently. But it can run by itself outside of eclipse.

Add image in pdf using jspdf

For result in base64, before convert to canvas:

var getBase64ImageUrl = function(url, callback, mine) {

                    var img = new Image();

                    url = url.replace("http://","//");

                    img.setAttribute('crossOrigin', 'anonymous');

                    img.onload = function () {
                        var canvas = document.createElement("canvas");
                        canvas.width =this.width;
                        canvas.height =this.height;

                        var ctx = canvas.getContext("2d");
                        ctx.drawImage(this, 0, 0);

                        var dataURL = canvas.toDataURL(mine || "image/jpeg");

                        callback(dataURL);
                    };
                    img.src = url;

                    img.onerror = function(){

                        console.log('on error')
                        callback('');

                    }

            }

   getBase64ImageUrl('Koala.jpeg', function(img){
         //img is a base64encode result
         //return img;
          console.log(img);

          var doc = new jsPDF();
              doc.setFontSize(40);
              doc.text(30, 20, 'Hello world!');
              doc.output('datauri');
              doc.addImage(img, 'JPEG', 15, 40, 180, 160);
    });

Getting title and meta tags from external website

I've got this working a different way and thought I'd share it. Less code than others and found it here. I've added a few things to make it load the page meta that you are on instead of a certain page. I wanted this to copy the default page title and description into the og tags automatically.

For some reason though, whatever way (different scripts) I tried, the page loads super slow online but instant on wamp. Not sure why so I'm probably going with a switch case since the site is not huge.

<?php
$url = 'http://sitename.com'.$_SERVER['REQUEST_URI'];
$fp = fopen($url, 'r');

$content = "";

while(!feof($fp)) {
    $buffer = trim(fgets($fp, 4096));
    $content .= $buffer;
}

$start = '<title>';
$end = '<\/title>';

preg_match("/$start(.*)$end/s", $content, $match);
$title = $match[1];

$metatagarray = get_meta_tags($url);
$description = $metatagarray["description"];

echo "<div><strong>Title:</strong> $title</div>";
echo "<div><strong>Description:</strong> $description</div>";
?>

and in the HTML header

<meta property="og:title" content="<?php echo $title; ?>" />
<meta property="og:description" content="<?php echo $description; ?>" />

What is the use of adding a null key or value to a HashMap in Java?

The answers so far only consider the worth of have a null key, but the question also asks about any number of null values.

The benefit of storing the value null against a key in a HashMap is the same as in databases, etc - you can record a distinction between having a value that is empty (e.g. string ""), and not having a value at all (null).

SQL Inner join more than two tables

try this method given below, modify to suit your need.

SELECT
  employment_status.staff_type,
  COUNT(monthly_pay_register.age),
  monthly_pay_register.BASIC_SALARY,
  monthly_pay_register.TOTAL_MONTHLY_ALLOWANCES,
  monthly_pay_register.MONTHLY_GROSS,
  monthly_pay_register.TOTAL_MONTHLY_DEDUCTIONS,
  monthly_pay_register.MONTHLY_PAY
FROM 
  (monthly_pay_register INNER JOIN deduction_logs 
ON
  monthly_pay_register.employee_info_employee_no = deduction_logs.employee_no)
INNER JOIN
  employment_status ON deduction_logs.employee_no = employment_status.employee_no
WHERE
  monthly_pay_register.`YEAR`=2017
and 
  monthly_pay_register.`MONTH`='may'

MD5 hashing in Android

I have made a simple Library in Kotlin.

Add at Root build.gradle

allprojects {
        repositories {
            ...
            maven { url 'https://jitpack.io' }
        }
    }

at App build.gradle

implementation 'com.github.1AboveAll:Hasher:-SNAPSHOT'

Usage

In Kotlin

val ob = Hasher()

Then Use hash() method

ob.hash("String_You_Want_To_Encode",Hasher.MD5)

ob.hash("String_You_Want_To_Encode",Hasher.SHA_1)

It will return MD5 and SHA-1 Respectively.

More about the Library

https://github.com/ihimanshurawat/Hasher

Jackson how to transform JsonNode to ArrayNode without casting?

I would assume at the end of the day you want to consume the data in the ArrayNode by iterating it. For that:

Iterator<JsonNode> iterator = datasets.withArray("datasets").elements();
while (iterator.hasNext()) 
        System.out.print(iterator.next().toString() + " "); 

or if you're into streams and lambda functions:

import com.google.common.collect.Streams;
Streams.stream(datasets.withArray("datasets").elements())
    .forEach( item -> System.out.print(item.toString()) )

Add swipe to delete UITableViewCell

@available(iOS 11.0, *)
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

        let editAction = UIContextualAction.init(style: UIContextualAction.Style.normal, title: "Edit", handler: { (action, view, completion) in
            //TODO: Edit
            completion(true)
            self.popUpViewPresent(index:indexPath.row)
        })

        let deleteAction = UIContextualAction.init(style: UIContextualAction.Style.destructive, title: "Delete", handler: { (action, view, completion) in
            //TODO: Delete
            completion(true)
            self.deleteTagAction(senderTag:indexPath.row)
        })
        editAction.image = UIImage(named: "Edit-white")
        deleteAction.image = UIImage(named: "Delete-white")
        editAction.backgroundColor = UIColor.gray
        deleteAction.backgroundColor = UIColor.red

        let config = UISwipeActionsConfiguration(actions: [deleteAction, editAction])
        config.performsFirstActionWithFullSwipe = false
        return config
    }

Java character array initializer

Instead of above way u can achieve the solution simply by following method..

public static void main(String args[]) {
    String ini = "Hi there";
    for (int i = 0; i < ini.length(); i++) {
        System.out.print(" " + ini.charAt(i));
    }
}

What is Options +FollowSymLinks?

Parameter Options FollowSymLinks enables you to have a symlink in your webroot pointing to some other file/dir. With this disabled, Apache will refuse to follow such symlink. More secure Options SymLinksIfOwnerMatch can be used instead - this will allow you to link only to other files which you do own.

If you use Options directive in .htaccess with parameter which has been forbidden in main Apache config, server will return HTTP 500 error code.

Allowed .htaccess options are defined by directive AllowOverride in the main Apache config file. To allow symlinks, this directive need to be set to All or Options.

Besides allowing use of symlinks, this directive is also needed to enable mod_rewrite in .htaccess context. But for this, also the more secure SymLinksIfOwnerMatch option can be used.

How to define a default value for "input type=text" without using attribute 'value'?

You should rather use the attribute placeholder to give the default value to the text input field.

e.g.

<input type="text" size="32" placeholder="1000" name="fee" />

error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

In case someone missed the obvious; note that if you build a GUI application and use
"-subsystem:windows" in the link-args, the application entry is WinMain@16. Not main(). Hence you can use this snippet to call your main():

#include <stdlib.h>
#include <windows.h>

#ifdef __GNUC__
#define _stdcall  __attribute__((stdcall))
#endif

int _stdcall
WinMain (struct HINSTANCE__ *hInstance,
         struct HINSTANCE__ *hPrevInstance,
         char               *lpszCmdLine,
         int                 nCmdShow)
{
  return main (__argc, __argv);
}

IBOutlet and IBAction

Ran into the diagram while looking at key-value coding, thought it might help someone. It helps with understanding of what IBOutlet is.

By looking at the flow, one could see that IBOutlets are only there to match the property name with a control name in the Nib file.

How nib file is loaded, screenshot of Matt's online book for iOS6

Is there a better way to run a command N times in bash?

xargs and seq will help

function __run_times { seq 1 $1| { shift; xargs -i -- "$@"; } }

the view :

abon@abon:~$ __run_times 3  echo hello world
hello world
hello world
hello world

How to copy text to the client's clipboard using jQuery?

Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.

Here's how to do it for Internet Explorer:

function copy (str)
{
    //for IE ONLY!
    window.clipboardData.setData('Text',str);
}

How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?

Just if someone is having this issue and hadn't done list[index, sub-index], you could be having the problem because you're missing a comma between two arrays in an array of arrays (It happened to me).

Best way to check if an PowerShell Object exist?

You can also do

if ($ie) {
    # Do Something if $ie is not null
}

Return HTML content as a string, given URL. Javascript Function

you need to return when the readystate==4 e.g.

function httpGet(theUrl)
{
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            return xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", theUrl, false );
    xmlhttp.send();    
}

YouTube API to fetch all videos on a channel

Thanks to the references shared here and elsewhere, I've made an online script / tool that one can use to obtain all videos of a channel.

It combines API calls to youtube.channels.list, playlistItems, videos. It uses recursive functions to make the asynchronous callbacks run the next iteration upon getting a valid response.

This also serves to limit the actual number of requests made at a time, hence keeping you safe from violating YouTube API rules. Sharing shortened snippets and then a link to the full code. I got around the 50 max results per call limitation by using the nextPageToken value that comes in the response to fetch the next 50 results and so on.

function getVideos(nextPageToken, vidsDone, params) {
    $.getJSON("https://www.googleapis.com/youtube/v3/playlistItems", {
        key: params.accessKey,
        part: "snippet",
        maxResults: 50,
        playlistId: params.playlistId,
        fields: "items(snippet(publishedAt, resourceId/videoId, title)), nextPageToken",
        pageToken: ( nextPageToken || '')
        },
        function(data) {
            // commands to process JSON variable, extract the 50 videos info

            if ( vidsDone < params.vidslimit) {

                // Recursive: the function is calling itself if
                // all videos haven't been loaded yet
                getVideos( data.nextPageToken, vidsDone, params);

            }
             else {
                 // Closing actions to do once we have listed the videos needed.
             }
    });
}

This got a basic listing of the videos, including id, title, date of publishing and similar. But to get more detail of each video like view counts and likes, one has to make API calls to videos.

// Looping through an array of video id's
function fetchViddetails(i) {
    $.getJSON("https://www.googleapis.com/youtube/v3/videos", {
        key: document.getElementById("accesskey").value,
        part: "snippet,statistics",
        id: vidsList[i]
        }, function(data) {

            // Commands to process JSON variable, extract the video
            // information and push it to a global array
            if (i < vidsList.length - 1) {
                fetchViddetails(i+1) // Recursive: calls itself if the
                                     //            list isn't over.
            }
});

See the full code here, and live version here. (Edit: fixed github link)
Edit: Dependencies: JQuery, Papa.parse

How to create a stopwatch using JavaScript?

Solution by Mosh Hamedani

Creating a StopWatch function constructor.

Define 4 local variables

  1. startTime
  2. endTime
  3. isRunning
  4. duration set to 0

Next create 3 methods

  1. start
  2. stop
  3. reset

start method

  • check if isRunning is true if so throw an error that start cannot be called twice.
  • set isRunning to true
  • assign the current Date object to startTime.

stop method

  • check if isRunning is false if so throw an error that stop cannot be called twice.
  • set isRunning to false
  • assign the current Date object to endTime.
  • calculate the seconds by endTime and startTime Date object
  • increment duration with seconds

reset method:

  • reset all the local variables.

Read-only property

if you want to access the duration local variable you need to define a property using Object.defineProperty. It's useful when you want to create a read-only property.

Object.defineProperty takes 3 parameters

  • the object which to define a property (in this case the current object (this))
  • the name of the property
  • the value of the key property.

  • We want to create a Read-only property so we pass an object as a value. The object contain a get method that return the duration local variable. in this way we cannot change the property only get it.

The trick is to use Date() object to calculate the time.

Reference the code below

function StopWatch() {


let startTime,
    endTime,
    isRunning,
    duration = 0;

  this.start = function () {
    if (isRunning) throw new Error("StopWatch has already been started.");

    isRunning = true;

    startTime = new Date();
  };



this.stop = function () {
    if (!isRunning) throw new Error("StopWatch has already been stop.");

    isRunning = false;

    endTime = new Date();

    const seconds = (endTime.getTime() - startTime.getTime()) / 1000;
    duration += seconds;
  };

  this.reset = function () {
    duration = 0;
    startTime = null;
    endTime = null;
    isRunning = false;
  };

  Object.defineProperty(this, "duration", {
    get: function () {
      return duration;
    },
  });
}

const sw = new StopWatch();

How to force reloading a page when using browser back button?

You can use pageshow event to handle situation when browser navigates to your page through history traversal:

window.addEventListener( "pageshow", function ( event ) {
  var historyTraversal = event.persisted || 
                         ( typeof window.performance != "undefined" && 
                              window.performance.navigation.type === 2 );
  if ( historyTraversal ) {
    // Handle page restore.
    window.location.reload();
  }
});

Note that HTTP cache may be involved too. You need to set proper cache related HTTP headers on server to cache only those resources that need to be cached. You can also do forced reload to instuct browser to ignore HTTP cache: window.location.reload( true ). But I don't think that it is best solution.

For more information check:

Initialize empty vector in structure - c++

Like this:

#include <string>
#include <vector>

struct user
{
    std::string username;
    std::vector<unsigned char> userpassword;
};

int main()
{
    user r;   // r.username is "" and r.userpassword is empty
    // ...
}

View JSON file in Browser

For Safari 12 and later, you can try the JSONBeautifier bookmarklet. Also works with other browsers.

I created this because JSON Formatter for Safari stopped working in Safari 12. There are a few new options for Safari 12, but I didn't find an open source one in the App Store, and I do not trust closed source browser extensions.

This can be used as a bookmarklet or the source, json-beautifier.js, can be copied and pasted into the browser console. The code is freely available for review and is less than 100 lines of code including comments. Runs entirely on your device and never sends your data over a network.

Works with local files too.

How do I convert from a money datatype in SQL server?

This looks like a formating issue to me.
As far as SQL Server's money type is concerned 0 == 0.00

If you're trying to display 0 in say c# rather then 0.00 you should convert it to a string, and format it as you want. (or truncate it.)

Begin, Rescue and Ensure in Ruby?

Yes, ensure ENSURES it is run every time, so you don't need the file.close in the begin block.

By the way, a good way to test is to do:

begin
  # Raise an error here
  raise "Error!!"
rescue
  #handle the error here
ensure
  p "=========inside ensure block"
end

You can test to see if "=========inside ensure block" will be printed out when there is an exception. Then you can comment out the statement that raises the error and see if the ensure statement is executed by seeing if anything gets printed out.

How to perform a LEFT JOIN in SQL Server between two SELECT statements?

SELECT [UserID] FROM [User] u LEFT JOIN (
SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043) t on t.TailUser=u.USerID

Java: getMinutes and getHours

Try Calender. Use getInstance to get a Calender-Object. Then use setTime to set the required Date. Now you can use get(int field) with the appropriate constant like HOUR_OF_DAY or so to read the values you need.

http://java.sun.com/javase/6/docs/api/java/util/Calendar.html

Python group by

result = []
# Make a set of your "types":
input_set = set([tpl[1] for tpl in input])
>>> set(['ETH', 'KAT', 'NOT'])
# Iterate over the input_set
for type_ in input_set:
    # a dict to gather things:
    D = {}
    # filter all tuples from your input with the same type as type_
    tuples = filter(lambda tpl: tpl[1] == type_, input)
    # write them in the D:
    D["type"] = type_
    D["itmes"] = [tpl[0] for tpl in tuples]
    # append D to results:
    result.append(D)

result
>>> [{'itmes': ['9085267', '11788544'], 'type': 'NOT'}, {'itmes': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'itmes': ['11013331', '9843236'], 'type': 'KAT'}]

What is an example of the simplest possible Socket.io example?

Edit: I feel it's better for anyone to consult the excellent chat example on the Socket.IO getting started page. The API has been quite simplified since I provided this answer. That being said, here is the original answer updated small-small for the newer API.

Just because I feel nice today:

index.html

<!doctype html>
<html>
    <head>
        <script src='/socket.io/socket.io.js'></script>
        <script>
            var socket = io();

            socket.on('welcome', function(data) {
                addMessage(data.message);

                // Respond with a message including this clients' id sent from the server
                socket.emit('i am client', {data: 'foo!', id: data.id});
            });
            socket.on('time', function(data) {
                addMessage(data.time);
            });
            socket.on('error', console.error.bind(console));
            socket.on('message', console.log.bind(console));

            function addMessage(message) {
                var text = document.createTextNode(message),
                    el = document.createElement('li'),
                    messages = document.getElementById('messages');

                el.appendChild(text);
                messages.appendChild(el);
            }
        </script>
    </head>
    <body>
        <ul id='messages'></ul>
    </body>
</html>

app.js

var http = require('http'),
    fs = require('fs'),
    // NEVER use a Sync function except at start-up!
    index = fs.readFileSync(__dirname + '/index.html');

// Send index.html to all requests
var app = http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(index);
});

// Socket.io server listens to our app
var io = require('socket.io').listen(app);

// Send current time to all connected clients
function sendTime() {
    io.emit('time', { time: new Date().toJSON() });
}

// Send current time every 10 secs
setInterval(sendTime, 10000);

// Emit welcome message on connection
io.on('connection', function(socket) {
    // Use socket to communicate with this particular client only, sending it it's own id
    socket.emit('welcome', { message: 'Welcome!', id: socket.id });

    socket.on('i am client', console.log);
});

app.listen(3000);

Changing website favicon dynamically

According to WikiPedia, you can specify which favicon file to load using the link tag in the head section, with a parameter of rel="icon".

For example:

 <link rel="icon" type="image/png" href="/path/image.png">

I imagine if you wanted to write some dynamic content for that call, you would have access to cookies so you could retrieve your session information that way and present appropriate content.

You may fall foul of file formats (IE reportedly only supports it's .ICO format, whilst most everyone else supports PNG and GIF images) and possibly caching issues, both on the browser and through proxies. This would be because of the original itention of favicon, specifically, for marking a bookmark with a site's mini-logo.

Pass multiple complex objects to a post/put Web API method

As @djikay mentioned, you cannot pass multiple FromBody parameters.

One workaround I have is to define a CompositeObject,

public class CompositeObject
{
    public Content Content { get; set; }
    public Config Config { get; set; }
}

and have your WebAPI takes this CompositeObject as the parameter instead.

public void StartProcessiong([FromBody] CompositeObject composite)
{ ... }

Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?

Sounds like you're calling sp_executesql with a VARCHAR statement, when it needs to be NVARCHAR.

e.g. This will give the error because @SQL needs to be NVARCHAR

DECLARE @SQL VARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

So:

DECLARE @SQL NVARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

What integer hash function are good that accepts an integer hash key?

For random hash values, some engineers said golden ratio prime number(2654435761) is a bad choice, with my testing results, I found that it's not true; instead, 2654435761 distributes the hash values pretty good.

#define MCR_HashTableSize 2^10

unsigned int
Hash_UInt_GRPrimeNumber(unsigned int key)
{
  key = key*2654435761 & (MCR_HashTableSize - 1)
  return key;
}

The hash table size must be a power of two.

I have written a test program to evaluate many hash functions for integers, the results show that GRPrimeNumber is a pretty good choice.

I have tried:

  1. total_data_entry_number / total_bucket_number = 2, 3, 4; where total_bucket_number = hash table size;
  2. map hash value domain into bucket index domain; that is, convert hash value into bucket index by Logical And Operation with (hash_table_size - 1), as shown in Hash_UInt_GRPrimeNumber();
  3. calculate the collision number of each bucket;
  4. record the bucket that has not been mapped, that is, an empty bucket;
  5. find out the max collision number of all buckets; that is, the longest chain length;

With my testing results, I found that Golden Ratio Prime Number always has the fewer empty buckets or zero empty bucket and the shortest collision chain length.

Some hash functions for integers are claimed to be good, but the testing results show that when the total_data_entry / total_bucket_number = 3, the longest chain length is bigger than 10(max collision number > 10), and many buckets are not mapped(empty buckets), which is very bad, compared with the result of zero empty bucket and longest chain length 3 by Golden Ratio Prime Number Hashing.

BTW, with my testing results, I found one version of shifting-xor hash functions is pretty good(It's shared by mikera).

unsigned int Hash_UInt_M3(unsigned int key)
{
  key ^= (key << 13);
  key ^= (key >> 17);    
  key ^= (key << 5); 
  return key;
}

Multiple INSERT statements vs. single INSERT with multiple VALUES

The issue probably has to do with the time it takes to compile the query.

If you want to speed up the inserts, what you really need to do is wrap them in a transaction:

BEGIN TRAN;
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('6f3f7257-a3d8-4a78-b2e1-c9b767cfe1c1', 'First 0', 'Last 0', 0);
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('32023304-2e55-4768-8e52-1ba589b82c8b', 'First 1', 'Last 1', 1);
...
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('f34d95a7-90b1-4558-be10-6ceacd53e4c4', 'First 999', 'Last 999', 999);
COMMIT TRAN;

From C#, you might also consider using a table valued parameter. Issuing multiple commands in a single batch, by separating them with semicolons, is another approach that will also help.

How to check if an excel cell is empty using Apache POI?

Cell.getCellType() is deprecated in the latest POI API. If you are using POI API version 3.17, use the below code:

if (Cell.getCellTypeEnum() == CellType.BLANK) {
    //do your stuff here
}

Private Variables and Methods in Python

Double underscore. That mangles the name. The variable can still be accessed, but it's generally a bad idea to do so.

Use single underscores for semi-private (tells python developers "only change this if you absolutely must") and doubles for fully private.

Get the second largest number in a list in linear time

If you do not mind using numpy (import numpy as np):

np.partition(numbers, -2)[-2]

gives you the 2nd largest element of the list with a guaranteed worst-case O(n) running time.

The partition(a, kth) methods returns an array where the kth element is the same it would be in a sorted array, all elements before are smaller, and all behind are larger.

How to get resources directory path programmatically

I'm assuming the contents of src/main/resources/ is copied to WEB-INF/classes/ inside your .war at build time. If that is the case you can just do (substituting real values for the classname and the path being loaded).

URL sqlScriptUrl = MyServletContextListener.class
                       .getClassLoader().getResource("sql/script.sql");

Postgres ERROR: could not open file for reading: Permission denied

For me it worked to simply to add sudo (or run as root) for the chown command:

sudo chown postgres /users/darchcruise/desktop/items_ordered.csv

jQuery UI " $("#datepicker").datepicker is not a function"

I just ran into a similar issue. When I changed my script reference from self-closing tags (ie, <script src=".." />) to empty nodes (ie, <script src=".."></script>) my errors went away and I could suddenly reference the jQuery UI functions.

At the time, I didn't realize this was just a brain-fart of me not closing it properly to begin with. (I'm posting this simply on the chance that anyone else coming across the thread is having a similar issue.)

Neither BindingResult nor plain target object for bean name available as request attribute

If you have Model or transfer object passed to GET method but still have this error, check naming of your variables. Use entity/transfer object names in camelcase. I had BusinessTripDTO object and named it 'trip' for short. It caused this error to occure, even I had all other parts in place. Renaming varaibles to businessTripDTO in Java and Thymeleaf solved this problem for me.

Textarea Auto height

This using Pure JavaScript Code.

_x000D_
_x000D_
function auto_grow(element) {_x000D_
    element.style.height = "5px";_x000D_
    element.style.height = (element.scrollHeight)+"px";_x000D_
}
_x000D_
textarea {_x000D_
    resize: none;_x000D_
    overflow: hidden;_x000D_
    min-height: 50px;_x000D_
    max-height: 100px;_x000D_
}
_x000D_
<textarea oninput="auto_grow(this)"></textarea>
_x000D_
_x000D_
_x000D_

Removing MySQL 5.7 Completely

You need to remove the /var/lib/mysql folder. Also, purge when you remove the packages (I'm told this helps).

sudo apt-get remove --purge mysql-server mysql-client mysql-common

sudo rm -rf /var/lib/mysql

I was encountering similar issues. The second line got rid of my issues and allowed me to set up MySql from scratch. Hopefully it helps you too!

bootstrap button shows blue outline when clicked

This one worked for me in Bootstrap 4:

.btn {border-color: transparent;}

MySQL Event Scheduler on a specific time everyday

CREATE EVENT test_event_03
ON SCHEDULE EVERY 1 MINUTE
STARTS CURRENT_TIMESTAMP
ENDS CURRENT_TIMESTAMP + INTERVAL 1 HOUR
DO
   INSERT INTO messages(message,created_at)
   VALUES('Test MySQL recurring Event',NOW());

Extracting text OpenCV

You can try this method that is developed by Chucai Yi and Yingli Tian.

They also share a software (which is based on Opencv-1.0 and it should run under Windows platform.) that you can use (though no source code available). It will generate all the text bounding boxes (shown in color shadows) in the image. By applying to your sample images, you will get the following results:

Note: to make the result more robust, you can further merge adjacent boxes together.


Update: If your ultimate goal is to recognize the texts in the image, you can further check out gttext, which is an OCR free software and Ground Truthing tool for Color Images with Text. Source code is also available.

With this, you can get recognized texts like:

Programmatically set the initial view controller using Storyboards

You can set Navigation rootviewcontroller as a main view controller. This idea can use for auto login as per application requirement.

UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];

UIViewController viewController = (HomeController*)[mainStoryboard instantiateViewControllerWithIdentifier: @"HomeController"];

UINavigationController navController = [[UINavigationController alloc] initWithRootViewController:viewController];

 self.window.rootViewController = navController;

if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {

    // do stuff for iOS 7 and newer

    navController.navigationBar.barTintColor = [UIColor colorWithRed:88/255.0 green:164/255.0 blue:73/255.0 alpha:1.0];

    navController.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithRed:88/255.0 green:164/255.0 blue:73/255.0 alpha:1.0];

    navController.navigationBar.tintColor = [UIColor whiteColor];

    navController.navigationItem.titleView.tintColor = [UIColor whiteColor];

    NSDictionary *titleAttributes =@{

                                     NSFontAttributeName :[UIFont fontWithName:@"Helvetica-Bold" size:14.0],

                                     NSForegroundColorAttributeName : [UIColor whiteColor]

                                     };

    navController.navigationBar.titleTextAttributes = titleAttributes;

    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

}

else {

    // do stuff for older versions than iOS 7

    navController.navigationBar.tintColor = [UIColor colorWithRed:88/255.0 green:164/255.0 blue:73/255.0 alpha:1.0];



    navController.navigationItem.titleView.tintColor = [UIColor whiteColor];

}

[self.window makeKeyAndVisible];

For StoryboardSegue Users

UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];

// Go to Login Screen of story board with Identifier name : LoginViewController_Identifier

LoginViewController *loginViewController = (LoginViewController*)[mainStoryboard instantiateViewControllerWithIdentifier:@“LoginViewController_Identifier”];

navigationController = [[UINavigationController alloc] initWithRootViewController:testViewController];

self.window.rootViewController = navigationController;

[self.window makeKeyAndVisible];

// Go To Main screen if you are already Logged In Just check your saving credential here

if([SavedpreferenceForLogin] > 0){
    [loginViewController performSegueWithIdentifier:@"mainview_action" sender:nil];
}

Thanks

How do I use a regex in a shell script?

the problem is you're trying to use regex features not supported by grep. namely, your \d won't work. use this instead:

REGEX_DATE="^[[:digit:]]{2}[-/][[:digit:]]{2}[-/][[:digit:]]{4}$"
echo "$1" | grep -qE "${REGEX_DATE}"
echo $?

you need the -E flag to get ERE in order to use {#} style.

How to set text color in submit button?

you try this:

<input type="submit" style="font-face: 'Comic Sans MS'; font-size: larger; color: teal; background-color: #FFFFC0; border: 3pt ridge lightgrey" value=" Send Me! ">

Best way to check if MySQL results returned in PHP?

$result = $mysqli->query($query);
if($result){
    perform action
}

this is how i do it, you could also throw an else there with a die...

SSRS expression to format two decimal places does not show zeros

Please try the following code snippet,

IIF(Round(Avg(Fields!Vision_Score.Value)) = Avg(Fields!Vision_Score.Value), 
Format(Avg(Fields!Vision_Score.Value)), 
FORMAT(Avg(Fields!Vision_Score.Value),"##.##"))

hope it will help, Thank-you.

SET versus SELECT when assigning variables?

Aside from the one being ANSI and speed etc., there is a very important difference that always matters to me; more than ANSI and speed. The number of bugs I have fixed due to this important overlook is large. I look for this during code reviews all the time.

-- Arrange
create table Employee (EmployeeId int);
insert into dbo.Employee values (1);
insert into dbo.Employee values (2);
insert into dbo.Employee values (3);

-- Act
declare @employeeId int;
select @employeeId = e.EmployeeId from dbo.Employee e;

-- Assert
-- This will print 3, the last EmployeeId from the query (an arbitrary value)
-- Almost always, this is not what the developer was intending. 
print @employeeId; 

Almost always, that is not what the developer is intending. In the above, the query is straight forward but I have seen queries that are quite complex and figuring out whether it will return a single value or not, is not trivial. The query is often more complex than this and by chance it has been returning single value. During developer testing all is fine. But this is like a ticking bomb and will cause issues when the query returns multiple results. Why? Because it will simply assign the last value to the variable.

Now let's try the same thing with SET:

 -- Act
 set @employeeId = (select e.EmployeeId from dbo.Employee e);

You will receive an error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

That is amazing and very important because why would you want to assign some trivial "last item in result" to the @employeeId. With select you will never get any error and you will spend minutes, hours debugging.

Perhaps, you are looking for a single Id and SET will force you to fix your query. Thus you may do something like:

-- Act
-- Notice the where clause
set @employeeId = (select e.EmployeeId from dbo.Employee e where e.EmployeeId = 1);
print @employeeId;

Cleanup

drop table Employee;

In conclusion, use:

  • SET: When you want to assign a single value to a variable and your variable is for a single value.
  • SELECT: When you want to assign multiple values to a variable. The variable may be a table, temp table or table variable etc.

How to insert table values from one database to another database?

If both the tables have the same schema then use this query: insert into database_name.table_name select * from new_database_name.new_table_name where='condition'

Replace database_name with the name of your 1st database and table_name with the name of table you want to copy from also replace new_database_name with the name of your other database where you wanna copy and new_table_name is the name of the table.

How to select some rows with specific rownames from a dataframe?

You can also use this:

DF[paste0("stu",c(2,3,5,9)), ]

"unary operator expected" error in Bash if condition

Took me a while to find this but note that if you have a spacing error you will also get the same error:

[: =: unary operator expected

Correct:

if [ "$APP_ENV" = "staging" ]

vs

if ["$APP_ENV" = "staging" ]

As always setting -x debug variable helps to find these:

set -x

Html.DropDownList - Disabled/Readonly

@Html.DropDownList("Types", Model.Types, new { @disabled = "" })

Works

Detecting superfluous #includes in C/C++?

Also check out include-what-you-use, which solves a similar problem.

How to implement the factory method pattern in C++ correctly

Have you thought about not using a factory at all, and instead making nice use of the type system? I can think of two different approaches which do this sort of thing:

Option 1:

struct linear {
    linear(float x, float y) : x_(x), y_(y){}
    float x_;
    float y_;
};

struct polar {
    polar(float angle, float magnitude) : angle_(angle),  magnitude_(magnitude) {}
    float angle_;
    float magnitude_;
};


struct Vec2 {
    explicit Vec2(const linear &l) { /* ... */ }
    explicit Vec2(const polar &p) { /* ... */ }
};

Which lets you write things like:

Vec2 v(linear(1.0, 2.0));

Option 2:

you can use "tags" like the STL does with iterators and such. For example:

struct linear_coord_tag linear_coord {}; // declare type and a global
struct polar_coord_tag polar_coord {};

struct Vec2 {
    Vec2(float x, float y, const linear_coord_tag &) { /* ... */ }
    Vec2(float angle, float magnitude, const polar_coord_tag &) { /* ... */ }
};

This second approach lets you write code which looks like this:

Vec2 v(1.0, 2.0, linear_coord);

which is also nice and expressive while allowing you to have unique prototypes for each constructor.

Importing files from different folder

From what I know, add an __init__.py file directly in the folder of the functions you want to import will do the job.

How to save local data in a Swift app?

NsUserDefaults saves only small variable sizes. If you want to save many objects you can use CoreData as a native solution, or I created a library that helps you save objects as easy as .save() function. It’s based on SQLite.

SundeedQLite

Check it out and tell me your comments

How to import an Excel file into SQL Server?

You can also use OPENROWSET to import excel file in sql server.

SELECT * INTO Your_Table FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
                        'Excel 12.0;Database=C:\temp\MySpreadsheet.xlsx',
                        'SELECT * FROM [Data$]')

Is the 'as' keyword required in Oracle to define an alias?

My conclusion is that(Tested on 12c):

  • AS is always optional, either with or without ""; AS makes no difference (column alias only, you can not use AS preceding table alias)
  • However, with or without "" does make difference because "" lets lower case possible for an alias

thus :

SELECT {T / t} FROM (SELECT 1 AS T FROM DUAL); -- Correct
SELECT "tEST" FROM (SELECT 1 AS "tEST" FROM DUAL); -- Correct
SELECT {"TEST" / tEST} FROM (SELECT 1 AS "tEST" FROM DUAL ); -- Incorrect

SELECT test_value AS "doggy" FROM test ORDER BY "doggy"; --Correct
SELECT test_value AS "doggy" FROM test WHERE "doggy" IS NOT NULL; --You can not do this, column alias not supported in WHERE & HAVING
SELECT * FROM test "doggy" WHERE "doggy".test_value IS NOT NULL; -- Do not use AS preceding table alias

So, the reason why USING AS AND "" causes problem is NOT AS

Note: "" double quotes are required if alias contains space OR if it contains lower-case characters and MUST show-up in Result set as lower-case chars. In all other scenarios its OPTIONAL and can be ignored.

docker: "build" requires 1 argument. See 'docker build --help'

From the command run:

sudo docker build -t myrepo/redis

there are no "arguments" passed to the docker build command, only a single flag -t and a value for that flag. After docker parses all of the flags for the command, there should be one argument left when you're running a build.

That argument is the build context. The standard command includes a trailing dot for the context:

sudo docker build -t myrepo/redis .

What's the build context?

Every docker build sends a directory to the build server. Docker is a client/server application, and the build runs on the server which isn't necessarily where the docker command is run. Docker uses the build context as the source for files used in COPY and ADD steps. When you are in the current directory to run the build, you would pass a . for the context, aka the current directory. You could pass a completely different directory, even a git repo, and docker will perform the build using that as the context, e.g.:

docker build -t sudobmitch/base:alpine --target alpine-base \
  'https://github.com/sudo-bmitch/docker-base.git#main'

For more details on these options to the build command, see the docker build documentation.

What if you included an argument?

If you are including the value for the build context (typically the .) and still see this error message, you have likely passed more than one argument. Typically this is from failing to parse a flag, or passing a string with spaces without quotes. Possible causes for docker to see more than one argument include:

  • Missing quotes around a path or argument with spaces (take note using variables that may have spaces in them)

  • Incorrect dashes in the command: make sure to type these manually rather than copy and pasting

  • Incorrect quotes: smart quotes don't work on the command line, type them manually rather than copy and pasting.

  • Whitespace that isn't white space, or that doesn't appear to be a space.

Most all of these come from either a typo or copy and pasting from a source that modified the text to look pretty, breaking it for using as a command.

How do you figure out where the CLI error is?

The easiest way I have to debug this, run the command without any other flags:

docker build .

Once that works, add flags back in until you get the error, and then you'll know what flag is broken and needs the quotes to be fixed/added or dashes corrected, etc.

How to make java delay for a few seconds?

You need to use the Thread.sleep() method.

This is used to pause the execution of current thread for specified time in milliseconds. The argument value for milliseconds can’t be negative, else it throws IllegalArgumentException.

FYI (Summary taken from here)

Java Thread Sleep important points

  • It always pause the current thread execution.
  • Thread sleep doesn’t lose any monitors or locks current thread has acquired.
  • Any other thread can interrupt the current thread in sleep, in that case InterruptedException is thrown.

what is the difference between ajax and jquery and which one is better?

It's really not an 'either/or' situation. AJAX stands for Asynchronous JavaScript and XML, and JQuery is a JavaScript library that takes the pain out of writing common JavaScript routines.

It's the difference between a thing (jQuery) and a process (AJAX). To compare them would be to compare apples and oranges.

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

This helped me out after reading @Mr-Faizan's and other answers.

Untick the 'Enable foreign key checks'

in phpMyAdmin and hit the query. I don't know about WorkBench but the other answers might help you out.

Make a directory and copy a file

Use the FileSystemObject object, namely, its CreateFolder and CopyFile methods. Basically, this is what your script will look like:

Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")

' Create a new folder
oFSO.CreateFolder "C:\MyFolder"

' Copy a file into the new folder
' Note that the destination folder path must end with a path separator (\)
oFSO.CopyFile "\\server\folder\file.ext", "C:\MyFolder\"

You may also want to add additional logic, like checking whether the folder you want to create already exists (because CreateFolder raises an error in this case) or specifying whether or not to overwrite the file being copied. So, you can end up with this:

Const strFolder = "C:\MyFolder\", strFile = "\\server\folder\file.ext"
Const Overwrite = True
Dim oFSO

Set oFSO = CreateObject("Scripting.FileSystemObject")

If Not oFSO.FolderExists(strFolder) Then
  oFSO.CreateFolder strFolder
End If

oFSO.CopyFile strFile, strFolder, Overwrite

Ruby 2.0.0p0 IRB warning: "DL is deprecated, please use Fiddle"

I got this resolution at openshift.com.

Resolution:

This error occurs only on Windows machine with Ruby 2.0.0 version. Until we officially support Ruby 2.0 please downgrade to Ruby 1.9.

On Windows, you can install Ruby 1.9.3 alongside 2.0. Change your %PATH% to c:\ruby193\ or whatever directory you installed to prior to installing the gem.

Changing the Git remote 'push to' default

You can easily change default remote for branches all at once simple using this command

git push -u <remote_name> --all

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

None of the above worked out for me until I changed the Action as [HttpPost]. and made the ajax type as POST.

    [HttpPost]
    public JsonResult GetSelectedSignalData(string signal1,...)
    {
         JsonResult result = new JsonResult();
         var signalData = GetTheData();
         try
         {
              var serializer = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue, RecursionLimit = 100 };

            result.Data = serializer.Serialize(signalData);
            return Json(result, JsonRequestBehavior.AllowGet);
            ..
            ..
            ...

    }

And the ajax call as

$.ajax({
    type: "POST",
    url: some_url,
    data: JSON.stringify({  signal1: signal1,.. }),
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        if (data !== null) {
            setValue();
        }

    },
    failure: function (data) {
        $('#errMessage').text("Error...");
    },
    error: function (data) {
        $('#errMessage').text("Error...");
    }
});

How do I clone a github project to run locally?

git clone git://github.com/ryanb/railscasts-episodes.git

Validate phone number using angular js

<div ng-class="{'has-error': userForm.mobileno.$error.pattern ,'has-success': userForm.mobileno.$valid}">

              <input type="text" name="mobileno" ng-model="mobileno" ng-pattern="/^[7-9][0-9]{9}$/"  required>

Here "userForm" is my form name.

jQuery .find() on data from .ajax() call is returning "[object Object]" instead of div

You should add dataType: "html" to the request. Im quite sure you wont be able to search the DOM of the returned html if it doesnt know it is html.

How to calculate cumulative normal distribution?

Here's an example:

>>> from scipy.stats import norm
>>> norm.cdf(1.96)
0.9750021048517795
>>> norm.cdf(-1.96)
0.024997895148220435

In other words, approximately 95% of the standard normal interval lies within two standard deviations, centered on a standard mean of zero.

If you need the inverse CDF:

>>> norm.ppf(norm.cdf(1.96))
array(1.9599999999999991)

PHP fwrite new line

Use PHP_EOL which produces \r\n or \n

$data = 'my data' . PHP_EOL . 'my data';
$fp = fopen('my_file', 'a');
fwrite($fp, $data);
fclose($fp);

// File output

my data
my data

How do I rename the extension for a bunch of files?

This is a good way to modify multiple extensions at once:

for fname in *.{mp4,avi}
do
   mv -v "$fname" "${fname%.???}.mkv"
done

Note: be careful at the extension size to be the same (the ???)

Iterating through all nodes in XML file

I think the fastest and simplest way would be to use an XmlReader, this will not require any recursion and minimal memory foot print.

Here is a simple example, for compactness I just used a simple string of course you can use a stream from a file etc.

  string xml = @"
    <parent>
      <child>
        <nested />
      </child>
      <child>
        <other>
        </other>
      </child>
    </parent>
    ";

  XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));
  while (rdr.Read())
  {
    if (rdr.NodeType == XmlNodeType.Element)
    {
      Console.WriteLine(rdr.LocalName);
    }
  }

The result of the above will be

parent
child
nested
child
other

A list of all the elements in the XML document.

Show default value in Spinner in android

Spinner don't support Hint, i recommend you to make a custom spinner adapter.

check this link : https://stackoverflow.com/a/13878692/1725748

Best way to get child nodes

Just to add to the other answers, there are still noteworthy differences here, specifically when dealing with <svg> elements.

I have used both .childNodes and .children and have preferred working with the HTMLCollection delivered by the .children getter.

Today however, I ran into issues with IE/Edge failing when using .children on an <svg>. While .children is supported in IE on basic HTML elements, it isn't supported on document/document fragments, or SVG elements.

For me, I was able to simply grab the needed elements via .childNodes[n] because I don't have extraneous text nodes to worry about. You may be able to do the same, but as mentioned elsewhere above, don't forget that you may run into unexpected elements.

Hope this is helpful to someone scratching their head trying to figure out why .children works elsewhere in their js on modern IE and fails on document or SVG elements.

Angularjs on page load call function

Instead of using onload, use Angular's ng-init.

<article id="showSelector" ng-controller="CinemaCtrl" ng-init="myFunction()">

Note: This requires that myFunction is a property of the CinemaCtrl scope.

Android screen size HDPI, LDPI, MDPI

The documentation is quite sketchy as far as definitive resolutions go. After some research, here's the solution I came to: Android splash screen image sizes to fit all devices

It's basically guided towards splash screens, but it's perfectly applicable to images that should occupy full screen.

CSS background image to fit width, height should auto-scale in proportion

Here's what worked for me:

background-size: auto 100%;

Error: class X is public should be declared in a file named X.java

when you named your file WeatherArray.java,maybe you have another file on hard disk ,so you can rename WeatherArray.java as ReWeatherArray.java, then rename ReWeatherArray.java as WeatherArray.java. it will be ok.

Is it possible to open a Windows Explorer window from PowerShell?

Just use the Invoke-Item cmdlet. For example, if you want to open a explorer window on the current directory you can do:

Invoke-Item .

How to draw circle in html page?

You can use the border-radius attribute to give it a border-radius equivalent to the element's border-radius. For example:

<div style="border-radius 10px; -moz-border-radius 10px; -webkit-border-radius 10px; width: 20px; height: 20px; background: red; border: solid black 1px;">&nbsp;</div>

(The reason for using the -moz and -webkit extensions is to support pre-CSS3-final versions of Gecko and Webkit.)

There are more examples on this page. As far as inserting text, you can do it but you have to be mindful of the positioning, as most browsers' box padding model still uses the outer square.

Get Memory Usage in Android

I use this function to calculate cpu usage. Hope it can help you.

private float readUsage() {
    try {
        RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
        String load = reader.readLine();

        String[] toks = load.split(" +");  // Split on one or more spaces

        long idle1 = Long.parseLong(toks[4]);
        long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5])
              + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        try {
            Thread.sleep(360);
        } catch (Exception e) {}

        reader.seek(0);
        load = reader.readLine();
        reader.close();

        toks = load.split(" +");

        long idle2 = Long.parseLong(toks[4]);
        long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5])
            + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        return (float)(cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return 0;
} 

Embed ruby within URL : Middleman Blog

<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %>   <i class="fa fa-facebook">     Facebook Share    </i> <%end%> 

I am assuming that current_article_url is http://0.0.0.0:4567/link_to_title

SonarQube not picking up Unit Test Coverage

I was facing the same problem and the challenge in my case was to configure Jacoco correctly and to configure the right parameters for Sonar. I will briefly explain, how I finally got SonarQube to display the test results and test coverage correctly.

In your project you need the Jacoco plugin in your pom or parent pom (you already got this). Moreover, you need the maven-surefire-plugin, which is used to display test results. All test reports are automatically generated when you run the maven build. The tricky part is to find the right parameters for Sonar. Not all parameters seem to work with regular expressions and you have to use a comma separated list for those (documentation is not really good in my opinion). Here is the list of parameters I have used (I used them from Bamboo, you might omit the "-D" if you use a sonar.properties file):

-Dsonar.branch.target=master (in newer version of SQ I had to remove this, so that master branch is analyzed correctly; I used auto branch checkbox in bamboo instead)
-Dsonar.working.directory=./target/sonar
-Dsonar.java.binaries=**/target/classes
-Dsonar.sources=./service-a/src,./service-b/src,./service-c/src,[..]
-Dsonar.exclusions=**/data/dto/**
-Dsonar.tests=.
-Dsonar.test.inclusions=**/*Test.java [-> all your tests have to end with "Test"]
-Dsonar.junit.reportPaths=./service-a/target/surefire-reports,./service-b/target/surefire-reports,
./service-c/target/surefire-reports,[..]
-Dsonar.jacoco.reportPaths=./service-a/target/jacoco.exec,./service-b/target/jacoco.exec,
./service-c/target/jacoco.exec,[..]
-Dsonar.projectVersion=${bamboo.buildNumber}
-Dsonar.coverage.exclusions=**/src/test/**,**/common/**
-Dsonar.cpd.exclusions=**/*Dto.java,**/*Entity.java,**/common/**

If you are using Lombok in your project, than you also need a lombok.config file to get the correct code coverage. The lombok.config file is located in the root directory of your project with the following content:

config.stopBubbling = true
lombok.addLombokGeneratedAnnotation = true

How to create a directory if it doesn't exist using Node.js?

The mkdir method has the ability to recursively create any directories in a path that don't exist, and ignore the ones that do.

From the Node v10/11 docs:

// Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.
fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
    if (err) throw err;
});

NOTE: You'll need to import the built-in fs module first.

Now here's a little more robust example that leverages native ES Modules (with flag enabled and .mjs extension), handles non-root paths, and accounts for full pathnames:

import fs from 'fs';
import path from 'path';

createDirectories(pathname) {
   const __dirname = path.resolve();
   pathname = pathname.replace(/^\.*\/|\/?[^\/]+\.[a-z]+|\/$/g, ''); // Remove leading directory markers, and remove ending /file-name.extension
   fs.mkdir(path.resolve(__dirname, pathname), { recursive: true }, e => {
       if (e) {
           console.error(e);
       } else {
           console.log('Success');
       }
    });
}

You can use it like createDirectories('/components/widget/widget.js');.

And of course, you'd probably want to get more fancy by using promises with async/await to leverage file creation in a more readable synchronous-looking way when the directories are created; but, that's beyond the question's scope.

Call multiple functions onClick ReactJS

this onclick={()=>{ f1(); f2() }} helped me a lot if i want two different functions at the same time. But now i want to create an audiorecorder with only one button. So if i click first i want to run the StartFunction f1() and if i click again then i want to run StopFunction f2().

How do you guys realize this?

What is the difference between aggregation, composition and dependency?

Aggregation and composition are terms that most people in the OO world have acquired via UML. And UML does a very poor job at defining these terms, as has been demonstrated by, for example, Henderson-Sellers and Barbier ("What is This Thing Called Aggregation?", "Formalization of the Whole-Part Relationship in the Unified Modeling Language"). I don't think that a coherent definition of aggregation and composition can be given if you are interested in being UML-compliant. I suggest you look at the cited works.

Regarding dependency, that's a highly abstract relationship between types (not objects) that can mean almost anything.

How do I delete specific lines in Notepad++?

Notepad++ v6.5

  1. Search menu -> Find... -> Mark tab -> Find what: your search text, check Bookmark Line, then Mark All. This will bookmark all the lines with the search term, you'll see the blue circles in the margin.

  2. Then Search menu -> Bookmark -> Remove Bookmarked Lines. This will delete all the bookmarked lines.

You can also use a regex to search. This method won't result in a blank line like John's and will actually delete the line.

Older Versions

  1. Search menu -> Find... -> Find what: your search text, check Bookmark Line and click Find All.
  2. Then Search -> Bookmark -> Remove Bookmarked Lines

How can I view all historical changes to a file in SVN

Start with

svn log -q file | grep '^r' | cut -f1 -d' '

That will get you a list of revisions where the file changed, which you can then use to script repeated calls to svn diff.

Where can I find php.ini?

For SAPI: php-fpm

There is no need to create a php.info file (it is not a good policy to leave it for the world to read anyway). On the command line:

php-fpm -i | more

Somewhere in its output, it will show this line:

Configuration File (php.ini) Path => /etc

Here is a more complete explanation: https://www.cloudinsidr.com/content/how-to-figure-out-your-php-configuration-parameters-without-info-php/

Cannot resolve method 'getSupportFragmentManager ( )' inside Fragment

I tried all above, but none working

Finally tried this my own

getBaseActivity().getFragmentManager()

and is working .. :)

What is the difference between DTR/DSR and RTS/CTS flow control?

An important difference is that some UARTs (16550 notably) will stop receiving characters immediately if their host instructs them to set DSR to be inactive. In contrast, characters will still be received if CTS is inactive. I believe that the intention here is that DSR indicates that the device is no longer listening and so sending any further characters is pointless, while CTS indicates that a buffer is getting full; the latter allows for a certain amount of 'skid' where the flow control line changed state between the DTE sampling it and the next character being transmitted. In (relatively) later devices that support a hardware FIFO it's possible that a number of characters could be transmitted after the DCE has set CTS to be inactive.

Re-doing a reverted merge in Git

You have to "revert the revert". Depending on you how did the original revert, it may not be as easy as it sounds. Look at the official document on this topic.

---o---o---o---M---x---x---W---x---Y
              /
      ---A---B-------------------C---D

to allow:

---o---o---o---M---x---x-------x-------*
              /                       /
      ---A---B-------------------C---D

But does it all work? Sure it does. You can revert a merge, and from a purely technical angle, git did it very naturally and had no real troubles.
It just considered it a change from "state before merge" to "state after merge", and that was it.
Nothing complicated, nothing odd, nothing really dangerous. Git will do it without even thinking about it.

So from a technical angle, there's nothing wrong with reverting a merge, but from a workflow angle it's something that you generally should try to avoid.

If at all possible, for example, if you find a problem that got merged into the main tree, rather than revert the merge, try really hard to:

  • bisect the problem down into the branch you merged, and just fix it,
  • or try to revert the individual commit that caused it.

Yes, it's more complex, and no, it's not always going to work (sometimes the answer is: "oops, I really shouldn't have merged it, because it wasn't ready yet, and I really need to undo all of the merge"). So then you really should revert the merge, but when you want to re-do the merge, you now need to do it by reverting the revert.

Converting a Uniform Distribution to a Normal Distribution

I would use Box-Muller. Two things about this:

  1. You end up with two values per iteration
    Typically, you cache one value and return the other. On the next call for a sample, you return the cached value.
  2. Box-Muller gives a Z-score
    You have to then scale the Z-score by the standard deviation and add the mean to get the full value in the normal distribution.

Android Color Picker

Here's another library:

https://github.com/eltos/SimpleDialogFragments

Features color wheel and pallet picker dialogs

How to fix Python Numpy/Pandas installation?

I had the same problem and, in my case, the problem was that python was looking for packages in some ordered locations, first of all the default computer one where default old packages are.

To check what your python is looking for you can do:

>>> import sys
>>> print '\n'.join(sys.path)

This was outputting the directory '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python' before pip or brew or port folders.

The simple solution is:

export PYTHONPATH="/Library/Python/2.7/site-packages:$PYTHONPATH"

This worked well for me, I advise you to add this line to your home bash_profile file for the next time. Remember that sys.path is built using the current working directory, followed by the directories in the PYTHONPATH environment variable. Then there are the installation-dependent default dirs.

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

This error can also occur in the normal situation when a database is starting or stopping. Normally on startup you can wait until the startup completes, then connect as usual. If the error persists, the service (on a Windows box) may be started without the database being started. This may be due to startup issues, or because the service is not configured to automatically start the database. In this case you will have to connect as sysdba and physically start the database using the "startup" command.

Git: can't undo local changes (error: path ... is unmerged)

I find git stash very useful for temporal handling of all 'dirty' states.

are there dictionaries in javascript like python?

I realize this is an old question, but it pops up in Google when you search for 'javascript dictionaries', so I'd like to add to the above answers that in ECMAScript 6, the official Map object has been introduced, which is a dictionary implementation:

var dict = new Map();
dict.set("foo", "bar");

//returns "bar"
dict.get("foo");

Unlike javascript's normal objects, it allows any object as a key:

var foo = {};
var bar = {};
var dict = new Map();
dict.set(foo, "Foo");
dict.set(bar, "Bar");

//returns "Bar"
dict.get(bar);

//returns "Foo"
dict.get(foo);

//returns undefined, as {} !== foo and {} !== bar
dict.get({});

Django: Model Form "object has no attribute 'cleaned_data'"

I would write the code like this:

def search_book(request):
    form = SearchForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        stitle = form.cleaned_data['title']
        sauthor = form.cleaned_data['author']
        scategory = form.cleaned_data['category']
        return HttpResponseRedirect('/thanks/')
    return render_to_response("books/create.html", {
        "form": form,
    }, context_instance=RequestContext(request))

Pretty much like the documentation.

Oracle PL Sql Developer cannot find my tnsnames.ora file

I had the same problema, but as described in the manual.pdf, you have to:

You are using an Oracle Instant Client but have not set all required environment variables:

  • PATH: Needs to include the Instant Client directory where oci.dll is located
  • TNS_ADMIN: Needs to point to the directory where tnsnames.ora is located.
  • NLS_LANG: Defines the language, territory, and character set for the client.

Regards

Given two directory trees, how can I find out which files differ by content?

You can also use Rsync and find. For find:

find $FOLDER -type f | cut -d/ -f2- | sort > /tmp/file_list_$FOLDER

But files with the same names and in the same subfolders, but with different content, will not be shown in the lists.

If you are a fan of GUI, you may check Meld that @Alexander mentioned. It works fine in both windows and linux.

How to count the NaN values in a column in pandas DataFrame

Since pandas 0.14.1 my suggestion here to have a keyword argument in the value_counts method has been implemented:

import pandas as pd
df = pd.DataFrame({'a':[1,2,np.nan], 'b':[np.nan,1,np.nan]})
for col in df:
    print df[col].value_counts(dropna=False)

2     1
 1     1
NaN    1
dtype: int64
NaN    2
 1     1
dtype: int64

Running Selenium Webdriver with a proxy in Python

My solution:

def my_proxy(PROXY_HOST,PROXY_PORT):
        fp = webdriver.FirefoxProfile()
        # Direct = 0, Manual = 1, PAC = 2, AUTODETECT = 4, SYSTEM = 5
        print PROXY_PORT
        print PROXY_HOST
        fp.set_preference("network.proxy.type", 1)
        fp.set_preference("network.proxy.http",PROXY_HOST)
        fp.set_preference("network.proxy.http_port",int(PROXY_PORT))
        fp.set_preference("general.useragent.override","whater_useragent")
        fp.update_preferences()
        return webdriver.Firefox(firefox_profile=fp)

Then call in your code:

my_proxy(PROXY_HOST,PROXY_PORT)

I had issues with this code because I was passing a string as a port #:

 PROXY_PORT="31280"

This is important:

int("31280")

You must pass an integer instead of a string or your firefox profile will not be set to a properly port and connection through proxy will not work.

How to convert the following json string to java object?

Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(response);// response will be the json String
YourPojo emp = gson.fromJson(object, YourPojo.class); 

How to restart remote MySQL server running on Ubuntu linux?

  1. SSH into the machine. Using the proper credentials and ip address, ssh [email protected]. This should provide you with shell access to the Ubuntu server.
  2. Restart the mySQL service. sudo service mysql restart should do the job.

If your mySQL service is named something else like mysqld you may have to change the command accordingly or try this: sudo /etc/init.d/mysql restart

Sorting Characters Of A C++ String

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

See here

Getting MAC Address

One other thing that you should note is that uuid.getnode() can fake the MAC addr by returning a random 48-bit number which may not be what you are expecting. Also, there's no explicit indication that the MAC address has been faked, but you could detect it by calling getnode() twice and seeing if the result varies. If the same value is returned by both calls, you have the MAC address, otherwise you are getting a faked address.

>>> print uuid.getnode.__doc__
Get the hardware address as a 48-bit positive integer.

    The first time this runs, it may launch a separate program, which could
    be quite slow.  If all attempts to obtain the hardware address fail, we
    choose a random 48-bit number with its eighth bit set to 1 as recommended
    in RFC 4122.

Why I've got no crontab entry on OS X when using vim?

I've never had this problem, but I create a ~/.crontab file and edit that (which allows me to back it up, Time Machine or otherwise), then run

crontab ~/.crontab

Has worked for me for 20+ years across many flavors of unix.

String.Format for Hex

If we have built in functions to convert your integer values to COLOR then why to worry.

string hexValue = string.Format("{0:X}", intColor);

Color brushes = System.Drawing.ColorTranslator.FromHtml("#"+hexValue);

What is JavaScript garbage collection?

"In computer science, garbage collection (GC) is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory used by objects that will never be accessed or mutated again by the application."

All JavaScript engines have their own garbage collectors, and they may differ. Most time you do not have to deal with them because they just do what they supposed to do.

Writing better code mostly depends of how good do you know programming principles, language and particular implementation.

iPhone system font

If you're doing programatic customisation, don't hard code the system font. Use UIFont systemFontOfSize:, UIFont boldSystemFontOfSize: and UIFont italicSystemFontOfSize (Apple documentation).

This has become especially relevant since iOS 7, which changed the system font to Helvetica Neue.

This has become super especially relevant since iOS 9, which changed the system font again to San Francisco.

Convert .cer certificate to .jks

Just to be sure that this is really the "conversion" you need, please note that jks files are keystores, a file format used to store more than one certificate and allows you to retrieve them programmatically using the Java security API, it's not a one-to-one conversion between equivalent formats.

So, if you just want to import that certificate in a new ad-hoc keystore you can do it with Keystore Explorer, a graphical tool. You'll be able to modify the keystore and the certificates contained therein like you would have done with the java terminal utilities like keytool (but in a more accessible way).

Check whether a variable is a string in Ruby

foo.instance_of? String

or

foo.kind_of? String 

if you you only care if it is derrived from String somewhere up its inheritance chain

XMLHttpRequest status 0 (responseText is empty)

To see what the problem is, when you get the cryptic error 0 go to ... | More Tools | Developer Tools (Ctrl+Shift+I) in Chrome (on the page giving the error)

Read the red text in the log to get the true error message. If there is too much in there, right-click and Clear Console, then do your last request again.

My first problem was, I was passing in Authorization headers to my own cross-domain web service for the browser for the first time.

I already had:

Access-Control-Allow-Origin: *

But not:

Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization

in the response header of my web service.

After I added that, my error zero was gone from my own web server, as well as when running the index.html file locally without a web server, but was still giving errors in code pen.

Back to ... | More Tools | Developer Tools while getting the error in codepen, and there is clearly explained: codepen uses https, so I cannot make calls to http, as the security is lower.

I need to therefore host my web service on https.

Knowing how to get the true error message - priceless!

Regex select all text between tags

You shouldn't be trying to parse html with regexes see this question and how it turned out.

In the simplest terms, html is not a regular language so you can't fully parse is with regular expressions.

Having said that you can parse subsets of html when there are no similar tags nested. So as long as anything between and is not that tag itself, this will work:

preg_match("/<([\w]+)[^>]*>(.*?)<\/\1>/", $subject, $matches);
$matches = array ( [0] => full matched string [1] => tag name [2] => tag content )

A better idea is to use a parser, like the native DOMDocument, to load your html, then select your tag and get the inner html which might look something like this:

$obj = new DOMDocument();
$obj -> load($html);
$obj -> getElementByTagName('el');
$value = $obj -> nodeValue();

And since this is a proper parser it will be able to handle nesting tags etc.

Generating random numbers in Objective-C

This will give you a floating point number between 0 and 47

float low_bound = 0;      
float high_bound = 47;
float rndValue = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);

Or just simply

float rndValue = (((float)arc4random()/0x100000000)*47);

Both lower and upper bound can be negative as well. The example code below gives you a random number between -35.76 and +12.09

float low_bound = -35.76;      
float high_bound = 12.09;
float rndValue = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);

Convert result to a rounder Integer value:

int intRndValue = (int)(rndValue + 0.5);

Unstaged changes left after git reset --hard

I had the same problem and it was related to the .gitattributes file. However the file type that caused the problem was not specified in the .gitattributes.

I was able to solve the issue by simply running

git rm .gitattributes
git add -A
git reset --hard

Is there a program to decompile Delphi?

You can use IDR it is a great program to decompile Delphi, it is updated to the current Delphi versions and it has a lot of features.

Seedable JavaScript random number generator

If you program in Typescript, I adapted the Mersenne Twister implementation that was brought in Christoph Henkelmann's answer to this thread as a typescript class:

/**
 * copied almost directly from Mersenne Twister implementation found in https://gist.github.com/banksean/300494
 * all rights reserved to him.
 */
export class Random {
    static N = 624;
    static M = 397;
    static MATRIX_A = 0x9908b0df;
    /* constant vector a */
    static UPPER_MASK = 0x80000000;
    /* most significant w-r bits */
    static LOWER_MASK = 0x7fffffff;
    /* least significant r bits */

    mt = new Array(Random.N);
    /* the array for the state vector */
    mti = Random.N + 1;
    /* mti==N+1 means mt[N] is not initialized */

    constructor(seed:number = null) {
        if (seed == null) {
            seed = new Date().getTime();
        }

        this.init_genrand(seed);
    }

    private init_genrand(s:number) {
        this.mt[0] = s >>> 0;
        for (this.mti = 1; this.mti < Random.N; this.mti++) {
            var s = this.mt[this.mti - 1] ^ (this.mt[this.mti - 1] >>> 30);
            this.mt[this.mti] = (((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253)
                + this.mti;
            /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
            /* In the previous versions, MSBs of the seed affect   */
            /* only MSBs of the array mt[].                        */
            /* 2002/01/09 modified by Makoto Matsumoto             */
            this.mt[this.mti] >>>= 0;
            /* for >32 bit machines */
        }
    }

    /**
     * generates a random number on [0,0xffffffff]-interval
     * @private
     */
    private _nextInt32():number {
        var y:number;
        var mag01 = new Array(0x0, Random.MATRIX_A);
        /* mag01[x] = x * MATRIX_A  for x=0,1 */

        if (this.mti >= Random.N) { /* generate N words at one time */
            var kk:number;

            if (this.mti == Random.N + 1)   /* if init_genrand() has not been called, */
                this.init_genrand(5489);
            /* a default initial seed is used */

            for (kk = 0; kk < Random.N - Random.M; kk++) {
                y = (this.mt[kk] & Random.UPPER_MASK) | (this.mt[kk + 1] & Random.LOWER_MASK);
                this.mt[kk] = this.mt[kk + Random.M] ^ (y >>> 1) ^ mag01[y & 0x1];
            }
            for (; kk < Random.N - 1; kk++) {
                y = (this.mt[kk] & Random.UPPER_MASK) | (this.mt[kk + 1] & Random.LOWER_MASK);
                this.mt[kk] = this.mt[kk + (Random.M - Random.N)] ^ (y >>> 1) ^ mag01[y & 0x1];
            }
            y = (this.mt[Random.N - 1] & Random.UPPER_MASK) | (this.mt[0] & Random.LOWER_MASK);
            this.mt[Random.N - 1] = this.mt[Random.M - 1] ^ (y >>> 1) ^ mag01[y & 0x1];

            this.mti = 0;
        }

        y = this.mt[this.mti++];

        /* Tempering */
        y ^= (y >>> 11);
        y ^= (y << 7) & 0x9d2c5680;
        y ^= (y << 15) & 0xefc60000;
        y ^= (y >>> 18);

        return y >>> 0;
    }

    /**
     * generates an int32 pseudo random number
     * @param range: an optional [from, to] range, if not specified the result will be in range [0,0xffffffff]
     * @return {number}
     */
    nextInt32(range:[number, number] = null):number {
        var result = this._nextInt32();
        if (range == null) {
            return result;
        }

        return (result % (range[1] - range[0])) + range[0];
    }

    /**
     * generates a random number on [0,0x7fffffff]-interval
     */
    nextInt31():number {
        return (this._nextInt32() >>> 1);
    }

    /**
     * generates a random number on [0,1]-real-interval
     */
    nextNumber():number {
        return this._nextInt32() * (1.0 / 4294967295.0);
    }

    /**
     * generates a random number on [0,1) with 53-bit resolution
     */
    nextNumber53():number {
        var a = this._nextInt32() >>> 5, b = this._nextInt32() >>> 6;
        return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0);
    }
}

you can than use it as follows:

var random = new Random(132);
random.nextInt32(); //return a pseudo random int32 number
random.nextInt32([10,20]); //return a pseudo random int in range [10,20]
random.nextNumber(); //return a a pseudo random number in range [0,1]

check the source for more methods.

Getting scroll bar width using JavaScript

Assuming container is only on page once and you are using jQuery, then:

var containerEl = $('.container')[0];
var scrollbarWidth = containerEl.offsetWidth - containerEl.clientWidth;

Also see this answer for more details.

base64 encoded images in email signatures

Recently I had the same problem to include QR image/png in email. The QR image is a byte array which is generated using ZXing. We do not want to save it to a file because saving/reading from a file is too expensive (slow). So both of the answers above do not work for me. Here's what I did to solve this problem:

import javax.mail.util.ByteArrayDataSource;
import org.apache.commons.mail.ImageHtmlEmail;
...
ImageHtmlEmail email = new ImageHtmlEmail();
byte[] qrImageBytes = createQRCode(); // get your image byte array
ByteArrayDataSource qrImageDataSource = new ByteArrayDataSource(qrImageBytes, "image/png");
String contentId = email.embed(qrImageDataSource, "QR Image");

Let's say the contentId is "111122223333", then your HTML part should have this:

<img src="cid: 111122223333">

There's no need to convert the byte array to Base64 because Commons Mail does the conversion for you automatically. Hope this helps.

no module named zlib

For the case I met, I found there are missing modules after make. So I did the following:

  1. install zlib-devel
  2. make and install python again.

Floating divs in Bootstrap layout

From all I have read you cannot do exactly what you want without javascript. If you float left before text

<div style="float:left;">widget</div> here is some CONTENT, etc.

Your content wraps as expected. But your widget is in the top left. If you instead put the float after the content

here is some CONTENT, etc. <div style="float:left;">widget</div>

Then your content will wrap the last line to the right of the widget if the last line of content can fit to the right of the widget, otherwise no wrapping is done. To make borders and backgrounds actually include the floated area in the previous example, most people add:

here is some CONTENT, etc. <div style="float:left;">widget</div><div style="clear:both;"></div>

In your question you are using bootstrap which just adds row-fluid::after { content: ""} which resolves the border/background issue.

Moving your content up will give you the one line wrap : http://jsfiddle.net/jJNPY/34/

  <div class="container-fluid">
  <div class="row-fluid">
    <div class="offset1 span8 pull-right">
    ... Widget 1...
    </div>
    .... a lot of content ....
    <div class="span8" style="margin-left: 0;">
    ... Widget 2...
    </div>


  </div>

</div><!--/.fluid-container-->

Excel column number from column name

I think you want this?

Column Name to Column Number

Sub Sample()
    ColName = "C"
    Debug.Print Range(ColName & 1).Column
End Sub

Edit: Also including the reverse of what you want

Column Number to Column Name

Sub Sample()
    ColNo = 3
    Debug.Print Split(Cells(, ColNo).Address, "$")(1)
End Sub

FOLLOW UP

Like if i have salary field at the very top lets say at cell C(1,1) now if i alter the file and shift salary column to some other place say F(1,1) then i will have to modify the code so i want the code to check for Salary and find the column number and then do rest of the operations according to that column number.

In such a case I would recommend using .FIND See this example below

Option Explicit

Sub Sample()
    Dim strSearch As String
    Dim aCell As Range

    strSearch = "Salary"

    Set aCell = Sheet1.Rows(1).Find(What:=strSearch, LookIn:=xlValues, _
    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)

    If Not aCell Is Nothing Then
        MsgBox "Value Found in Cell " & aCell.Address & _
        " and the Cell Column Number is " & aCell.Column
    End If
End Sub

SNAPSHOT

enter image description here

android start activity from service

UPDATE ANDROID 10 AND HIGHER

Start an activity from service (foreground or background) is no longer allowed.

There are still some restrictions that can be seen in the documentation

https://developer.android.com/guide/components/activities/background-starts

Copying and pasting data using VBA code

'So from this discussion i am thinking this should be the code then.

Sub Button1_Click()
    Dim excel As excel.Application
    Dim wb As excel.Workbook
    Dim sht As excel.Worksheet
    Dim f As Object

    Set f = Application.FileDialog(3)
    f.AllowMultiSelect = False
    f.Show

    Set excel = CreateObject("excel.Application")
    Set wb = excel.Workbooks.Open(f.SelectedItems(1))
    Set sht = wb.Worksheets("Data")

    sht.Activate
    sht.Columns("A:G").Copy
    Range("A1").PasteSpecial Paste:=xlPasteValues


    wb.Close
End Sub

'Let me know if this is correct or a step was missed. Thx.

How to replace a hash key with another key

Answering exactly what was asked:

hash = {"_id"=>"4de7140772f8be03da000018"}
hash.transform_keys { |key| key[1..] }
# => {"id"=>"4de7140772f8be03da000018"}

The method transform_keys exists in the Hash class since Ruby version 2.5.

https://blog.bigbinary.com/2018/01/09/ruby-2-5-adds-hash-transform_keys-method.html

How to force JS to do math instead of putting two strings together

You have the line

dots = document.getElementById("txt").value;

in your file, this will set dots to be a string because the contents of txt is not restricted to a number.

to convert it to an int change the line to:

dots = parseInt(document.getElementById("txt").value, 10);

Note: The 10 here specifies decimal (base-10). Without this some browsers may not interpret the string correctly. See MDN: parseInt.

How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file

In CSS, for the font-weight property, the value: normal defaults to the numeric value 400, and bold to 700.

If you want to specify other weights, you need to give the number value. That number value needs to be supported for the font family that you are using.

For example you would define semi-bold like this:

font-weight: 600;

Here an JSFiddle using 'Open Sans' font family, loaded with the above weights.

Batch File; List files in directory, only filenames?

The full command is:

dir /b /a-d

Let me break it up;

Basically the /b is what you look for.

/a-d will exclude the directory names.


For more information see dir /? for other arguments that you can use with the dir command.

MS SQL 2008 - get all table names and their row counts in a DB

SELECT sc.name +'.'+ ta.name TableName
 ,SUM(pa.rows) RowCnt
 FROM sys.tables ta
 INNER JOIN sys.partitions pa
 ON pa.OBJECT_ID = ta.OBJECT_ID
 INNER JOIN sys.schemas sc
 ON ta.schema_id = sc.schema_id
 WHERE ta.is_ms_shipped = 0 AND pa.index_id IN (1,0)
 GROUP BY sc.name,ta.name
 ORDER BY SUM(pa.rows) DESC

See this:

Convert byte to string in Java

If it's a single byte, just cast the byte to a char and it should work out to be fine i.e. give a char entity corresponding to the codepoint value of the given byte. If not, use the String constructor as mentioned elsewhere.

char ch = (char)0x63;
System.out.println(ch);

Using GroupBy, Count and Sum in LINQ Lambda Expressions

        var q = from b in listOfBoxes
                group b by b.Owner into g
                select new
                           {
                               Owner = g.Key,
                               Boxes = g.Count(),
                               TotalWeight = g.Sum(item => item.Weight),
                               TotalVolume = g.Sum(item => item.Volume)
                           };

segmentation fault : 11

This declaration:

double F[1000][1000000];

would occupy 8 * 1000 * 1000000 bytes on a typical x86 system. This is about 7.45 GB. Chances are your system is running out of memory when trying to execute your code, which results in a segmentation fault.

Find duplicate records in a table using SQL Server

Select * from dbo.sales group by shoppername having(count(Item) > 1)

DateTime.TryParseExact() rejecting valid formats

This is the Simple method, Use ParseExact

CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result;
String dateString = "Sun 08 Jun 2013 8:30 AM -06:00";
String format = "ddd dd MMM yyyy h:mm tt zzz";
result = DateTime.ParseExact(dateString, format, provider);

This should work for you.

How can I get the average (mean) of selected columns

Try using rowMeans:

z$mean=rowMeans(z[,c("x", "y")], na.rm=TRUE)

  w x  y mean
1 5 1  1    1
2 6 2  2    2
3 7 3  3    3
4 8 4 NA    4

Java: splitting the filename into a base and extension

You can also user java Regular Expression. String.split() also uses the expression internally. Refer http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html

Set CSS property in Javascript?

This works well with most CSS properties if there are no hyphens in them.

var element = document.createElement('select');
element.style.width = "100px";

For properties with hyphens in them like max-width, you should convert the sausage-case to camelCase

var element = document.createElement('select');
element.style.maxWidth = "100px";

how to get curl to output only http response body (json) and no other headers etc

You are specifying the -i option:

-i, --include

(HTTP) Include the HTTP-header in the output. The HTTP-header includes things like server-name, date of the document, HTTP-version and more...

Simply remove that option from your command line:

response=$(curl -sb -H "Accept: application/json" "http://host:8080/some/resource")

How to Populate a DataTable from a Stored Procedure

You don't need to add the columns manually. Just use a DataAdapter and it's simple as:

DataTable table = new DataTable();
using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
using(var cmd = new SqlCommand("usp_GetABCD", con))
using(var da = new SqlDataAdapter(cmd))
{
   cmd.CommandType = CommandType.StoredProcedure;
   da.Fill(table);
}

Note that you even don't need to open/close the connection. That will be done implicitly by the DataAdapter.

The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.

Django datetime issues (default=datetime.now())

From the Python language reference, under Function definitions:

Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that that same “pre-computed” value is used for each call.

Fortunately, Django has a way to do what you want, if you use the auto_now argument for the DateTimeField:

date = models.DateTimeField(auto_now=True)

See the Django docs for DateTimeField.

Reading a cell value in Excel vba and write in another Cell

I have this function for this case ..

Function GetValue(r As Range, Tag As String) As Integer
Dim c, nRet As String
Dim n, x As Integer
Dim bNum As Boolean

c = r.Value
n = InStr(c, Tag)
For x = n + 1 To Len(c)
  Select Case Mid(c, x, 1)
    Case ":":    bNum = True
    Case " ": Exit For
    Case Else: If bNum Then nRet = nRet & Mid(c, x, 1)
  End Select
Next
GetValue = val(nRet)
End Function

To fill cell BC .. (assumed that you check cell A1)

Worksheets("Übersicht_2013").Cells(i, "BC") = GetValue(range("A1"),"S")

AJAX cross domain call

I use this code for cross domain ajax call, I hope it will help more than one here. I'm using Prototype library and you can do the same with JQuery or Dojo or anything else:

Step 1: create a new js file and put this class inside, I called it xss_ajax.js

var WSAjax = Class.create ({
    initialize: function (_url, _callback){
        this.url = _url ;
        this.callback = _callback ;
        this.connect () ;
    },
    connect: function (){
        var script_id = null;
        var script = document.createElement('script');
        script.setAttribute('type', 'text/javascript');
        script.setAttribute('src', this.url);
        script.setAttribute('id', 'xss_ajax_script');

        script_id = document.getElementById('xss_ajax_script');
        if(script_id){
            document.getElementsByTagName('head')[0].removeChild(script_id);
        }

        // Insert <script> into DOM
        document.getElementsByTagName('head')[0].appendChild(script);
    },
    process: function (data){
        this.callback(data) ;
    }

}) ;

This class creates a dynamic script element which src attributes targets your JSON data provider (JSON-P in fact as your distant server must provide the data in this format :: call_back_function(//json_data_here) :: so when the script tag is created your JSON will be directly evaled as a function (we'll talk about passing the callback method name to server on step 2), the main concept behind this is that script like img elements are not concerned by the SOP constraints.

Step2: in any html page where you wanna pull the JSON asynchronously (we call this AJAJ ~ Asynchronous JAvascript + JSON :-) instead of AJAX which use the XHTTPRequest object) do like below

//load Prototype first
//load the file you've created in step1


var xss_crawler = new WSAjax (
     "http://your_json_data_provider_url?callback=xss_crawler.process"
 ,   function (_data){
            // your json data is _data and do whatever you like with it 
        }) ;

D'you remenber the callback on step 1? so we pass it to the server and it will returns the JSON embeded in that method so in our case the server will return an evalable javascript code xss_crawler.process(//the_json_data), remember that xss_crawler is an instance of WSAjax class. The server code depends on you (if it's yours), but most of Ajax data providers let you specify the callback method in parameters like we did. In Ruby on rails I just did

render :json=>MyModel.all(:limit=>10), :callback => params[:callback],:content_type => "application/json"

and that's all, you can now pull data from another domain from your apps (widgets, maps etc), in JSON format only, don't forget.

I hope it was helpfull, thanks for your patience :-), peace and sorry for code formatting, it doesn't work well

LINQ to SQL - How to select specific columns and return strongly typed list

Basically you are doing it the right way. However, you should use an instance of the DataContext for querying (it's not obvious that DataContext is an instance or the type name from your query):

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new Person { Name = a.Name, Age = a.Age }).ToList();

Apparently, the Person class is your LINQ to SQL generated entity class. You should create your own class if you only want some of the columns:

class PersonInformation {
   public string Name {get;set;}
   public int Age {get;set;}
}

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new PersonInformation { Name = a.Name, Age = a.Age }).ToList();

You can freely swap var with List<PersonInformation> here without affecting anything (as this is what the compiler does).

Otherwise, if you are working locally with the query, I suggest considering an anonymous type:

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new { a.Name, a.Age }).ToList();

Note that in all of these cases, the result is statically typed (it's type is known at compile time). The latter type is a List of a compiler generated anonymous class similar to the PersonInformation class I wrote above. As of C# 3.0, there's no dynamic typing in the language.

UPDATE:

If you really want to return a List<Person> (which might or might not be the best thing to do), you can do this:

var result = from a in new DataContext().Persons
             where a.Age > 18
             select new { a.Name, a.Age };

List<Person> list = result.AsEnumerable()
                          .Select(o => new Person {
                                           Name = o.Name, 
                                           Age = o.Age
                          }).ToList();

You can merge the above statements too, but I separated them for clarity.

git: How to diff changed files versus previous versions after a pull?

I like to use:

git diff HEAD^

Or if I only want to diff a specific file:

git diff HEAD^ -- /foo/bar/baz.txt

How to quickly clear a JavaScript Object?

ES5

ES5 solution can be:

// for enumerable and non-enumerable properties
Object.getOwnPropertyNames(obj).forEach(function (prop) {
  delete obj[prop];
});

ES6

And ES6 solution can be:

// for enumerable and non-enumerable properties
for (const prop of Object.getOwnPropertyNames(obj)) {
  delete obj[prop];
}

Performance

Regardless of the specs, the quickest solutions will generally be:

// for enumerable and non-enumerable of an object with proto chain
var props = Object.getOwnPropertyNames(obj);
for (var i = 0; i < props.length; i++) {
  delete obj[props[i]];
}

// for enumerable properties of shallow/plain object
for (var key in obj) {
  // this check can be safely omitted in modern JS engines
  // if (obj.hasOwnProperty(key))
    delete obj[key];
}

The reason why for..in should be performed only on shallow or plain object is that it traverses the properties that are prototypically inherited, not just own properties that can be deleted. In case it isn't known for sure that an object is plain and properties are enumerable, for with Object.getOwnPropertyNames is a better choice.

How to use Class<T> in Java?

As other answers point out, there are many and good reasons why this class was made generic. However there are plenty of times that you don't have any way of knowing the generic type to use with Class<T>. In these cases, you can simply ignore the yellow eclipse warnings or you can use Class<?> ... That's how I do it ;)

Select2() is not a function

For me, select2.min.js file worked instead of select2.full.min.js. I have manually define files which I have copied from dist folder that I got from github page. Also make sure that you have one jQuery(document).ready(...) definition and jquery file imported before select2 file.

How to return data from promise

One of the fundamental principles behind a promise is that it's handled asynchronously. This means that you cannot create a promise and then immediately use its result synchronously in your code (e.g. it's not possible to return the result of a promise from within the function that initiated the promise).

What you likely want to do instead is to return the entire promise itself. Then whatever function needs its result can call .then() on the promise, and the result will be there when the promise has been resolved.

Here is a resource from HTML5Rocks that goes over the lifecycle of a promise, and how its output is resolved asynchronously:
http://www.html5rocks.com/en/tutorials/es6/promises/

How do I find the parent directory in C#?

To get a 'grandparent' directory, call Directory.GetParent() twice:

var gparent = Directory.GetParent(Directory.GetParent(str_directory).ToString());

Clear form after submission with jQuery

Propably this would do it for you.

 $('input').val('').removeAttr('checked').removeAttr('selected');

importing jar libraries into android-studio

This is how you add jar files from external folders

1) Click on File and there you click on New and New Module

2) New Window appears ,,There you have to choose the Import .JAR/.AAR package .

3) Click on the path option at the top right corner of the window ...And give the whole path of the JAR file .

4)click on finish.

Now you have added the Jar file and You need to add it in the dependency for your application project

1)Right click on app folder and there you have to choose Open Module Settings or F4

2)Click on dependency at the top right corner of the current window .

3)Click on '+' symbol and choose 'Module Dependency' and It will show you the existed JAR files which you have included in your project ...

Choose the one you want and click 'OK/Finish'

Thank you

The name 'controlname' does not exist in the current context

I had the same issue since i was tring to re produce the aspx file from a visual studio 2010 project so the controls had clientidmode="Static" property. When this is removed it was resolved.

Interpreting segfault messages

This is a segfault due to following a null pointer trying to find code to run (that is, during an instruction fetch).

If this were a program, not a shared library

Run addr2line -e yourSegfaultingProgram 00007f9bebcca90d (and repeat for the other instruction pointer values given) to see where the error is happening. Better, get a debug-instrumented build, and reproduce the problem under a debugger such as gdb.

Since it's a shared library

You're hosed, unfortunately; it's not possible to know where the libraries were placed in memory by the dynamic linker after-the-fact. Reproduce the problem under gdb.

What the error means

Here's the breakdown of the fields:

  • address (after the at) - the location in memory the code is trying to access (it's likely that 10 and 11 are offsets from a pointer we expect to be set to a valid value but which is instead pointing to 0)
  • ip - instruction pointer, ie. where the code which is trying to do this lives
  • sp - stack pointer
  • error - An error code for page faults; see below for what this means on x86.

    /*
     * Page fault error code bits:
     *
     *   bit 0 ==    0: no page found       1: protection fault
     *   bit 1 ==    0: read access         1: write access
     *   bit 2 ==    0: kernel-mode access  1: user-mode access
     *   bit 3 ==                           1: use of reserved bit detected
     *   bit 4 ==                           1: fault was an instruction fetch
     */
    

ArrayBuffer to base64 encoded string

This works fine for me:

var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(arrayBuffer)));

In ES6, the syntax is a little simpler:

let base64String = btoa(String.fromCharCode(...new Uint8Array(arrayBuffer)));

As pointed out in the comments, this method may result in a runtime error in some browsers when the ArrayBuffer is large. The exact size limit is implementation dependent in any case.

MVC 3 file upload and model binding

For multiple files; note the newer "multiple" attribute for input:

Form:

@using (Html.BeginForm("FileImport","Import",FormMethod.Post, new {enctype = "multipart/form-data"}))
{
    <label for="files">Filename:</label>
    <input type="file" name="files" multiple="true" id="files" />
    <input type="submit"  />
}

Controller:

[HttpPost]
public ActionResult FileImport(IEnumerable<HttpPostedFileBase> files)
{
    return View();
}

Fill background color left to right CSS

If you are like me and need to change color of text itself also while in the same time filling the background color check my solution.

Steps to create:

  1. Have two text, one is static colored in color on hover, and the other one in default state color which you will be moving on hover
  2. On hover move wrapper of the not static one text while in the same time move inner text of that wrapper to the opposite direction.
  3. Make sure to add overflow hidden where needed

Good thing about this solution:

  • Support IE9, uses only transform
  • Button (or element you are applying animation) is fluid in width, so no fixed values are being used here

Not so good thing about this solution:

  • A really messy markup, could be solved by using pseudo elements and att(data)?
  • There is some small glitch in animation when having more then one button next to each other, maybe it could be easily solved but I didn't take much time to investigate yet.

Check the pen ---> https://codepen.io/nikolamitic/pen/vpNoNq

<button class="btn btn--animation-from-right">
  <span class="btn__text-static">Cover left</span>
  <div class="btn__text-dynamic">
    <span class="btn__text-dynamic-inner">Cover left</span>
  </div>
</button>

.btn {
  padding: 10px 20px;
  position: relative;

  border: 2px solid #222;
  color: #fff;
  background-color: #222;
  position: relative;

  overflow: hidden;
  cursor: pointer;

  text-transform: uppercase;
  font-family: monospace;
  letter-spacing: -1px;

  [class^="btn__text"] {
    font-size: 24px;
  }

  .btn__text-dynamic,
  .btn__text-dynamic-inner {    
    display: flex;
    justify-content: center;
    align-items: center;

    position: absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    z-index: 2;

    transition: all ease 0.5s;
  }

  .btn__text-dynamic {
    background-color: #fff;
    color: #222;

    overflow: hidden;
  }

  &:hover {
    .btn__text-dynamic {
      transform: translateX(-100%);
    }
    .btn__text-dynamic-inner {
      transform: translateX(100%);
    }
  }
}

.btn--animation-from-right {
    &:hover {
    .btn__text-dynamic {
      transform: translateX(100%);
    }
    .btn__text-dynamic-inner {
      transform: translateX(-100%);
    }
  }
}

You can remove .btn--animation-from-right modifier if you want to animate to the left.

Selenium -- How to wait until page is completely loaded

There are two different ways to use delay in selenium one which is most commonly in use. Please try this:

driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

second one which you can use that is simply try catch method by using that method you can get your desire result.if you want example code feel free to contact me defiantly I will provide related code

Posting raw image data as multipart/form-data in curl

In case anyone had the same problem: check this as @PravinS suggested. I used the exact same code as shown there and it worked for me perfectly.

This is the relevant part of the server code that helped:

if (isset($_POST['btnUpload']))
{
$url = "URL_PATH of upload.php"; // e.g. http://localhost/myuploader/upload.php // request URL
$filename = $_FILES['file']['name'];
$filedata = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
if ($filedata != '')
{
    $headers = array("Content-Type:multipart/form-data"); // cURL headers for file uploading
    $postfields = array("filedata" => "@$filedata", "filename" => $filename);
    $ch = curl_init();
    $options = array(
        CURLOPT_URL => $url,
        CURLOPT_HEADER => true,
        CURLOPT_POST => 1,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => $postfields,
        CURLOPT_INFILESIZE => $filesize,
        CURLOPT_RETURNTRANSFER => true
    ); // cURL options
    curl_setopt_array($ch, $options);
    curl_exec($ch);
    if(!curl_errno($ch))
    {
        $info = curl_getinfo($ch);
        if ($info['http_code'] == 200)
            $errmsg = "File uploaded successfully";
    }
    else
    {
        $errmsg = curl_error($ch);
    }
    curl_close($ch);
}
else
{
    $errmsg = "Please select the file";
}
}

html form should look something like:

<form action="uploadpost.php" method="post" name="frmUpload" enctype="multipart/form-data">
<tr>
  <td>Upload</td>
  <td align="center">:</td>
  <td><input name="file" type="file" id="file"/></td>
</tr>
<tr>
  <td>&nbsp;</td>
  <td align="center">&nbsp;</td>
  <td><input name="btnUpload" type="submit" value="Upload" /></td>
</tr>

What is hashCode used for? Is it unique?

It's not unique to WP7--it's present on all .Net objects. It sort of does what you describe, but I would not recommend it as a unique identifier in your apps, as it is not guaranteed to be unique.

Object.GetHashCode Method

Finding the last index of an array

Is this worth mentioning?

var item = new Stack(arr).Pop();

Make view 80% width of parent in React Native

As of React Native 0.42 height: and width: accept percentages.

Use width: 80% in your stylesheets and it just works.

  • Screenshot

  • Live Example
    Child Width/Height as Proportion of Parent

  • Code

    import React from 'react';
    import { Text, View, StyleSheet } from 'react-native';
    
    const width_proportion = '80%';
    const height_proportion = '40%';
    
    const styles = StyleSheet.create({
      screen: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#5A9BD4',
      },
      box: {
        width: width_proportion,
        height: height_proportion,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#B8D2EC',
      },
      text: {
        fontSize: 18,
      },
    });
    
    export default () => (
      <View style={styles.screen}>
        <View style={styles.box}>
          <Text style={styles.text}>
            {width_proportion} of width{'\n'}
            {height_proportion} of height
          </Text>
        </View>
      </View>
    );
    

How to find the Number of CPU Cores via .NET/C#?

The the easyest way = Environment.ProcessorCount
Exemple from Environment.ProcessorCount Property

using System;

class Sample 
{
    public static void Main() 
    {
        Console.WriteLine("The number of processors " +
            "on this computer is {0}.", 
            Environment.ProcessorCount);
    }
}

Can I rollback a transaction I've already committed? (data loss)

No, you can't undo, rollback or reverse a commit.

STOP THE DATABASE!

(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE or similar, not an rm -rf /data/directory scenario).

If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate so that no checkpoint is run on shutdown.

You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.

If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.

Urgent mitigation

Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base, pg_clog, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog etc. No part is unimportant.

Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.

Ways some data could've survived

If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT or UPDATE. Thus, the old versions of the UPDATEd rows might still be lying around, present but inaccessible.

Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl in immediate mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.

Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.

Recovery

You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.

I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOASTed data so it's of limited utility. Give it a try, if you're lucky it might work.

See: pg_dirtyread on GitHub.

I've removed what I'd written in this section as it's obsoleted by that tool.

See also PostgreSQL row storage fundamentals

Prevention

See my blog entry Preventing PostgreSQL database corruption.


On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.