Programs & Examples On #Aero glass

Aero Glass is a Microsoft Windows desktop theme, incorporating various animation and transparency effects into the desktop using hardware acceleration and the Desktop Window Manager (DWM).

Background blur with CSS

In which way do you want it dynamic? If you want the popup to successfully map to the background, you need to create two backgrounds. It requires both the use of element() or -moz-element() and a filter (for Firefox, use a SVG filter like filter: url(#svgBlur) since Firefox does not support -moz-filter: blur() as yet?). It only works in Firefox at the time of writing.

See demo here.

I still need to create a simple demo to show how it is done. You're welcome to view the source.

datetime.parse and making it work with a specific format

Thanks for the tip, i used this to get my date "20071122" parsed, I needed to add datetimestyles, I used none and it worked:

DateTime dt = DateTime.MinValue;

DateTime.TryParseExact("20071122", "yyyyMMdd", null,System.Globalization.DateTimeStyles.None, out dt);

Why does background-color have no effect on this DIV?

This being a very old question but worth adding that I have just had a similar issue where a background colour on a footer element in my case didn't show. I added a position: relative which worked.

How To have Dynamic SQL in MySQL Stored Procedure

After 5.0.13, in stored procedures, you can use dynamic SQL:

delimiter // 
CREATE PROCEDURE dynamic(IN tbl CHAR(64), IN col CHAR(64))
BEGIN
    SET @s = CONCAT('SELECT ',col,' FROM ',tbl );
    PREPARE stmt FROM @s;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END
//
delimiter ;

Dynamic SQL does not work in functions or triggers. See the MySQL documentation for more uses.

How to hide elements without having them take space on the page?

Thanks to this question. I wanted the exact opposite, i.e a hidden div should still occupy its space on the browser. So, I used visibility: hidden instead of display: none.

Hide Show content-list with only CSS, no javascript used

The answer below includes changing text for "show/hide", and uses a single checkbox, two labels, a total of four lines of html and five lines of css. It also starts out with the content hidden.

Try it in JSFiddle

HTML

<input id="display-toggle" type=checkbox>
<label id="display-button" for="display-toggle"><span>Display Content</span></label>
<label id="hide-button" for="display-toggle"><span>Hide Content</span></label>    
<div id="hidden-content"><br />Hidden Content</div>

CSS

label {
  background-color: #ccc;
  color: brown;
  padding: 15px;
  text-decoration: none;
  font-size: 16px;
  border: 2px solid brown;
  border-radius: 5px;
  display: block;
  width: 200px;
  text-align: center;
}

input,
label#hide-button,
#hidden-content {
  display: none;
}

input#display-toggle:checked ~ label#display-button {
  display: none;
}

input#display-toggle:checked ~ label#hide-button {
  display: block;
  background-color: #aaa;
  color: #333
}

input#display-toggle:checked ~ #hidden-content {
  display: block;
} 

WPF Databinding: How do I access the "parent" data context?

This will also work:

<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl},
                             Path=DataContext.AllowItemCommand}" />

ListView will inherit its DataContext from Window, so it's available at this point, too.
And since ListView, just like similar controls (e. g. Gridview, ListBox, etc.), is a subclass of ItemsControl, the Binding for such controls will work perfectly.

Installing RubyGems in Windows

To setup you Ruby development environment on Windows:

  1. Install Ruby via RubyInstaller: http://rubyinstaller.org/downloads/

  2. Check your ruby version: Start - Run - type in cmd to open a windows console

  3. Type in ruby -v
  4. You will get something like that: ruby 2.0.0p353 (2013-11-22) [i386-mingw32]

For Ruby 2.4 or later, run the extra installation at the end to install the DevelopmentKit. If you forgot to do that, run ridk install in your windows console to install it.

For earlier versions:

  1. Download and install DevelopmentKit from the same download page as Ruby Installer. Choose an ?exe file corresponding to your environment (32 bits or 64 bits and working with your version of Ruby).
  2. Follow the installation instructions for DevelopmentKit described at: https://github.com/oneclick/rubyinstaller/wiki/Development-Kit#installation-instructions. Adapt it for Windows.
  3. After installing DevelopmentKit you can install all needed gems by just running from the command prompt (windows console or terminal): gem install {gem name}. For example, to install rails, just run gem install rails.

Hope this helps.

Triggering a checkbox value changed event in DataGridView

Try hooking into the CellContentClick event. The DataGridViewCellEventArgs will have a ColumnIndex and a RowIndex so you can know if a ChecboxCell was in fact clicked. The good thing about this event is that it will only fire if the actual checkbox itself was clicked. If you click on the white area of the cell around the checkbox, it won't fire. This way, you're pretty much guaranteed that the checkbox value was changed when this event fires. You can then call Invalidate() to trigger your drawing event, as well as a call to EndEdit() to trigger the end of the row's editing if you need that.

how to access downloads folder in android?

If you're using a shell, the filepath to the Download (no "s") folder is

/storage/emulated/0/Download

remove first element from array and return the array minus the first element

This should remove the first element, and then you can return the remaining:

_x000D_
_x000D_
var myarray = ["item 1", "item 2", "item 3", "item 4"];_x000D_
    _x000D_
myarray.shift();_x000D_
alert(myarray);
_x000D_
_x000D_
_x000D_

As others have suggested, you could also use slice(1);

_x000D_
_x000D_
var myarray = ["item 1", "item 2", "item 3", "item 4"];_x000D_
  _x000D_
alert(myarray.slice(1));
_x000D_
_x000D_
_x000D_

How to get all child inputs of a div element (jQuery)

If you are using a framework like Ruby on Rails or Spring MVC you may need to use divs with square braces or other chars, that are not allowed you can use document.getElementById and this solution still works if you have multiple inputs with the same type.

var div = document.getElementById(divID);
$(div).find('input:text, input:password, input:file, select, textarea')
        .each(function() {
            $(this).val('');
        });
$(div).find('input:radio, input:checkbox').each(function() {
    $(this).removeAttr('checked');
    $(this).removeAttr('selected');
});

This examples shows how to clear the inputs, for you example you'll need to change it.

Remove the last line from a file in Bash

Ruby(1.9+)

ruby -ne 'BEGIN{prv=""};print prv ; prv=$_;' file

Substring a string from the end of the string

You can do:

string str = "Hello Marco !";
str = str.Substring(0, str.Length - 2);

How to restore/reset npm configuration to default values?

npm config edit

Opens the config file in an editor. Use the --global flag to edit the global config. now you can delete what ever the registry's you don't want and save file.

npm config list will display the list of available now.

How to search a string in String array

If the array is sorted, you can use BinarySearch. This is a O(log n) operation, so it is faster as looping. If you need to apply multiple searches and speed is a concern, you could sort it (or a copy) before using it.

How to serialize an Object into a list of URL query parameters?

Object.keys(obj).map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`).join('&')

remove double quotes from Json return data using Jquery

The stringfy method is not for parsing JSON, it's for turning an object into a JSON string.

The JSON is parsed by jQuery when you load it, you don't need to parse the data to use it. Just use the string in the data:

$('div#ListingData').text(data.data.items[0].links[1].caption);

Unable to negotiate with XX.XXX.XX.XX: no matching host key type found. Their offer: ssh-dss

How would one specify multiple algorithms? I ask because git just updated on my work laptop, (Windows 10, using the official Git for Windows build,) and I got this error when I tried to push a project branch to my Azure DevOps remote. I tried to push --set-upstream and got this:

Unable to negotiate with 20.44.80.98 port 22: no matching key exchange method found. Their offer: diffie-hellman-group1-sha1,diffie-hellman-group14-sha1
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

So how would one implement the suggestions above allowing for both of those? (As a quick get-it-done, I used @golvok's solution with group14 and it worked, but I really don't know if 1 or 14 is better, etc.)

How to find the foreach index?

I would like to add this, I used this in laravel to just index my table:

  • With $loop->index
  • I also preincrement it with ++$loop to start at 1

My Code:

@foreach($resultsPerCountry->first()->studies as $result)
  <tr>
    <td>{{ ++$loop->index}}</td>                                    
  </tr>
@endforeach

Get first 100 characters from string, respecting full words

I apologize for resurrecting this question but I stumbled upon this thread and found a small issue. For anyone wanting a character limit that will remove words that would go above your given limit, the above answers work great. In my specific case, I like to display a word if the limit falls in the middle of said word. I decided to share my solution in case anyone else is looking for this functionality and needs to include words instead of trimming them out.

function str_limit($str, $len = 100, $end = '...')
{
    if(strlen($str) < $len)
    {
        return $str;
    }

    $str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str));

    if(strlen($str) <= $len)
    {
        return $str;
    }

    $out = '';
    foreach(explode(' ', trim($str)) as $val)
    {
        $out .= $val . ' ';

        if(strlen($out) >= $len)
        {
            $out = trim($out);
            return (strlen($out) == strlen($str)) ? $out : $out . $end;
        }
    }
}

Examples:

  • Input: echo str_limit('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', 100, '...');
  • Output: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore...
  • Input: echo str_limit('Lorem ipsum', 100, '...');
  • Output: Lorem ipsum
  • Input: echo str_limit('Lorem ipsum', 1, '...');
  • Output: Lorem...

Test for non-zero length string in Bash: [ -n "$var" ] or [ "$var" ]

The correct answer is the following:

if [[ -n $var ]] ; then
  blah
fi

Note the use of the [[...]], which correctly handles quoting the variables for you.

Setting a WebRequest's body data

With HttpWebRequest.GetRequestStream

Code example from http://msdn.microsoft.com/en-us/library/d4cek6cc.aspx

string postData = "firstone=" + inputData;
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postData);

// Set the content type of the data being posted.
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";

// Set the content length of the string being posted.
myHttpWebRequest.ContentLength = byte1.Length;

Stream newStream = myHttpWebRequest.GetRequestStream ();

newStream.Write (byte1, 0, byte1.Length);

From one of my own code:

var request = (HttpWebRequest)WebRequest.Create(uri);
request.Credentials = this.credentials;
request.Method = method;
request.ContentType = "application/atom+xml;type=entry";
using (Stream requestStream = request.GetRequestStream())
using (var xmlWriter = XmlWriter.Create(requestStream, new XmlWriterSettings() { Indent = true, NewLineHandling = NewLineHandling.Entitize, }))
{
    cmisAtomEntry.WriteXml(xmlWriter);
}

try 
{    
    return (HttpWebResponse)request.GetResponse();  
}
catch (WebException wex)
{
    var httpResponse = wex.Response as HttpWebResponse;
    if (httpResponse != null)
    {
        throw new ApplicationException(string.Format(
            "Remote server call {0} {1} resulted in a http error {2} {3}.",
            method,
            uri,
            httpResponse.StatusCode,
            httpResponse.StatusDescription), wex);
    }
    else
    {
        throw new ApplicationException(string.Format(
            "Remote server call {0} {1} resulted in an error.",
            method,
            uri), wex);
    }
}
catch (Exception)
{
    throw;
}

Align inline-block DIVs to top of container element

<style type="text/css">
        div {
  text-align: center;
         }

         .img1{
            width: 150px;
            height: 150px;
            border-radius: 50%;
         }

         span{
            display: block;
         }
    </style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type='password' class='secondInput mt-4 mr-1' placeholder="Password">
  <span class='dif'></span>
  <br>
  <button>ADD</button>
</div>

<script type="text/javascript">

$('button').click(function() {
  $('.dif').html("<img/>");

})

Remove Select arrow on IE

In case you want to use the class and pseudo-class:

.simple-control is your css class

:disabled is pseudo class

select.simple-control:disabled{
         /*For FireFox*/
        -webkit-appearance: none;
        /*For Chrome*/
        -moz-appearance: none;
}

/*For IE10+*/
select:disabled.simple-control::-ms-expand {
        display: none;
}

Generate unique random numbers between 1 and 100

for arrays with holes like this [,2,,4,,6,7,,] because my problem was to fill these holes. So I modified it as per my need :)

the following modified solution worked for me :)

var arr = [,2,,4,,6,7,,]; //example
while(arr.length < 9){
  var randomnumber=Math.floor(Math.random()*9+1);
  var found=false;
  for(var i=0;i<arr.length;i++){
    if(arr[i]==randomnumber){found=true;break;}
  }

  if(!found)
    for(k=0;k<9;k++)
    {if(!arr[k]) //if it's empty  !!MODIFICATION
      {arr[k]=randomnumber; break;}}
}

alert(arr); //outputs on the screen

How to copy multiple files in one layer using a Dockerfile?

simple

COPY README.md  package.json gulpfile.js __BUILD_NUMBER ./

from the doc

If multiple resources are specified, either directly or due to the use of a wildcard, then must be a directory, and it must end with a slash /.

What's the difference between echo, print, and print_r in PHP?

they both are language constructs. echo returns void and print returns 1. echo is considered slightly faster than print.

How do I convert between big-endian and little-endian values in C++?

I recently wrote a macro to do this in C, but it's equally valid in C++:

#define REVERSE_BYTES(...) do for(size_t REVERSE_BYTES=0; REVERSE_BYTES<sizeof(__VA_ARGS__)>>1; ++REVERSE_BYTES)\
    ((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES] ^= ((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES],\
    ((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES] ^= ((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES],\
    ((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES] ^= ((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES];\
while(0)

It accepts any type and reverses the bytes in the passed argument. Example usages:

int main(){
    unsigned long long x = 0xABCDEF0123456789;
    printf("Before: %llX\n",x);
    REVERSE_BYTES(x);
    printf("After : %llX\n",x);

    char c[7]="nametag";
    printf("Before: %c%c%c%c%c%c%c\n",c[0],c[1],c[2],c[3],c[4],c[5],c[6]);
    REVERSE_BYTES(c);
    printf("After : %c%c%c%c%c%c%c\n",c[0],c[1],c[2],c[3],c[4],c[5],c[6]);
}

Which prints:

Before: ABCDEF0123456789
After : 8967452301EFCDAB
Before: nametag
After : gateman

The above is perfectly copy/paste-able, but there's a lot going on here, so I'll break down how it works piece by piece:

The first notable thing is that the entire macro is encased in a do while(0) block. This is a common idiom to allow normal semicolon use after the macro.

Next up is the use of a variable named REVERSE_BYTES as the for loop's counter. The name of the macro itself is used as a variable name to ensure that it doesn't clash with any other symbols that may be in scope wherever the macro is used. Since the name is being used within the macro's expansion, it won't be expanded again when used as a variable name here.

Within the for loop, there are two bytes being referenced and XOR swapped (so a temporary variable name is not required):

((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES]
((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES]

__VA_ARGS__ represents whatever was given to the macro, and is used to increase the flexibility of what may be passed in (albeit not by much). The address of this argument is then taken and cast to an unsigned char pointer to permit the swapping of its bytes via array [] subscripting.

The final peculiar point is the lack of {} braces. They aren't necessary because all of the steps in each swap are joined with the comma operator, making them one statement.

Finally, it's worth noting that this is not the ideal approach if speed is a top priority. If this is an important factor, some of the type-specific macros or platform-specific directives referenced in other answers are likely a better option. This approach, however, is portable to all types, all major platforms, and both the C and C++ languages.

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

This solves the issue when you scroll past the beginning or end of the div

var selScrollable = '.scrollable';
// Uses document because document will be topmost level in bubbling
$(document).on('touchmove',function(e){
  e.preventDefault();
});
// Uses body because jQuery on events are called off of the element they are
// added to, so bubbling would not work if we used document instead.
$('body').on('touchstart', selScrollable, function(e) {
  if (e.currentTarget.scrollTop === 0) {
    e.currentTarget.scrollTop = 1;
  } else if (e.currentTarget.scrollHeight === e.currentTarget.scrollTop + e.currentTarget.offsetHeight) {
    e.currentTarget.scrollTop -= 1;
  }
});
// Stops preventDefault from being called on document if it sees a scrollable div
$('body').on('touchmove', selScrollable, function(e) {
  e.stopPropagation();
});

Note that this won't work if you want to block whole page scrolling when a div does not have overflow. To block that, use the following event handler instead of the one immediately above (adapted from this question):

$('body').on('touchmove', selScrollable, function(e) {
    // Only block default if internal div contents are large enough to scroll
    // Warning: scrollHeight support is not universal. (https://stackoverflow.com/a/15033226/40352)
    if($(this)[0].scrollHeight > $(this).innerHeight()) {
        e.stopPropagation();
    }
});

How to use SearchView in Toolbar Android

You have to use Appcompat library for that. Which is used like below:

dashboard.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" 
      xmlns:tools="http://schemas.android.com/tools"
      xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_search"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="always|collapseActionView"
        app:actionViewClass="androidx.appcompat.widget.SearchView"
        android:title="Search"/>
</menu>

Activity file (in Java):

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate(R.menu.dashboard, menu);

     MenuItem searchItem = menu.findItem(R.id.action_search);

    SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);

    SearchView searchView = null;
    if (searchItem != null) {
        searchView = (SearchView) searchItem.getActionView();
    }
    if (searchView != null) {
        searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
    }
        return super.onCreateOptionsMenu(menu);
}

Activity file (in Kotlin):

override fun onCreateOptionsMenu(menu: Menu?): Boolean {
    menuInflater.inflate(R.menu.menu_search, menu)

    val searchItem: MenuItem? = menu?.findItem(R.id.action_search)
    val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
    val searchView: SearchView? = searchItem?.actionView as SearchView

    searchView?.setSearchableInfo(searchManager.getSearchableInfo(componentName))
    return super.onCreateOptionsMenu(menu)
}

manifest file:

<meta-data 
      android:name="android.app.default_searchable" 
      android:value="com.apkgetter.SearchResultsActivity" /> 

        <activity
            android:name="com.apkgetter.SearchResultsActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop" >
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
            </intent-filter>

            <meta-data
                android:name="android.app.searchable"
                android:resource="@xml/searchable" />
        </activity>

searchable xml file:

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:hint="@string/search_hint"
    android:label="@string/app_name" />

And at last, your SearchResultsActivity class code. for showing result of your search.

Is there a way to create key-value pairs in Bash script?

In bash, we use

declare -A name_of_dictonary_variable

so that Bash understands it is a dictionary.

For e.g. you want to create sounds dictionary then,

declare -A sounds

sounds[dog]="Bark"

sounds[wolf]="Howl"

where dog and wolf are "keys", and Bark and Howl are "values".

You can access all values using : echo ${sounds[@]} OR echo ${sounds[*]}

You can access all keys only using: echo ${!sounds[@]}

And if you want any value for a particular key, you can use:

${sounds[dog]}

this will give you value (Bark) for key (Dog).

android listview item height

The trick for me was not setting the height -- but instead setting the minHeight. This must be applied to the root view of whatever layout your custom adapter is using to render each row.

Max retries exceeded with URL in requests

Adding my own experience for those who are experiencing this in the future. My specific error was

Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known'

It turns out that this was actually because I had reach the maximum number of open files on my system. It had nothing to do with failed connections, or even a DNS error as indicated.

Is there an easy way to attach source in Eclipse?

Short answer would be yes.

You can attach source using the properties for a project.

Go to Properties (for the Project) -> Java Build Path -> Libraries

Select the Library you want to attach source/javadoc for and then expand it, you'll see a list like so:

Source Attachment: (none)
Javadoc location: (none)
Native library location: (none)
Access rules: (No restrictions)

Select Javadoc location and then click Edit on the right hahnd side. It should be quite straight forward from there.

Good luck :)

R: Print list to a text file

depending on your tastes, an alternative to nico's answer:

d<-lapply(mylist, write, file=" ... ", append=T);

using javascript to detect whether the url exists before display in iframe

Due to my low reputation I couldn't comment on Derek ????'s answer. I've tried that code as it is and it didn't work well. There are three issues on Derek ????'s code.

  1. The first is that the time to async send the request and change its property 'status' is slower than to execute the next expression - if(request.status === "404"). So the request.status will eventually, due to internet band, remain on status 0 (zero), and it won't achieve the code right below if. To fix that is easy: change 'true' to 'false' on method open of the ajax request. This will cause a brief (or not so) block on your code (due to synchronous call), but will change the status of the request before reaching the test on if.

  2. The second is that the status is an integer. Using '===' javascript comparison operator you're trying to compare if the left side object is identical to one on the right side. To make this work there are two ways:

    • Remove the quotes that surrounds 404, making it an integer;
    • Use the javascript's operator '==' so you will be testing if the two objects are similar.
  3. The third is that the object XMLHttpRequest only works on newer browsers (Firefox, Chrome and IE7+). If you want that snippet to work on all browsers you have to do in the way W3Schools suggests: w3schools ajax

The code that really worked for me was:

var request;
if(window.XMLHttpRequest)
    request = new XMLHttpRequest();
else
    request = new ActiveXObject("Microsoft.XMLHTTP");
request.open('GET', 'http://www.mozilla.org', false);
request.send(); // there will be a 'pause' here until the response to come.
// the object request will be actually modified
if (request.status === 404) {
    alert("The page you are trying to reach is not available.");
}

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

I was able to solve the problem in my react native project by simply adding

configurations {
        all*.exclude group: 'com.android.support', module: 'support-compat'
        all*.exclude group: 'com.android.support', module: 'support-core-ui'
    }

at the end of my android\app\build.gradle file

using awk with column value conditions

This is more readable for me

awk '{if ($2 ~ /findtext/) print $3}' <infile>

How do I make an HTML button not reload the page

there is no need to js or jquery. to stop page reloading just specify the button type as 'button'. if you dont specify the button type, browser will set it to 'reset' or 'submit' witch cause to page reload.

 <button type='button'>submit</button> 

getResourceAsStream returns null

You might want to try this to get the stream i.e first get the url and then open it as stream.

URL url = getClass().getResource("/initialization/Lifepaths.txt"); 
InputStream strm = url.openStream(); 

I once had a similar question: Reading txt file from jar fails but reading image works

Why my regexp for hyphenated words doesn't work?

You can use this:

r'[a-z]+(?:-[a-z]+)*' 

Get the difference between dates in terms of weeks, months, quarters, and years

I just wrote this for another question, then stumbled here.

library(lubridate)

#' Calculate age
#' 
#' By default, calculates the typical "age in years", with a
#' \code{floor} applied so that you are, e.g., 5 years old from
#' 5th birthday through the day before your 6th birthday. Set
#' \code{floor = FALSE} to return decimal ages, and change \code{units}
#' for units other than years.
#' @param dob date-of-birth, the day to start calculating age.
#' @param age.day the date on which age is to be calculated.
#' @param units unit to measure age in. Defaults to \code{"years"}. Passed to \link{\code{duration}}.
#' @param floor boolean for whether or not to floor the result. Defaults to \code{TRUE}.
#' @return Age in \code{units}. Will be an integer if \code{floor = TRUE}.
#' @examples
#' my.dob <- as.Date('1983-10-20')
#' age(my.dob)
#' age(my.dob, units = "minutes")
#' age(my.dob, floor = FALSE)
age <- function(dob, age.day = today(), units = "years", floor = TRUE) {
    calc.age = interval(dob, age.day) / duration(num = 1, units = units)
    if (floor) return(as.integer(floor(calc.age)))
    return(calc.age)
}

Usage examples:

my.dob <- as.Date('1983-10-20')

age(my.dob)
# [1] 31

age(my.dob, floor = FALSE)
# [1] 31.15616

age(my.dob, units = "minutes")
# [1] 16375680

age(seq(my.dob, length.out = 6, by = "years"))
# [1] 31 30 29 28 27 26

Learning to write a compiler

The Dragon Book is too complicated. So ignore it as a starting point. It is good and makes you think a lot once you already have a starting point, but for starters, perhaps you should simply try to write an math/logical expression evaluator using RD, LL or LR parsing techniques with everything (lexing/parsing) written by hand in perhaps C/Java. This is interesting in itself and gives you an idea of the problems involved in a compiler. Then you can jump in to your own DSL using some scripting language (since processing text is usually easier in these) and like someone said, generate code in either the scripting language itself or C. You should probably use flex/bison/antlr etc to do the lexing/parsing if you are going to do it in c/java.

Why java.security.NoSuchProviderException No such provider: BC?

For those who are using web servers make sure that the bcprov-jdk16-145.jar has been installed in you servers lib, for weblogic had to put the jar in:

<weblogic_jdk_home>\jre\lib\ext

Xcode iOS 8 Keyboard types not supported

Xcode: 6.4 iOS:8 I got this error as well, but for a very different reason.

//UIKeyboardTypeNumberPad needs a "Done" button    
UIBarButtonItem *doneBarButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                                                              target:self
                                                                              action:@selector(doneBarButtonTapped:)];

enhancedNumpadToolbar = [[UIToolbar alloc]init]; // previously declared
[self.enhancedNumpadToolbar setItems:@[doneBarButton]];
self.myNumberTextField.inputAccessoryView = self.enhancedNumpadToolbar; //txf previously declared

I got the same error (save mine was "type 4" rather than "type 8"), until I discovered that I was missing this line:

[self.enhancedNumpadToolbar sizeToFit];

I added it, and the sun started shining, the birds resumed chirping, and all was well with the world.

PS You would also get such an error for other mischief, such as forgetting to alloc/init.

Is there an XSL "contains" directive?

It should be something like...

<xsl:if test="contains($hhref, '1234')">

(not tested)

See w3schools (always a good reference BTW)

Invert "if" statement to reduce nesting

In theory, inverting if could lead to better performance if it increases branch prediction hit rate. In practice, I think it is very hard to know exactly how branch prediction will behave, especially after compiling, so I would not do it in my day-to-day development, except if I am writing assembly code.

More on branch prediction here.

using "if" and "else" Stored Procedures MySQL

I think that this construct: if exists (select... is specific for MS SQL. In MySQL EXISTS predicate tells you whether the subquery finds any rows and it's used like this: SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);

You can rewrite the above lines of code like this:

DELIMITER $$

CREATE PROCEDURE `checando`(in nombrecillo varchar(30), in contrilla varchar(30), out resultado int)

BEGIN
    DECLARE count_prim INT;
    DECLARE count_sec INT;

    SELECT COUNT(*) INTO count_prim FROM compas WHERE nombre = nombrecillo AND contrasenia = contrilla;
    SELECT COUNT(*) INTO count_sec FROM FROM compas WHERE nombre = nombrecillo;

    if (count_prim > 0) then
        set resultado = 0;
    elseif (count_sec > 0) then
        set resultado = -1;
    else 
        set resultado = -2;
    end if;
    SELECT resultado;
END

When using Trusted_Connection=true and SQL Server authentication, will this affect performance?

Not 100% sure what you mean:

Trusted_Connection=True;

IS using Windows credentials and is 100% equivalent to:

Integrated Security=SSPI;

or

Integrated Security=true;

If you don't want to use integrated security / trusted connection, you need to specify user id and password explicitly in the connection string (and leave out any reference to Trusted_Connection or Integrated Security)

server=yourservername;database=yourdatabase;user id=YourUser;pwd=TopSecret

Only in this case, the SQL Server authentication mode is used.

If any of these two settings is present (Trusted_Connection=true or Integrated Security=true/SSPI), then the Windows credentials of the current user are used to authenticate against SQL Server and any user iD= setting will be ignored and not used.

For reference, see the Connection Strings site for SQL Server 2005 with lots of samples and explanations.

Using Windows Authentication is the preferred and recommended way of doing things, but it might incur a slight delay since SQL Server would have to authenticate your credentials against Active Directory (typically). I have no idea how much that slight delay might be, and I haven't found any references for that.


Summing up:

If you specify either Trusted_Connection=True; or Integrated Security=SSPI; or Integrated Security=true; in your connection string

==> THEN (and only then) you have Windows Authentication happening. Any user id= setting in the connection string will be ignored.


If you DO NOT specify either of those settings,

==> then you DO NOT have Windows Authentication happening (SQL Authentication mode will be used)


Remove last item from array

say you have var arr = [1,0,2]

arr.splice(-1,1) will return to you array [1,0]; while arr.slice(-1,1) will return to you array [2];

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

How about this:

USE TargetDatabase
GO

INSERT INTO dbo.TargetTable(field1, field2, field3)
   SELECT field1, field2, field3
     FROM SourceDatabase.dbo.SourceTable
     WHERE (some condition)

Unable to find the requested .Net Framework Data Provider in Visual Studio 2010 Professional

I like the other suggestions but I would rather not update the machine.config for a single application. I suggest that you just add it to the web.config / app.config. Here is what I needed to use the MySql Connector/NET that I "bin" deployed.

<system.data>
    <DbProviderFactories >
        <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.6.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories>
</system.data>

Regular Expression to get a string between parentheses in Javascript

_x000D_
_x000D_
let str = "Before brackets (Inside brackets) After brackets".replace(/.*\(|\).*/g, '');_x000D_
console.log(str) // Inside brackets
_x000D_
_x000D_
_x000D_

How do I obtain a Query Execution Plan in SQL Server?

Like with SQL Server Management Studio (already explained), it is also possible with Datagrip as explained here.

  1. Right-click an SQL statement, and select Explain plan.
  2. In the Output pane, click Plan.
  3. By default, you see the tree representation of the query. To see the query plan, click the Show Visualization icon, or press Ctrl+Shift+Alt+U

The type java.lang.CharSequence cannot be resolved in package declaration

"Java 8 support for Eclipse Kepler SR2", and the new "JavaSE-1.8" execution environment showed up automatically.

Download this one:- Eclipse kepler SR2

and then follow this link:- Eclipse_Java_8_Support_For_Kepler

Encrypt and Decrypt in Java

Symmetric Key Cryptography : Symmetric key uses the same key for encryption and decryption. The main challenge with this type of cryptography is the exchange of the secret key between the two parties sender and receiver.

Example : The following example uses symmetric key for encryption and decryption algorithm available as part of the Sun's JCE(Java Cryptography Extension). Sun JCE is has two layers, the crypto API layer and the provider layer.

DES (Data Encryption Standard) was a popular symmetric key algorithm. Presently DES is outdated and considered insecure. Triple DES and a stronger variant of DES. It is a symmetric-key block cipher. There are other algorithms like Blowfish, Twofish and AES(Advanced Encryption Standard). AES is the latest encryption standard over the DES.

Steps :

  1. Add the Security Provider : We are using the SunJCE Provider that is available with the JDK.
  2. Generate Secret Key : Use KeyGenerator and an algorithm to generate a secret key. We are using DESede.
  3. Encode Text : For consistency across platform encode the plain text as byte using UTF-8 encoding.
  4. Encrypt Text : Instantiate Cipher with ENCRYPT_MODE, use the secret key and encrypt the bytes.
  5. Decrypt Text : Instantiate Cipher with DECRYPT_MODE, use the same secret key and decrypt the bytes.

All the above given steps and concept are same, we just replace algorithms.

import java.util.Base64;    
import javax.crypto.Cipher;  
import javax.crypto.KeyGenerator;   
import javax.crypto.SecretKey;  
public class EncryptionDecryptionAES {  
    static Cipher cipher;  

    public static void main(String[] args) throws Exception {
        /* 
         create key 
         If we need to generate a new key use a KeyGenerator
         If we have existing plaintext key use a SecretKeyFactory
        */ 
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128); // block size is 128bits
        SecretKey secretKey = keyGenerator.generateKey();

        /*
          Cipher Info
          Algorithm : for the encryption of electronic data
          mode of operation : to avoid repeated blocks encrypt to the same values.
          padding: ensuring messages are the proper length necessary for certain ciphers 
          mode/padding are not used with stream cyphers.  
         */
        cipher = Cipher.getInstance("AES"); //SunJCE provider AES algorithm, mode(optional) and padding schema(optional)  

        String plainText = "AES Symmetric Encryption Decryption";
        System.out.println("Plain Text Before Encryption: " + plainText);

        String encryptedText = encrypt(plainText, secretKey);
        System.out.println("Encrypted Text After Encryption: " + encryptedText);

        String decryptedText = decrypt(encryptedText, secretKey);
        System.out.println("Decrypted Text After Decryption: " + decryptedText);
    }

    public static String encrypt(String plainText, SecretKey secretKey)
            throws Exception {
        byte[] plainTextByte = plainText.getBytes();
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedByte = cipher.doFinal(plainTextByte);
        Base64.Encoder encoder = Base64.getEncoder();
        String encryptedText = encoder.encodeToString(encryptedByte);
        return encryptedText;
    }

    public static String decrypt(String encryptedText, SecretKey secretKey)
            throws Exception {
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] encryptedTextByte = decoder.decode(encryptedText);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
        String decryptedText = new String(decryptedByte);
        return decryptedText;
    }
}

Output:

Plain Text Before Encryption: AES Symmetric Encryption Decryption
Encrypted Text After Encryption: sY6vkQrWRg0fvRzbqSAYxepeBIXg4AySj7Xh3x4vDv8TBTkNiTfca7wW/dxiMMJl
Decrypted Text After Decryption: AES Symmetric Encryption Decryption

Source

Example: Cipher with two modes, they are encrypt and decrypt. we have to start every time after setting mode to encrypt or decrypt a text. enter image description here

How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?

For wireless debugging, Mac system and iPhone/Device should be on same network. For making on same network you can do as - Either you can start hotspot on Mac & connect that on iPhone/Device or vice versa.

On Mac

enter image description here

OR

On iPhone-

enter image description here

Xcode ? Window ? Devices and Simulators ? select devices Tab ? click connect via network enter image description here

https://help.apple.com/xcode/mac/9.0/index.html?localePath=en.lproj#/devbc48d1bad

What exactly does Double mean in java?

Double is a wrapper class,

The Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double.

In addition, this class provides several methods for converting a double to a String and a String to a double, as well as other constants and methods useful when dealing with a double.

The double data type,

The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

Check each datatype with their ranges : Java's Primitive Data Types.


Important Note : If you'r thinking to use double for precise values, you need to re-think before using it. Java Traps: double

"rm -rf" equivalent for Windows?

here is what worked for me:

Just try decreasing the length of the path. i.e :: Rename all folders that lead to such a file to smallest possible names. Say one letter names. Go on renaming upwards in the folder hierarchy. By this u effectively reduce the path length. Now finally try deleting the file straight away.

editing PATH variable on mac

environment.plst file loads first on MAC so put the path on it.

For 1st time use, use the following command

export PATH=$PATH: /path/to/set

How to delete the contents of a folder?

I resolved the issue with rmtree makedirs by adding time.sleep() between:

if os.path.isdir(folder_location):
    shutil.rmtree(folder_location)

time.sleep(.5)

os.makedirs(folder_location, 0o777)

How to extract text from a PDF file?

After trying textract (which seemed to have too many dependencies) and pypdf2 (which could not extract text from the pdfs I tested with) and tika (which was too slow) I ended up using pdftotext from xpdf (as already suggested in another answer) and just called the binary from python directly (you may need to adapt the path to pdftotext):

import os, subprocess
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
args = ["/usr/local/bin/pdftotext",
        '-enc',
        'UTF-8',
        "{}/my-pdf.pdf".format(SCRIPT_DIR),
        '-']
res = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = res.stdout.decode('utf-8')

There is pdftotext which does basically the same but this assumes pdftotext in /usr/local/bin whereas I am using this in AWS lambda and wanted to use it from the current directory.

Btw: For using this on lambda you need to put the binary and the dependency to libstdc++.so into your lambda function. I personally needed to compile xpdf. As instructions for this would blow up this answer I put them on my personal blog.

App.Config Transformation for projects which are not Web Projects in Visual Studio?

If you use a TFS online(Cloud version) and you want to transform the App.Config in a project, you can do the following without installing any extra tools. From VS => Unload the project => Edit project file => Go to the bottom of the file and add the following:

<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="AfterBuild" Condition="Exists('App.$(Configuration).config')">
<TransformXml Source="App.config" Transform="App.$(Configuration).config" Destination="$(OutDir)\$(AssemblyName).dll.config" />

AssemblyFile and Destination works for local use and TFS online(Cloud) server.

How can I force gradle to redownload dependencies?

You can tell Gradle to re-download some dependencies in the build script by flagging the dependency as 'changing'. Gradle will then check for updates every 24 hours, but this can be configured using the resolutionStrategy DSL. I find it useful to use this for for SNAPSHOT or NIGHTLY builds.

configurations.all {
    // Check for updates every build
    resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
}

Expanded:

dependencies {
    implementation group: "group", name: "projectA", version: "1.1-SNAPSHOT", changing: true
}

Condensed:

implementation('group:projectA:1.1-SNAPSHOT') { changing = true }

I found this solution at this forum thread.

Eclipse "this compilation unit is not on the build path of a java project"

For example if there are 4 project and a root project, add the other child projects to build path of root project. If there is not selection of build path, add below codes to .project file.

<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
    <name>rootProject</name>
    <comment></comment>
    <projects>
    </projects>
    <buildSpec>
        <buildCommand>
            <name>org.eclipse.jdt.core.javabuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>org.eclipse.m2e.core.maven2Builder</name>
            <arguments>
            </arguments>
        </buildCommand>
    </buildSpec>
    <natures>
        <nature>org.eclipse.jdt.core.javanature</nature>
        <nature>org.eclipse.m2e.core.maven2Nature</nature>
    </natures>
</projectDescription>

How to show Snackbar when Activity starts?

Try this

Snackbar.make(findViewById(android.R.id.content), "Got the Result", Snackbar.LENGTH_LONG)
                        .setAction("Submit", mOnClickListener)
                        .setActionTextColor(Color.RED)
                        .show();

About .bash_profile, .bashrc, and where should alias be written in?

Check out http://mywiki.wooledge.org/DotFiles for an excellent resource on the topic aside from man bash.

Summary:

  • You only log in once, and that's when ~/.bash_profile or ~/.profile is read and executed. Since everything you run from your login shell inherits the login shell's environment, you should put all your environment variables in there. Like LESS, PATH, MANPATH, LC_*, ... For an example, see: My .profile
  • Once you log in, you can run several more shells. Imagine logging in, running X, and in X starting a few terminals with bash shells. That means your login shell started X, which inherited your login shell's environment variables, which started your terminals, which started your non-login bash shells. Your environment variables were passed along in the whole chain, so your non-login shells don't need to load them anymore. Non-login shells only execute ~/.bashrc, not /.profile or ~/.bash_profile, for this exact reason, so in there define everything that only applies to bash. That's functions, aliases, bash-only variables like HISTSIZE (this is not an environment variable, don't export it!), shell options with set and shopt, etc. For an example, see: My .bashrc
  • Now, as part of UNIX peculiarity, a login-shell does NOT execute ~/.bashrc but only ~/.profile or ~/.bash_profile, so you should source that one manually from the latter. You'll see me do that in my ~/.profile too: source ~/.bashrc.

How to get primary key of table?

How about this:

SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'Your Database'
  AND TABLE_NAME = 'Your Table name'
  AND COLUMN_KEY = 'PRI';


SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'Your Database'
  AND TABLE_NAME = 'Your Table name'
  AND COLUMN_KEY = 'UNI';

CREATE TABLE LIKE A1 as A2

You can use below query to create table and insert distinct values into this table:

Select Distinct Column1, Column2, Column3 into New_Users from Old_Users

Preventing console window from closing on Visual Studio C/C++ Console application

A somewhat better solution:

atexit([] { system("PAUSE"); });

at the beginning of your program.

Pros:

  • can use std::exit()
  • can have multiple returns from main
  • you can run your program under the debugger
  • IDE independent (+ OS independent if you use the cin.sync(); cin.ignore(); trick instead of system("pause");)

Cons:

  • have to modify code
  • won't pause on std::terminate()
  • will still happen in your program outside of the IDE/debugger session; you can prevent this under Windows using:

extern "C" int __stdcall IsDebuggerPresent(void);
int main(int argc, char** argv) {
    if (IsDebuggerPresent())
        atexit([] {system("PAUSE"); });
    ...
}

SQL Server - after insert trigger - update another column in the same table

Use a computed column instead. It is almost always a better idea to use a computed column than a trigger.

See Example below of a computed column using the UPPER function:

create table #temp (test varchar (10), test2 AS upper(test))
insert #temp (test)
values ('test')
select * from #temp

And not to sound like a broken record or anything, but this is critically important. Never write a trigger that will not work correctly on multiple record inserts/updates/deletes. This is an extremely poor practice as sooner or later one of these will happen and your trigger will cause data integrity problems asw it won't fail precisely it will only run the process on one of the records. This can go a long time until someone discovers the mess and by themn it is often impossible to correctly fix the data.

How can I get a list of all values in select box?

As per the DOM structure you can use below code:

var x = document.getElementById('mySelect');
     var txt = "";
     var val = "";
     for (var i = 0; i < x.length; i++) {
         txt +=x[i].text + ",";
         val +=x[i].value + ",";
      }

Forbidden: You don't have permission to access / on this server, WAMP Error

This could be one solution.

public class RegisterActivity extends AppCompatActivity {

    private static final String TAG = "RegisterActivity";
    private static final String URL_FOR_REGISTRATION = "http://192.168.10.4/android_login_example/register.php";
    ProgressDialog progressDialog;

    private EditText signupInputName, signupInputEmail, signupInputPassword, signupInputAge;
    private Button btnSignUp;
    private Button btnLinkLogin;
    private RadioGroup genderRadioGroup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        // Progress dialog
        progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);

        signupInputName = (EditText) findViewById(R.id.signup_input_name);
        signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
        signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
        signupInputAge = (EditText) findViewById(R.id.signup_input_age);

        btnSignUp = (Button) findViewById(R.id.btn_signup);
        btnLinkLogin = (Button) findViewById(R.id.btn_link_login);

        genderRadioGroup = (RadioGroup) findViewById(R.id.gender_radio_group);
        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submitForm();
            }
        });
        btnLinkLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent i = new Intent(getApplicationContext(),MainActivity.class);
                startActivity(i);
            }
        });
    }

    private void submitForm() {

        int selectedId = genderRadioGroup.getCheckedRadioButtonId();
        String gender;
        if(selectedId == R.id.female_radio_btn)
            gender = "Female";
        else
            gender = "Male";

        registerUser(signupInputName.getText().toString(),
                signupInputEmail.getText().toString(),
                signupInputPassword.getText().toString(),
                gender,
                signupInputAge.getText().toString());
    }

    private void registerUser(final String name,  final String email, final String password,
                              final String gender, final String dob) {
        // Tag used to cancel the request
        String cancel_req_tag = "register";

        progressDialog.setMessage("Adding you ...");
        showDialog();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                URL_FOR_REGISTRATION, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Register Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    if (!error) {
                        String user = jObj.getJSONObject("user").getString("name");
                        Toast.makeText(getApplicationContext(), "Hi " + user +", You are successfully Added!", Toast.LENGTH_SHORT).show();

                        // Launch login activity
                        Intent intent = new Intent(
                                RegisterActivity.this,
                                MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {



                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Registration Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                // Posting params to register url
                Map<String, String> params = new HashMap<String, String>();
                params.put("name", name);
                params.put("email", email);
                params.put("password", password);
                params.put("gender", gender);
                params.put("age", dob);
                return params;
            }
        };
        // Adding request to request queue
        AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
    }

    private void showDialog() {
        if (!progressDialog.isShowing())
            progressDialog.show();
    }

    private void hideDialog() {
        if (progressDialog.isShowing())
            progressDialog.dismiss();
    }
    }

Why use String.Format?

I can see a number of reasons:

Readability

string s = string.Format("Hey, {0} it is the {1}st day of {2}.  I feel {3}!", _name, _day, _month, _feeling);

vs:

string s = "Hey," + _name + " it is the " + _day + "st day of " + _month + ".  I feel " + feeling + "!";

Format Specifiers (and this includes the fact you can write custom formatters)

string s = string.Format("Invoice number: {0:0000}", _invoiceNum);

vs:

string s = "Invoice Number = " + ("0000" + _invoiceNum).Substr(..... /*can't even be bothered to type it*/)

String Template Persistence

What if I want to store string templates in the database? With string formatting:

_id         _translation
  1         Welcome {0} to {1}.  Today is {2}.
  2         You have {0} products in your basket.
  3         Thank-you for your order.  Your {0} will arrive in {1} working days.

vs:

_id         _translation
  1         Welcome
  2         to
  3         .  Today is
  4         . 
  5         You have
  6         products in your basket.
  7         Someone
  8         just shoot
  9         the developer.

com.jcraft.jsch.JSchException: UnknownHostKey

You can also simply do

session.setConfig("StrictHostKeyChecking", "no");

It's not secure and it's a workaround not suitable for live environment as it will disable globally known host keys checking.

What is the difference between SQL Server 2012 Express versions?

Scroll down on that page and you'll see:

Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express)
This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.

That's the SQLEXPRWT_x64_ENU.exe download.... (WT = with tools)


Express with Advanced Services (contains the database engine, Express Tools, Reporting Services, and Full Text Search)
This package contains all the components of SQL Express. This is a larger download than “with Tools,” as it also includes both Full Text Search and Reporting Services.

That's the SQLEXPRADV_x64_ENU.exe download ... (ADV = Advanced Services)


The SQLEXPR_x64_ENU.exe file is just the database engine - no tools, no Reporting Services, no fulltext-search - just barebones engine.

Remove or adapt border of frame of legend using matplotlib

One more related question, since it took me forever to find the answer:

How to make the legend background blank (i.e. transparent, not white):

legend = plt.legend()
legend.get_frame().set_facecolor('none')

Warning, you want 'none' (the string). None means the default color instead.

What is the default scope of a method in Java?

The default scope is package-private. All classes in the same package can access the method/field/class. Package-private is stricter than protected and public scopes, but more permissive than private scope.

More information:
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
http://mindprod.com/jgloss/scope.html

Datatable vs Dataset

A DataTable object represents tabular data as an in-memory, tabular cache of rows, columns, and constraints. The DataSet consists of a collection of DataTable objects that you can relate to each other with DataRelation objects.

What is the simplest and most robust way to get the user's current location on Android?

After seeing all the answers, and question (Simplest and Robust). I got clicked about only library Android-ReactiveLocation.

When i made an location tracking app. Then i realized that its very typical to handle location tracking with optimised with battery.

So i want tell freshers and also developers who don't want to maintain their location code with future optimisations. Use this library.

ReactiveLocationProvider locationProvider = new 

    ReactiveLocationProvider(context);
    locationProvider.getLastKnownLocation()
        .subscribe(new Consumer<Location>() {
            @Override
            public void call(Location location) {
                doSthImportantWithObtainedLocation(location);
            }
        });

Dependencies to put in app level build.gradle

dependencies {
    ...
    compile 'pl.charmas.android:android-reactive-location2:2.1@aar'
    compile 'com.google.android.gms:play-services-location:11.0.4' //you can use newer GMS version if you need
    compile 'com.google.android.gms:play-services-places:11.0.4'
    compile 'io.reactivex:rxjava:2.0.5' //you can override RxJava version if you need
}

Pros to use this lib:

  • This lib is and will be actively maintained.
  • You dont worry about battery optimisation. As developers have done their best.
  • Easy installation, put dependency and play.
  • easily connect to Play Services API
  • obtain last known location
  • subscribe for location updates use
  • location settings API
  • manage geofences
  • geocode location to list of addresses
  • activity recognition
  • use current place API fetch place
  • autocomplete suggestions

How to reset par(mfrow) in R

You can reset the plot by doing this:

dev.off()

How to create exe of a console application

For .NET Core 2.2 you can publish the application and set the target to be a self-contained executable.

In Visual Studio right click your console application project. Select publish to folder and set the profile settings like so:

Visual Studio Publish Menu

You'll find your compiled code with the .exe in the publish folder.

How to check if a file exists in a shell script

You're missing a required space between the bracket and -e:

#!/bin/bash
if [ -e x.txt ]
then
    echo "ok"
else
    echo "nok"
fi

How to hide a div from code (c#)

one fast and simple way is to make the div as

<div runat="server" id="MyDiv"></div>

and on code behind you set MyDiv.Visible=false

How can I get a vertical scrollbar in my ListBox?

The problem with your solution is you're putting a scrollbar around a ListBox where you probably want to put it inside the ListBox.

If you want to force a scrollbar in your ListBox, use the ScrollBar.VerticalScrollBarVisibility attached property.

<ListBox 
    ItemsSource="{Binding}" 
    ScrollViewer.VerticalScrollBarVisibility="Visible">
</ListBox>

Setting this value to Auto will popup the scrollbar on an as needed basis.

In javascript, how do you search an array for a substring match

In your specific case, you can do it just with a boring old counter:

var index, value, result;
for (index = 0; index < windowArray.length; ++index) {
    value = windowArray[index];
    if (value.substring(0, 3) === "id-") {
        // You've found it, the full text is in `value`.
        // So you might grab it and break the loop, although
        // really what you do having found it depends on
        // what you need.
        result = value;
        break;
    }
}

// Use `result` here, it will be `undefined` if not found

But if your array is sparse, you can do it more efficiently with a properly-designed for..in loop:

var key, value, result;
for (key in windowArray) {
    if (windowArray.hasOwnProperty(key) && !isNaN(parseInt(key, 10))) {
        value = windowArray[key];
        if (value.substring(0, 3) === "id-") {
            // You've found it, the full text is in `value`.
            // So you might grab it and break the loop, although
            // really what you do having found it depends on
            // what you need.
            result = value;
            break;
        }
    }
}

// Use `result` here, it will be `undefined` if not found

Beware naive for..in loops that don't have the hasOwnProperty and !isNaN(parseInt(key, 10)) checks; here's why.


Off-topic:

Another way to write

var windowArray = new Array ("item","thing","id-3-text","class");

is

var windowArray = ["item","thing","id-3-text","class"];

...which is less typing for you, and perhaps (this bit is subjective) a bit more easily read. The two statements have exactly the same result: A new array with those contents.

"Auth Failed" error with EGit and GitHub

After spending hours looking for the solution to this problem, I finally struck gold by making the changes mentioned on an Eclipse Forum.

Steps:

Prerequisites: mysysgit is installed with default configuration.

1.Create the file C:/Users/Username/.ssh/config (Replace "Username" with your Windows 7 user name. (e.g. C:/Users/John/.ssh/config)) and put this in it:

Host github.com
HostName github.com
User git
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa

2.Try setting up the remote repository now in Eclipse.

Cheers. It should work perfectly.

Refresh image with a new one at the same url

One answer is to hackishly add some get query parameter like has been suggested.

A better answer is to emit a couple of extra options in your HTTP header.

Pragma: no-cache
Expires: Fri, 30 Oct 1998 14:19:41 GMT
Cache-Control: no-cache, must-revalidate

By providing a date in the past, it won't be cached by the browser. Cache-Control was added in HTTP/1.1 and the must-revalidate tag indicates that proxies should never serve up an old image even under extenuating circumstances, and the Pragma: no-cache isn't really necessary for current modern browsers/caches but may help with some crufty broken old implementations.

Should a retrieval method return 'null' or throw an exception when it can't produce the return value?

Return a null instead of throwing an exception and clearly document the possibility of a null return value in the API documentation. If the calling code doesn't honor the API and check for the null case, it will most probably result in some sort of "null pointer exception" anyway :)

In C++, I can think of 3 different flavors of setting up a method that finds an object.

Option A

Object *findObject(Key &key);

Return null when an object can't be found. Nice and simple. I'd go with this one. The alternative approaches below are for people who don't hate out-params.

Option B

void findObject(Key &key, Object &found);

Pass in a reference to variable that will be receiving the object. The method thrown an exception when an object can't be found. This convention is probably more suitable if it's not really expected for an object not to be found -- hence you throw an exception to signify that it's an unexpected case.

Option C

bool findObject(Key &key, Object &found);

The method returns false when an object can't be found. The advantage of this over option A is that you can check for the error case in one clear step:

if (!findObject(myKey, myObj)) { ...

Detect if a page has a vertical scrollbar?

Other solutions didn't work in one of my projects and I've ending up checking overflow css property

function haveScrollbar() {
    var style = window.getComputedStyle(document.body);
    return style["overflow-y"] != "hidden";
}

but it will only work if scrollbar appear disappear by changing the prop it will not work if the content is equal or smaller than the window.

Vim for Windows - What do I type to save and exit from a file?

  • Press i or a to get into insert mode, and type the message of choice

  • Press ESC several times to get out of insert mode, or any other mode you might have run into by accident

    • to save, :wq, :x or ZZ

    • to exit without saving, :q! or ZQ

To reload a file and undo all changes you have made...:

Press several times ESC and then enter :e!.

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

I also encountered this mongoose error CastError: Cast to ObjectId failed for value \"583fe2c488cf652d4c6b45d1\" at path \"_id\" for model User

So I run npm list command to verify the mongodb and mongoose version in my local. Heres the report: ......
......
+-- [email protected]
+-- [email protected]
.....

It seems there's an issue on this mongodb version so what I did is I uninstall and try to use different version such as 2.2.16

$ npm uninstall mongodb, it will delete the mongodb from your node_modules directory. After that install the lower version of mongodb.
$ npm install [email protected]
Finally, I restart the app and the CastError is gone!!

How do I do an OR filter in a Django query?

There is Q objects that allow to complex lookups. Example:

from django.db.models import Q

Item.objects.filter(Q(creator=owner) | Q(moderated=False))

Set position / size of UI element as percentage of screen size

For TextView and it's descendants (e.g., Button) you can get the display size from the WindowManager and then set the TextView height to be some fraction of it:

Button btn = new Button (this);
android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 
btn.setHeight((int)(display.getHeight()*0.68));

Posting form to different MVC post action depending on the clicked submit button

you can use ajax calls to call different methods without a postback

$.ajax({
    type: "POST",
     url: "@(Url.Action("Action", "Controller"))",
     data: {id: 'id', id1: 'id1' },
     contentType: "application/json; charset=utf-8",
     cache: false,
     async: true,
     success: function (result) {
        //do something
     }
});

Can I get image from canvas element and use it in img src tag?

Do this. Add this to the bottom of your doc just before you close the body tag.

<script>
    function canvasToImg() {
      var canvas = document.getElementById("yourCanvasID");
      var ctx=canvas.getContext("2d");
      //draw a red box
      ctx.fillStyle="#FF0000";
      ctx.fillRect(10,10,30,30);

      var url = canvas.toDataURL();

      var newImg = document.createElement("img"); // create img tag
      newImg.src = url;
      document.body.appendChild(newImg); // add to end of your document
    }

    canvasToImg(); //execute the function
</script>

Of course somewhere in your doc you need the canvas tag that it will grab.

<canvas id="yourCanvasID" />

ActiveMQ connection refused

I had also similar problem. In my case brokerUrl was not configured properly. So that's way I received following Error:

Cause: Error While attempting to add new Connection to the pool: nested exception is javax.jms.JMSException: Could not connect to broker URL : tcp://localhost:61616. Reason: java.net.ConnectException: Connection refused

& I resolved it following way.

   ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();

  connectionFactory.setBrokerURL("tcp://hostname:61616");
  connectionFactory.setUserName("admin");
  connectionFactory.setPassword("admin");

How to return history of validation loss in Keras

Another option is CSVLogger: https://keras.io/callbacks/#csvlogger. It creates a csv file appending the result of each epoch. Even if you interrupt training, you get to see how it evolved.

extract date only from given timestamp in oracle sql

try this type of format:

SELECT to_char(sysdate,'dd-mm-rrrr') FROM dual

Should I call Close() or Dispose() for stream objects?

For what it's worth, the source code for Stream.Close explains why there are two methods:

// Stream used to require that all cleanup logic went into Close(),
// which was thought up before we invented IDisposable.  However, we
// need to follow the IDisposable pattern so that users can write
// sensible subclasses without needing to inspect all their base
// classes, and without worrying about version brittleness, from a
// base class switching to the Dispose pattern.  We're moving
// Stream to the Dispose(bool) pattern - that's where all subclasses
// should put their cleanup now.

In short, Close is only there because it predates Dispose, and it can't be deleted for compatibility reasons.

Javascript logical "!==" operator?

reference here

!== is the strict not equal operator and only returns a value of true if both the operands are not equal and/or not of the same type. The following examples return a Boolean true:

a !== b 
a !== "2" 
4 !== '4' 

How to take column-slices of dataframe in pandas

Note: .ix has been deprecated since Pandas v0.20. You should instead use .loc or .iloc, as appropriate.

The DataFrame.ix index is what you want to be accessing. It's a little confusing (I agree that Pandas indexing is perplexing at times!), but the following seems to do what you want:

>>> df = DataFrame(np.random.rand(4,5), columns = list('abcde'))
>>> df.ix[:,'b':]
      b         c         d         e
0  0.418762  0.042369  0.869203  0.972314
1  0.991058  0.510228  0.594784  0.534366
2  0.407472  0.259811  0.396664  0.894202
3  0.726168  0.139531  0.324932  0.906575

where .ix[row slice, column slice] is what is being interpreted. More on Pandas indexing here: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-advanced

How to install PyQt5 on Windows?

If you have python installed completely, it can save you the hassle. All you need to do is enter the following command in your respective shell:

pip install pyqt5

And contrary to popular belief, AS LONG AS YOU HAVE PIP INSTALLED, you can do this on virtually any OS... Hope this helped!

Jquery Validate custom error message location

This Worked for me

Actually error is a array which contain error message and other values for elements we pass, you can console.log(error); and see. Inside if condition "error.appendTo($(element).parents('div').find($('.errorEmail')));" Is nothing but finding html element in code and passing the error message.

    $("form[name='contactUs']").validate({
rules: {
    message: 'required',
    name: "required",
    phone_number: {
        required: true,
        minlength: 10,
        maxlength: 10,
        number: false
    },
    email: {
        required: true,
        email: true
    }
},
messages: {
    name: "Please enter your name",
    email: "Please enter a valid email address",
    message: "Please enter your message",
    phone_number: "Please enter a valid mobile number"
},
errorPlacement: function(error, element) {
        $("#errorText").empty();

        if(error[0].htmlFor == 'name')
        {
            error.appendTo($(element).parents('div').find($('.errorName')));
        }
        if(error[0].htmlFor == 'email')
        {
            error.appendTo($(element).parents('div').find($('.errorEmail')));
        }
        if(error[0].htmlFor == 'phone_number')
        {
            error.appendTo($(element).parents('div').find($('.errorMobile')));
        }
        if(error[0].htmlFor == 'message')
        {
            error.appendTo($(element).parents('div').find($('.errorMessage')));
        }
      }
    });

CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

Look in the Cmakelists.txt if you find ARM you need to install C++ for ARM

It's these packages:

C++ Universal Windows Platform for ARM64 "Not Required"

Visual C++ Compilers and libraries for ARM "Not Required"

Visual C++ Compilers and libraries for ARM64 "Very Likely Required"

Required for finding Threads on ARM 
enable_language(C) 
enable_language(CXX)

Then the problems

No CMAKE_C_COMPILER could be found.

No CMAKE_CXX_COMPILER could be found.

Might disappear unless you specify c compiler like clang, and maybe installing clang will work in other favour.

You can with optional remove in cmakelists.txt both with # before enable_language if you are not compiling for ARM.

How do I create dynamic variable names inside a loop?

var marker  = [];
for ( var i = 0; i < 6; i++) {               
     marker[i]='Hello'+i;                    
}
console.log(marker);
alert(marker);

Is it possible to compile a program written in Python?

You dont have to compile it. the first you use it (import) it is compiled by the CPython interpreter. But if you really want to compile there are several options.

To compile to exe

Or 2 compile just a specific *.py file, you can just use

import py_compile
py_compile.compile("yourpythoncode.py")

How to use ES6 Fat Arrow to .filter() an array of objects

You can't implicitly return with an if, you would need the braces:

let adults = family.filter(person => { if (person.age > 18) return person} );

It can be simplified though:

let adults = family.filter(person => person.age > 18);

SSRS the definition of the report is invalid

This occurred for me due to changing the names of certain dataset fields within BIDS that were being referenced by parameters. I forgot to go into the parameters and reassign a default value (the default value of the parameter didn't automatically change to the newly renamed dataset field. Instead .

How to run java application by .bat file

javac Application.java

java Application

pause

The javac command will compile the java program and the java command will run the program and pause will pause the result until you cross it.

Counting the number of option tags in a select tag in jQuery

Ok, i had a few problems because i was inside a

$('.my-dropdown').live('click', function(){  
});

I had multiples inside my page that's why i used a class.

My drop down was filled automatically by a ajax request when i clicked it, so i only had the element $(this)

so...

I had to do:

$('.my-dropdown').live('click', function(){
  total_tems = $(this).find('option').length;
});

Fastest way to check if a string matches a regexp in ruby?

This is the benchmark I have run after finding some articles around the net.

With 2.4.0 the winner is re.match?(str) (as suggested by @wiktor-stribizew), on previous versions, re =~ str seems to be fastest, although str =~ re is almost as fast.

#!/usr/bin/env ruby
require 'benchmark'

str = "aacaabc"
re = Regexp.new('a+b').freeze

N = 4_000_000

Benchmark.bm do |b|
    b.report("str.match re\t") { N.times { str.match re } }
    b.report("str =~ re\t")    { N.times { str =~ re } }
    b.report("str[re]  \t")    { N.times { str[re] } }
    b.report("re =~ str\t")    { N.times { re =~ str } }
    b.report("re.match str\t") { N.times { re.match str } }
    if re.respond_to?(:match?)
        b.report("re.match? str\t") { N.times { re.match? str } }
    end
end

Results MRI 1.9.3-o551:

$ ./bench-re.rb  | sort -t $'\t' -k 2
       user     system      total        real
re =~ str         2.390000   0.000000   2.390000 (  2.397331)
str =~ re         2.450000   0.000000   2.450000 (  2.446893)
str[re]           2.940000   0.010000   2.950000 (  2.941666)
re.match str      3.620000   0.000000   3.620000 (  3.619922)
str.match re      4.180000   0.000000   4.180000 (  4.180083)

Results MRI 2.1.5:

$ ./bench-re.rb  | sort -t $'\t' -k 2
       user     system      total        real
re =~ str         1.150000   0.000000   1.150000 (  1.144880)
str =~ re         1.160000   0.000000   1.160000 (  1.150691)
str[re]           1.330000   0.000000   1.330000 (  1.337064)
re.match str      2.250000   0.000000   2.250000 (  2.255142)
str.match re      2.270000   0.000000   2.270000 (  2.270948)

Results MRI 2.3.3 (there is a regression in regex matching, it seems):

$ ./bench-re.rb  | sort -t $'\t' -k 2
       user     system      total        real
re =~ str         3.540000   0.000000   3.540000 (  3.535881)
str =~ re         3.560000   0.000000   3.560000 (  3.560657)
str[re]           4.300000   0.000000   4.300000 (  4.299403)
re.match str      5.210000   0.010000   5.220000 (  5.213041)
str.match re      6.000000   0.000000   6.000000 (  6.000465)

Results MRI 2.4.0:

$ ./bench-re.rb  | sort -t $'\t' -k 2
       user     system      total        real
re.match? str     0.690000   0.010000   0.700000 (  0.682934)
re =~ str         1.040000   0.000000   1.040000 (  1.035863)
str =~ re         1.040000   0.000000   1.040000 (  1.042963)
str[re]           1.340000   0.000000   1.340000 (  1.339704)
re.match str      2.040000   0.000000   2.040000 (  2.046464)
str.match re      2.180000   0.000000   2.180000 (  2.174691)

Eclipse - debugger doesn't stop at breakpoint

If you are on Eclipse,

Right click on your project folder under "Package Explorer".

Goto Source -> Clean up and choose your project.

This will cleanup any mess and your break-point should work now.

This Row already belongs to another table error when trying to add rows?

You need to create a new Row with the values from dr first. A DataRow can only belong to a single DataTable.

You can also use Add which takes an array of values:

myTable.Rows.Add(dr.ItemArray)

Or probably even better:

// This works because the row was added to the original table.
myTable.ImportRow(dr);

// The following won't work. No data will be added or exception thrown.
var drFail = dt.NewRow()
drFail["CustomerID"] = "[Your data here]";
// dt.Rows.Add(row); // Uncomment for import to succeed.
myTable.ImportRow(drFail);

Memory Allocation "Error: cannot allocate vector of size 75.1 Mb"

gc() can help

saving data as .RData, closing, re-opening R, and loading the RData can help.

see my answer here: https://stackoverflow.com/a/24754706/190791 for more details

Android: How can I get the current foreground activity (from a service)?

It can be done by:

  1. Implement your own application class, register for ActivityLifecycleCallbacks - this way you can see what is going on with our app. On every on resume the callback assigns the current visible activity on the screen and on pause it removes the assignment. It uses method registerActivityLifecycleCallbacks() which was added in API 14.

    public class App extends Application {
    
    private Activity activeActivity;
    
    @Override
    public void onCreate() {
        super.onCreate();
        setupActivityListener();
    }
    
    private void setupActivityListener() {
    registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            }
            @Override
            public void onActivityStarted(Activity activity) {
            }
            @Override
            public void onActivityResumed(Activity activity) {
                activeActivity = activity;
            }
            @Override
            public void onActivityPaused(Activity activity) {
                activeActivity = null;
            }
            @Override
            public void onActivityStopped(Activity activity) {
            }
            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }
            @Override
            public void onActivityDestroyed(Activity activity) {
            }
        });
    }
    
    public Activity getActiveActivity(){
        return activeActivity;
    }
    
    }
    
  2. In your service call getApplication() and cast it to your app class name (App in this case). Than you can call app.getActiveActivity() - that will give you a current visible Activity (or null when no activity is visible). You can get the name of the Activity by calling activeActivity.getClass().getSimpleName()

How can I make a TextBox be a "password box" and display stars when using MVVM?

As Tasnim Fabiha mentioned, it is possible to change font for TextBox in order to show only dots/asterisks. But I wasn't able to find his font...so I give you my working example:

<TextBox Text="{Binding Password}" 
     FontFamily="pack://application:,,,/Resources/#password" />

Just copy-paste won't work. Firstly you have to download mentioned font "password.ttf" link: https://github.com/davidagraf/passwd/blob/master/public/ttf/password.ttf Then copy that to your project Resources folder (Project->Properties->Resources->Add resource->Add existing file). Then set it's Build Action to: Resource.

After this you will see just dots, but you can still copy text from that, so it is needed to disable CTRL+C shortcut like this:

<TextBox Text="{Binding Password}" 
     FontFamily="pack://application:,,,/Resources/#password" > 
    <TextBox.InputBindings>
        <!--Disable CTRL+C -->
        <KeyBinding Command="ApplicationCommands.NotACommand"
            Key="C"
            Modifiers="Control" />
    </TextBox.InputBindings>
</TextBox>

taking input of a string word by word

(This is for the benefit of others who may refer)

You can simply use cin and a char array. The cin input is delimited by the first whitespace it encounters.

#include<iostream>
using namespace std;

main()
{
    char word[50];
    cin>>word;
    while(word){
        //Do stuff with word[]
        cin>>word;
    }
}

How to sort an array of integers correctly

to handle undefined, null, and NaN: Null behaves like 0, NaN and undefined goes to end.

array = [3, 5, -1, 1, NaN, 6, undefined, 2, null]
array.sort((a,b) => isNaN(a) || a-b)
// [-1, null, 1, 2, 3, 5, 6, NaN, undefined]

NSString with \n or line break

I just ran into the same issue when overloading -description for a subclass of NSObject. In this situation I was able to use carriage return (\r) instead of newline (\n) to create a line break.

[NSString stringWithFormat:@"%@\r%@", mystring1,mystring2];

How to center content in a bootstrap column?

[Updated Dec 2020]: Tested and Included 5.0 version of Bootstrap.


I know this question is old. And the question did not mentioned which version of Bootstrap he was using. So i'll assume the answer to this question is resolved.

If any of you (like me) stumbled upon this question and looking for answer using current bootstrap 5.0 (2020) and 4.5 (2019) framework, then here's the solution.

Bootstrap 4.5 and 5.0

Use d-flex justify-content-center on your column div. This will center everything inside that column.

<div class="row">
    <div class="col-4 d-flex justify-content-center">
        // Image
    </div>
</div>

If you want to align the text inside the col just use text-center

<div class="row">
    <div class="col-4 text-center">
        // text only
    </div>
</div>

If you have text and image inside the column, you need to use d-flex justify-content-center and text-center.

<div class="row">
    <div class="col-4 d-flex justify-content-center text-center">
        // for image and text
    </div>
</div>

How can I break up this long line in Python?

That's a start. It's not a bad practice to define your longer strings outside of the code that uses them. It's a way to separate data and behavior. Your first option is to join string literals together implicitly by making them adjacent to one another:

("This is the first line of my text, "
"which will be joined to a second.")

Or with line ending continuations, which is a little more fragile, as this works:

"This is the first line of my text, " \
"which will be joined to a second."

But this doesn't:

"This is the first line of my text, " \ 
"which will be joined to a second."

See the difference? No? Well you won't when it's your code either.

The downside to implicit joining is that it only works with string literals, not with strings taken from variables, so things can get a little more hairy when you refactor. Also, you can only interpolate formatting on the combined string as a whole.

Alternatively, you can join explicitly using the concatenation operator (+):

("This is the first line of my text, " + 
"which will be joined to a second.")

Explicit is better than implicit, as the zen of python says, but this creates three strings instead of one, and uses twice as much memory: there are the two you have written, plus one which is the two of them joined together, so you have to know when to ignore the zen. The upside is you can apply formatting to any of the substrings separately on each line, or to the whole lot from outside the parentheses.

Finally, you can use triple-quoted strings:

"""This is the first line of my text
which will be joined to a second."""

This is often my favorite, though its behavior is slightly different as the newline and any leading whitespace on subsequent lines will show up in your final string. You can eliminate the newline with an escaping backslash.

"""This is the first line of my text \
which will be joined to a second."""

This has the same problem as the same technique above, in that correct code only differs from incorrect code by invisible whitespace.

Which one is "best" depends on your particular situation, but the answer is not simply aesthetic, but one of subtly different behaviors.

How to pass an array to a function in VBA?

This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array() then pass the variable into your function, VBA will be happy.

Sub test()
    Dim fString As String
    Dim arr() As Variant
    arr = Array("foo", "bar")
    fString = processArr(arr)
End Sub

Also your function processArr() could be written as:

Function processArr(arr() As Variant) As String
    processArr = Replace(Join(arr()), " ", "")
End Function

If you are into the whole brevity thing.

How to get the real path of Java application at runtime?

I use this method to get complete path to jar or exe.

File pto = new File(YourClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());

pto.getAbsolutePath());

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

if you don't want to use json.parse(json.stringify(object)) you could create recursively key-value copies:

function copy(item){
  let result = null;
  if(!item) return result;
  if(Array.isArray(item)){
    result = [];
    item.forEach(element=>{
      result.push(copy(element));
    });
  }
  else if(item instanceof Object && !(item instanceof Function)){ 
    result = {};
    for(let key in item){
      if(key){
        result[key] = copy(item[key]);
      }
    }
  }
  return result || item;
}

But the best way is to create a class that can return a clone of it self

class MyClass{
    data = null;
    constructor(values){ this.data = values }
    toString(){ console.log("MyClass: "+this.data.toString(;) }
    remove(id){ this.data = data.filter(d=>d.id!==id) }
    clone(){ return new MyClass(this.data) }
}

Java String.split() Regex

String[] ops = str.split("\\s*[a-zA-Z]+\\s*");
String[] notops = str.split("\\s*[^a-zA-Z]+\\s*");
String[] res = new String[ops.length+notops.length-1];
for(int i=0; i<res.length; i++) res[i] = i%2==0 ? notops[i/2] : ops[i/2+1];

This should do it. Everything nicely stored in res.

How to make HTML element resizable using pure Javascript?

what about a pure css3 solution?

div {
    resize: both;
    overflow: auto;
} 

MDN Web Docs

W3Schools example

Browser support

Missing styles. Is the correct theme chosen for this layout?

It can be fixed by changing your theme in styles.xml from Theme.AppCompat.Light.DarkActionBar to Base.Theme.AppCompat.Light.DarkActionBar

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

to

<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

and clean the project. It will surely help.

What is the difference between .yaml and .yml extension?

As @David Heffeman indicates the recommendation is to use .yaml when possible, and the recommendation has been that way since September 2006.

That some projects use .yml is mostly because of ignorance of the implementers/documenters: they wanted to use YAML because of readability, or some other feature not available in other formats, were not familiar with the recommendation and and just implemented what worked, maybe after looking at some other project/library (without questioning whether what was done is correct).

The best way to approach this is to be rigorous when creating new files (i.e. use .yaml) and be permissive when accepting input (i.e. allow .yml when you encounter it), possible automatically upgrading/correcting these errors when possible.

The other recommendation I have is to document the argument(s) why you have to use .yml, when you think you have to. That way you don't look like an ignoramus, and give others the opportunity to understand your reasoning. Of course "everybody else is doing it" and "On Google .yml has more pages than .yaml" are not arguments, they are just statistics about the popularity of project(s) that have it wrong or right (with regards to the extension of YAML files). You can try to prove that some projects are popular, just because they use a .yml extension instead of the correct .yaml, but I think you will be hard pressed to do so.

Some projects realize (too late) that they use the incorrect extension (e.g. originally docker-compose used .yml, but in later versions started to use .yaml, although they still support .yml). Others still seem ignorant about the correct extension, like AppVeyor early 2019, but allow you to specify the configuration file for a project, including extension. This allows you to get the configuration file out of your face as well as giving it the proper extension: I use .appveyor.yaml instead of appveyor.yml for building the windows wheels of my YAML parser for Python).


On the other hand:

The Yaml (sic!) component of Symfony2 implements a selected subset of features defined in the YAML 1.2 version specification.

So it seems fitting that they also use a subset of the recommended extension.

What is the minimum length of a valid international phone number?

As per different sources, I think the minimum length in E-164 format depends on country to country. For eg:

  • For Israel: The minimum phone number length (excluding the country code) is 8 digits. - Official Source (Country Code 972)
  • For Sweden : The minimum number length (excluding the country code) is 7 digits. - Official Source? (country code 46)

  • For Solomon Islands its 5 for fixed line phones. - Source (country code 677)

... and so on. So including country code, the minimum length is 9 digits for Sweden and 11 for Israel and 8 for Solomon Islands.

Edit (Clean Solution): Actually, Instead of validating an international phone number by having different checks like length etc, you can use the Google's libphonenumber library. It can validate a phone number in E164 format directly. It will take into account everything and you don't even need to give the country if the number is in valid E164 format. Its pretty good! Taking an example:

String phoneNumberE164Format = "+14167129018"
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
    PhoneNumber phoneNumberProto = phoneUtil.parse(phoneNumberE164Format, null);
    boolean isValid = phoneUtil.isValidNumber(phoneNumberProto); // returns true if valid
    if (isValid) {
        // Actions to perform if the number is valid
    } else {
        // Do necessary actions if its not valid 
    }
} catch (NumberParseException e) {
    System.err.println("NumberParseException was thrown: " + e.toString());
}

If you know the country for which you are validating the numbers, you don;t even need the E164 format and can specify the country in .parse function instead of passing null.

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

I had the same error and I solved it with MultiDex, like described on this link : https://developer.android.com/studio/build/multidex.html


Sometimes it is not enough just to enable MultiDex.

If any class that's required during startup is not provided in the primary DEX file, then your app crashes with the error java.lang.NoClassDefFoundError. https://developer.android.com/studio/build/multidex#keep

FirebaseInitProvider is required during startup.

So you must manually specify FirebaseInitProvider as required in the primary DEX file.

build.gradle file

android {
    buildTypes {
        release {
            multiDexKeepFile file('multidex-config.txt')
            ...
        }
    }
}

multidex-config.txt (in the same directory as the build.gradle file)

com/google/firebase/provider/FirebaseInitProvider.class

How to write JUnit test with Spring Autowire?

A JUnit4 test with Autowired and bean mocking (Mockito):

// JUnit starts spring context
@RunWith(SpringRunner.class)
// spring load context configuration from AppConfig class
@ContextConfiguration(classes = AppConfig.class)
// overriding some properties with test values if you need
@TestPropertySource(properties = {
        "spring.someConfigValue=your-test-value",
})
public class PersonServiceTest {

    @MockBean
    private PersonRepository repository;

    @Autowired
    private PersonService personService; // uses PersonRepository    

    @Test
    public void testSomething() {
        // using Mockito
        when(repository.findByName(any())).thenReturn(Collection.emptyList());
        Person person = new Person();
        person.setName(null);

        // when
        boolean found = personService.checkSomething(person);

        // then
        assertTrue(found, "Something is wrong");
    }
}

How to enable authentication on MongoDB through Docker?

I have hard time when trying to

  • Create other db than admin
  • Add new users and enable authentication to the db above

So I made 2020 answer here

My directory looks like this

+-- docker-compose.yml
+-- mongo-entrypoint
    +-- entrypoint.js

My docker-compose.yml looks like this

version: '3.4'
services:
  mongo-container:
    # If you need to connect to your db from outside this container 
    network_mode: host
    image: mongo:4.2
    environment:
        - MONGO_INITDB_ROOT_USERNAME=admin
        - MONGO_INITDB_ROOT_PASSWORD=pass
    ports:
      - "27017:27017"
    volumes:
      - "$PWD/mongo-entrypoint/:/docker-entrypoint-initdb.d/"
    command: mongod

Please change admin and pass with your need.

Inside mongo-entrypoint, I have entrypoint.js file with this content:

var db = connect("mongodb://admin:pass@localhost:27017/admin");

db = db.getSiblingDB('new_db'); // we can not use "use" statement here to switch db

db.createUser(
    {
        user: "user",
        pwd: "pass",
        roles: [ { role: "readWrite", db: "new_db"} ],
        passwordDigestor: "server",
    }
)

Here again you need to change admin:pass to your root mongo credentials in your docker-compose.yml that you stated before. In additional you need to change new_db, user, pass to your new database name and credentials that you need.

Now you can:

docker-compose up -d

And connect to this db from localhost, please note that I already have mongo cli, you can install it or you can exec to the container above to use mongo command:

mongo new_db -u user -p pass

Or you can connect from other computer

mongo host:27017/new_db -u user -p pass

My git repository: https://github.com/sexydevops/docker-compose-mongo

Hope it can help someone, I lost my afternoon for this ;)

Install specific branch from github using Npm

Tried suggested answers, but got it working only with this prefix approach:

npm i github:user/repo.git#version --save -D

How to set a variable inside a loop for /F

Try this:

setlocal EnableDelayedExpansion

...

for /F "tokens=*" %%a in ('type %FileName%') do (
    set z=%%a
    echo !z!
    echo %%a
)

PHP - remove all non-numeric characters from a string

You can use preg_replace in this case;

$res = preg_replace("/[^0-9]/", "", "Every 6 Months" );

$res return 6 in this case.

If want also to include decimal separator or thousand separator check this example:

$res = preg_replace("/[^0-9.]/", "", "$ 123.099");

$res returns "123.099" in this case

Include period as decimal separator or thousand separator: "/[^0-9.]/"

Include coma as decimal separator or thousand separator: "/[^0-9,]/"

Include period and coma as decimal separator and thousand separator: "/[^0-9,.]/"

What is the best way to implement "remember me" for a website?

Store their UserId and a RememberMeToken. When they login with remember me checked generate a new RememberMeToken (which invalidate any other machines which are marked are remember me).

When they return look them up by the remember me token and make sure the UserId matches.

Creating and appending text to txt file in VB.NET

Don't check File.Exists() like that. In fact, the whole thing is over-complicated. This should do what you need:

Dim strFile As String = $@"C:\ErrorLog_{DateTime.Today:dd-MMM-yyyy}.txt"
File.AppendAllText(strFile, $"Error Message in  Occured at-- {DateTime.Now}{Environment.NewLine}")

Got it all down to two lines of code :)

How can my iphone app detect its own version number?

As I describe here, I use a script to rewrite a header file with my current Subversion revision number. That revision number is stored in the kRevisionNumber constant. I can then access the version and revision number using something similar to the following:

[NSString stringWithFormat:@"Version %@ (%@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"], kRevisionNumber]

which will create a string of the format "Version 1.0 (51)".

Select data between a date/time range

In a simple way it can be queried as

select * from hockey_stats 
where game_date between '2018-01-01' and '2018-01-31';

This works if time is not a concern.

Considering time also follow in the following way:

select * from hockey_stats where (game_date between '2018-02-05 01:20:00' and '2018-02-05 03:50:00');

Note this is for MySQL server.

Can you have if-then-else logic in SQL?

Please check whether this helps:

select TOP 1
    product, 
    price 
from 
    table1 
where 
    (project=1 OR Customer=2 OR company=3) AND
    price IS NOT NULL
ORDER BY company 

PDO closing connection

I created a derived class to have a more self-documented instruction instead of $conn=null;.

class CMyPDO extends PDO {
    public function __construct($dsn, $username = null, $password = null, array $options = null) {
        parent::__construct($dsn, $username, $password, $options);
    }

    static function getNewConnection() {
        $conn=null;
        try {
            $conn = new CMyPDO("mysql:host=$host;dbname=$dbname",$user,$pass);
        }
        catch (PDOException $exc) {
            echo $exc->getMessage();
        }
        return $conn;
    }

    static function closeConnection(&$conn) {
        $conn=null;
    }
}

So I can call my code between:

$conn=CMyPDO::getNewConnection();
// my code
CMyPDO::closeConnection($conn);

How to create a multi line body in C# System.Net.Mail.MailMessage

In case you dont need the message body in html, turn it off:

message.IsBodyHtml = false;

then use e.g:

message.Body = "First line" + Environment.NewLine + 
               "Second line";

but if you need to have it in html for some reason, use the html-tag:

message.Body = "First line <br /> Second line";

How to enable Bootstrap tooltip on disabled button?

Try this example:

Tooltips must be initialized with jQuery: select the specified element and call the tooltip() method in JavaScript:

$(document).ready(function () {
    $('[data-toggle="tooltip"]').tooltip();
});

Add CSS:

.tool-tip {
  display: inline-block;
}

.tool-tip [disabled] {
  pointer-events: none;
}

And your html:

<span class="tool-tip" data-toggle="tooltip" data-placement="bottom" title="I am Tooltip">
    <button disabled="disabled">I am disabled</button>
</span>

How to find a value in an array and remove it by using PHP array functions?

You need to find the key of the array first, this can be done using array_search()

Once done, use the unset()

<?php
$array = array( 'apple', 'orange', 'pear' );

unset( $array[array_search( 'orange', $array )] );
?>

How to use if-else logic in Java 8 stream forEach

In most cases, when you find yourself using forEach on a Stream, you should rethink whether you are using the right tool for your job or whether you are using it the right way.

Generally, you should look for an appropriate terminal operation doing what you want to achieve or for an appropriate Collector. Now, there are Collectors for producing Maps and Lists, but no out of-the-box collector for combining two different collectors, based on a predicate.

Now, this answer contains a collector for combining two collectors. Using this collector, you can achieve the task as

Pair<Map<KeyType, Animal>, List<KeyType>> pair = animalMap.entrySet().stream()
    .collect(conditional(entry -> entry.getValue() != null,
            Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue),
            Collectors.mapping(Map.Entry::getKey, Collectors.toList()) ));
Map<KeyType,Animal> myMap = pair.a;
List<KeyType> myList = pair.b;

But maybe, you can solve this specific task in a simpler way. One of you results matches the input type; it’s the same map just stripped off the entries which map to null. If your original map is mutable and you don’t need it afterwards, you can just collect the list and remove these keys from the original map as they are mutually exclusive:

List<KeyType> myList=animalMap.entrySet().stream()
    .filter(pair -> pair.getValue() == null)
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());

animalMap.keySet().removeAll(myList);

Note that you can remove mappings to null even without having the list of the other keys:

animalMap.values().removeIf(Objects::isNull);

or

animalMap.values().removeAll(Collections.singleton(null));

If you can’t (or don’t want to) modify the original map, there is still a solution without a custom collector. As hinted in Alexis C.’s answer, partitioningBy is going into the right direction, but you may simplify it:

Map<Boolean,Map<KeyType,Animal>> tmp = animalMap.entrySet().stream()
    .collect(Collectors.partitioningBy(pair -> pair.getValue() != null,
                 Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
Map<KeyType,Animal> myMap = tmp.get(true);
List<KeyType> myList = new ArrayList<>(tmp.get(false).keySet());

The bottom line is, don’t forget about ordinary Collection operations, you don’t have to do everything with the new Stream API.

Detecting TCP Client Disconnect

The return value of receive will be -1 if connection is lost else it will be size of buffer.

void ReceiveStream(void *threadid)
{
    while(true)
    {
        while(ch==0)
        {
            char buffer[1024];
            int newData;
            newData = recv(thisSocket, buffer, sizeof(buffer), 0);
            if(newData>=0)
            {
                std::cout << buffer << std::endl;
            }
            else
            {
                std::cout << "Client disconnected" << std::endl;
                if (thisSocket)
                {
                    #ifdef WIN32
                        closesocket(thisSocket);
                        WSACleanup();
                    #endif
                    #ifdef LINUX
                        close(thisSocket);
                    #endif
                }
                break;
            }
        }
        ch = 1;
        StartSocket();
    }
}

Invoking a PHP script from a MySQL trigger

That should be considered a very bad programming practice to call PHP code from a database trigger. If you will explain the task you are trying to solve using such "mad" tricks, we might provide a satisfying solution.

ADDED 19.03.2014:

I should have added some reasoning earlier, but only found time to do this now. Thanks to @cmc for an important remark. So, PHP triggers add the following complexities to your application:

  • Adds a certain degree of security problems to the application (external PHP script calls, permission setup, probably SELinux setup etc) as @Johan says.

  • Adds additional level of complexity to your application (to understand how database works you now need to know both SQL and PHP, not only SQL) and you will have to debug PHP also, not only SQL.

  • Adds additional point of failure to your application (PHP misconfiguration for example), which needs to be diagnosied also ( I think trigger needs to hold some debug code which will log somwewhere all insuccessful PHP interpreter calls and their reasons).

  • Adds additional point of performance analysis. Each PHP call is expensive, since you need to start interpreter, compile script to bytecode, execute it etc. So each query involving this trigger will execute slower. And sometimes it will be difficult to isolate query performance problems since EXPLAIN doesn't tell you anything about query being slower because of trigger routine performance. And I'm not sure how trigger time is dumped into slow query log.

  • Adds some problems to application testing. SQL can be tested pretty easily. But to test SQL + PHP triggers, you will have to apply some skill.

Truncate a SQLite table if it exists?

Unfortunately, we do not have a "TRUNCATE TABLE" command in SQLite, but you can use SQLite's DELETE command to delete the complete data from an existing table, though it is recommended to use the DROP TABLE command to drop the complete table and re-create it once again.

Check if character is number?

Similar to one of the answers above, I used

 var sum = 0; //some value
 let num = parseInt(val); //or just Number.parseInt
 if(!isNaN(num)) {
     sum += num;
 }

This blogpost sheds some more light on this check if a string is numeric in Javascript | Typescript & ES6

How to start an application without waiting in a batch file?

I used start /b for this instead of just start and it ran without a window for each command, so there was no waiting.

Import existing Gradle Git project into Eclipse

Open eclipse and right click in the package explorer ? import Select gradle Browse to the location where you checked out Click “Build Model” Select all the projects and hit finish

Insert default value when parameter is null

chrisofspades,

As far as I know that behavior is not compatible with the way the db engine works, but there is a simple (i don't know if elegant, but performant) solution to achive your two objectives of DO NOT

  1. maintain the default value in multiple places, and
  2. use multiple insert statements.

The solution is to use two fields, one nullable for insert, and other one calculated to selections:

CREATE TABLE t (
    insValue VARCHAR(50) NULL
    , selValue AS ISNULL(insValue, 'something')
)

DECLARE @d VARCHAR(10)
INSERT INTO t (insValue) VALUES (@d) -- null
SELECT selValue FROM t

This method even let You centralize the management of business defaults in a parameter table, placing an ad hoc function to do this, vg changing:

selValue AS ISNULL(insValue, 'something')

for

selValue AS ISNULL(insValue, **getDef(t,1)**)

I hope this helps.

How do I copy folder with files to another folder in Unix/Linux?

You are looking for the cp command. You need to change directories so that you are outside of the directory you are trying to copy.

If the directory you're copying is called dir1 and you want to copy it to your /home/Pictures folder:

cp -r dir1/ ~/Pictures/

Linux is case-sensitive and also needs the / after each directory to know that it isn't a file. ~ is a special character in the terminal that automatically evaluates to the current user's home directory. If you need to know what directory you are in, use the command pwd.

When you don't know how to use a Linux command, there is a manual page that you can refer to by typing:

man [insert command here]

at a terminal prompt.

Also, to auto complete long file paths when typing in the terminal, you can hit Tab after you've started typing the path and you will either be presented with choices, or it will insert the remaining part of the path.

T-SQL How to create tables dynamically in stored procedures?

This is a way to create tables dynamically using T-SQL stored procedures:

declare @cmd nvarchar(1000), @MyTableName nvarchar(100);
set @MyTableName = 'CustomerDetails';
set @cmd = 'CREATE TABLE dbo.' + quotename(@MyTableName, '[') + '(ColumnName1 int not null,ColumnName2 int not null);';

Execute it as:

exec(@cmd);

Can promises have multiple arguments to onFulfilled?

De-structuring Assignment in ES6 would help here.For Ex:

let [arg1, arg2] = new Promise((resolve, reject) => {
    resolve([argument1, argument2]);
});

Is there a C++ decompiler?

You can use IDA Pro by Hex-Rays. You will usually not get good C++ out of a binary unless you compiled in debugging information. Prepare to spend a lot of manual labor reversing the code.

If you didn't strip the binaries there is some hope as IDA Pro can produce C-alike code for you to work with. Usually it is very rough though, at least when I used it a couple of years ago.

Function inside a function.?

(4+3)*(4*2) == 56

Note that PHP doesn't really support "nested functions", as in defined only in the scope of the parent function. All functions are defined globally. See the docs.

Node.js global proxy setting

While not a Nodejs setting, I suggest you use proxychains which I find rather convenient. It is probably available in your package manager.

After setting the proxy in the config file (/etc/proxychains.conf for me), you can run proxychains npm start or proxychains4 npm start (i.e. proxychains [command_to_proxy_transparently]) and all your requests will be proxied automatically.

Config settings for me:

These are the minimal settings you will have to append

## Exclude all localhost connections (dbs and stuff)
localnet 0.0.0.0/0.0.0.0
## Set the proxy type, ip and port here
http    10.4.20.103 8080

(You can get the ip of the proxy by using nslookup [proxyurl])

fatal error: iostream.h no such file or directory

Using standard C++ calling (note that you should use namespace std for cout or add using namespace std;)

#include <iostream>

int main()
{
    std::cout<<"Hello World!\n";
    return 0;
}

Best way to specify whitespace in a String.Split operation

Why don't you just do this:

var ssizes = myStr.Split(" \t".ToCharArray());

It seems there is a method String.ToCharArray() in .NET 4.0!

EDIT: As VMAtm has pointed out, the method already existed in .NET 2.0!

asp.net Button OnClick event not firing

Try to Clean your solution and then try once again.

It will definitely work. Because every thing in code seems to be ok.

Go through this link for cleaning solution>

http://social.msdn.microsoft.com/Forums/en-US/vsdebug/thread/e53aab69-75b9-434a-bde3-74ca0865c165/

How can I prevent java.lang.NumberFormatException: For input string: "N/A"?

Make an exception handler like this,

private int ConvertIntoNumeric(String xVal)
{
 try
  { 
     return Integer.parseInt(xVal);
  }
 catch(Exception ex) 
  {
     return 0; 
  }
}

.
.
.
.

int xTest = ConvertIntoNumeric("N/A");  //Will return 0

Why so red? IntelliJ seems to think every declaration/method cannot be found/resolved

The issue was that the file I was trying to import was so large that IntelliJ wouldn't run any CodeInsights on it.

Setting the idea.max.intellisense.filesize option to a higher value as per the instructions on this answer resolved my issue.

Convert datatable to JSON in C#

public static string ConvertIntoJson(DataTable dt)
{
    var jsonString = new StringBuilder();
    if (dt.Rows.Count > 0)
    {
        jsonString.Append("[");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            jsonString.Append("{");
            for (int j = 0; j < dt.Columns.Count; j++)
                jsonString.Append("\"" + dt.Columns[j].ColumnName + "\":\"" 
                    + dt.Rows[i][j].ToString().Replace('"','\"') + (j < dt.Columns.Count - 1 ? "\"," : "\""));

            jsonString.Append(i < dt.Rows.Count - 1 ? "}," : "}");
        }
        return jsonString.Append("]").ToString();
    }
    else
    {
        return "[]";
    }
}
public static string ConvertIntoJson(DataSet ds)
{
    var jsonString = new StringBuilder();
    jsonString.Append("{");
    for (int i = 0; i < ds.Tables.Count; i++)
    {
        jsonString.Append("\"" + ds.Tables[i].TableName + "\":");
        jsonString.Append(ConvertIntoJson(ds.Tables[i]));
        if (i < ds.Tables.Count - 1)
            jsonString.Append(",");
    }
    jsonString.Append("}");
    return jsonString.ToString();
}

Qt. get part of QString

If you do not need to modify the substring, then you can use QStringRef. The QStringRef class is a read only wrapper around an existing QString that references a substring within the existing string. This gives much better performance than creating a new QString object to contain the sub-string. E.g.

QString myString("This is a string");
QStringRef subString(&myString, 5, 2); // subString contains "is"

If you do need to modify the substring, then left(), mid() and right() will do what you need...

QString myString("This is a string");
QString subString = myString.mid(5,2); // subString contains "is"
subString.append("n't"); // subString contains "isn't"

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

There are a couple of options. You can use the --device flag that use can use to access USB devices without --privileged mode:

docker run -t -i --device=/dev/ttyUSB0 ubuntu bash

Alternatively, assuming your USB device is available with drivers working, etc. on the host in /dev/bus/usb, you can mount this in the container using privileged mode and the volumes option. For example:

docker run -t -i --privileged -v /dev/bus/usb:/dev/bus/usb ubuntu bash

Note that as the name implies, --privileged is insecure and should be handled with care.

C# Dictionary get item by index

Your key is a string and your value is an int. Your code won't work because it cannot look up the random int you pass. Also, please provide full code

Boto3 to download all files from a S3 Bucket

I'm currently achieving the task, by using the following

#!/usr/bin/python
import boto3
s3=boto3.client('s3')
list=s3.list_objects(Bucket='bucket')['Contents']
for s3_key in list:
    s3_object = s3_key['Key']
    if not s3_object.endswith("/"):
        s3.download_file('bucket', s3_object, s3_object)
    else:
        import os
        if not os.path.exists(s3_object):
            os.makedirs(s3_object)

Although, it does the job, I'm not sure its good to do this way. I'm leaving it here to help other users and further answers, with better manner of achieving this

Autoplay an audio with HTML5 embed tag while the player is invisible

You Could use this code, It's Works with me

<div style="visibility:hidden">
    <audio autoplay loop>
        <source src="../audio/audio.mp3">
    </audio> 
</div>

Check if string is upper, lower, or mixed case in Python

There are a number of "is methods" on strings. islower() and isupper() should meet your needs:

>>> 'hello'.islower()
True

>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

Here's an example of how to use those methods to classify a list of strings:

>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']

Random record from MongoDB

If you're using mongoid, the document-to-object wrapper, you can do the following in Ruby. (Assuming your model is User)

User.all.to_a[rand(User.count)]

In my .irbrc, I have

def rando klass
    klass.all.to_a[rand(klass.count)]
end

so in rails console, I can do, for example,

rando User
rando Article

to get documents randomly from any collection.

Return multiple values from a function in swift

Update Swift 4.1

Here we create a struct to implement the Tuple usage and validate the OTP text length. That needs to be of 2 fields for this example.

struct ValidateOTP {
var code: String
var isValid: Bool }

func validateTheOTP() -> ValidateOTP {
    let otpCode = String(format: "%@%@", txtOtpField1.text!, txtOtpField2.text!)
    if otpCode.length < 2 {
        return ValidateOTP(code: otpCode, isValid: false)
    } else {
        return ValidateOTP(code: otpCode, isValid: true)
    }
}

Usage:

let isValidOTP = validateTheOTP()
    if isValidOTP.isValid { print(" valid OTP") } else {   self.alert(msg: "Please fill the valid OTP", buttons: ["Ok"], handler: nil)
    }

Hope it helps!

Thanks

What is the difference between single and double quotes in SQL?

Single quotes delimit a string constant or a date/time constant.

Double quotes delimit identifiers for e.g. table names or column names. This is generally only necessary when your identifier doesn't fit the rules for simple identifiers.

See also:

You can make MySQL use double-quotes per the ANSI standard:

SET GLOBAL SQL_MODE=ANSI_QUOTES

You can make Microsoft SQL Server use double-quotes per the ANSI standard:

SET QUOTED_IDENTIFIER ON

Spark SQL: apply aggregate functions to a list of columns

There are multiple ways of applying aggregate functions to multiple columns.

GroupedData class provides a number of methods for the most common functions, including count, max, min, mean and sum, which can be used directly as follows:

  • Python:

    df = sqlContext.createDataFrame(
        [(1.0, 0.3, 1.0), (1.0, 0.5, 0.0), (-1.0, 0.6, 0.5), (-1.0, 5.6, 0.2)],
        ("col1", "col2", "col3"))
    
    df.groupBy("col1").sum()
    
    ## +----+---------+-----------------+---------+
    ## |col1|sum(col1)|        sum(col2)|sum(col3)|
    ## +----+---------+-----------------+---------+
    ## | 1.0|      2.0|              0.8|      1.0|
    ## |-1.0|     -2.0|6.199999999999999|      0.7|
    ## +----+---------+-----------------+---------+
    
  • Scala

    val df = sc.parallelize(Seq(
      (1.0, 0.3, 1.0), (1.0, 0.5, 0.0),
      (-1.0, 0.6, 0.5), (-1.0, 5.6, 0.2))
    ).toDF("col1", "col2", "col3")
    
    df.groupBy($"col1").min().show
    
    // +----+---------+---------+---------+
    // |col1|min(col1)|min(col2)|min(col3)|
    // +----+---------+---------+---------+
    // | 1.0|      1.0|      0.3|      0.0|
    // |-1.0|     -1.0|      0.6|      0.2|
    // +----+---------+---------+---------+
    

Optionally you can pass a list of columns which should be aggregated

df.groupBy("col1").sum("col2", "col3")

You can also pass dictionary / map with columns a the keys and functions as the values:

  • Python

    exprs = {x: "sum" for x in df.columns}
    df.groupBy("col1").agg(exprs).show()
    
    ## +----+---------+
    ## |col1|avg(col3)|
    ## +----+---------+
    ## | 1.0|      0.5|
    ## |-1.0|     0.35|
    ## +----+---------+
    
  • Scala

    val exprs = df.columns.map((_ -> "mean")).toMap
    df.groupBy($"col1").agg(exprs).show()
    
    // +----+---------+------------------+---------+
    // |col1|avg(col1)|         avg(col2)|avg(col3)|
    // +----+---------+------------------+---------+
    // | 1.0|      1.0|               0.4|      0.5|
    // |-1.0|     -1.0|3.0999999999999996|     0.35|
    // +----+---------+------------------+---------+
    

Finally you can use varargs:

  • Python

    from pyspark.sql.functions import min
    
    exprs = [min(x) for x in df.columns]
    df.groupBy("col1").agg(*exprs).show()
    
  • Scala

    import org.apache.spark.sql.functions.sum
    
    val exprs = df.columns.map(sum(_))
    df.groupBy($"col1").agg(exprs.head, exprs.tail: _*)
    

There are some other way to achieve a similar effect but these should more than enough most of the time.

See also:

How can I import a database with MySQL from terminal?

How to load from command line

Explanation:

  1. First create a database or use an existing database. In my case, I am using an existing database

  2. Load the database by giving <name of database> = ClassicModels in my case and using the operator < give the path to the database = sakila-data.sql

  3. By running show tables, I get the list of tables as you can see.

Note : In my case I got an error 1062, because I am trying to load the same thing again.

What are Transient and Volatile Modifiers?

Volatile means other threads can edit that particular variable. So the compiler allows access to them.

http://www.javamex.com/tutorials/synchronization_volatile.shtml

Transient means that when you serialize an object, it will return its default value on de-serialization

http://www.geekinterview.com/question_details/2

How Connect to remote host from Aptana Studio 3

Window -> Show View -> Other -> Studio/Remote

(Drag this tabbed window wherever)

Click the add FTP button (see below); #profit

Add New FTP Site...

Change column type in pandas

You have four main options for converting types in pandas:

  1. to_numeric() - provides functionality to safely convert non-numeric types (e.g. strings) to a suitable numeric type. (See also to_datetime() and to_timedelta().)

  2. astype() - convert (almost) any type to (almost) any other type (even if it's not necessarily sensible to do so). Also allows you to convert to categorial types (very useful).

  3. infer_objects() - a utility method to convert object columns holding Python objects to a pandas type if possible.

  4. convert_dtypes() - convert DataFrame columns to the "best possible" dtype that supports pd.NA (pandas' object to indicate a missing value).

Read on for more detailed explanations and usage of each of these methods.


1. to_numeric()

The best way to convert one or more columns of a DataFrame to numeric values is to use pandas.to_numeric().

This function will try to change non-numeric objects (such as strings) into integers or floating point numbers as appropriate.

Basic usage

The input to to_numeric() is a Series or a single column of a DataFrame.

>>> s = pd.Series(["8", 6, "7.5", 3, "0.9"]) # mixed string and numeric values
>>> s
0      8
1      6
2    7.5
3      3
4    0.9
dtype: object

>>> pd.to_numeric(s) # convert everything to float values
0    8.0
1    6.0
2    7.5
3    3.0
4    0.9
dtype: float64

As you can see, a new Series is returned. Remember to assign this output to a variable or column name to continue using it:

# convert Series
my_series = pd.to_numeric(my_series)

# convert column "a" of a DataFrame
df["a"] = pd.to_numeric(df["a"])

You can also use it to convert multiple columns of a DataFrame via the apply() method:

# convert all columns of DataFrame
df = df.apply(pd.to_numeric) # convert all columns of DataFrame

# convert just columns "a" and "b"
df[["a", "b"]] = df[["a", "b"]].apply(pd.to_numeric)

As long as your values can all be converted, that's probably all you need.

Error handling

But what if some values can't be converted to a numeric type?

to_numeric() also takes an errors keyword argument that allows you to force non-numeric values to be NaN, or simply ignore columns containing these values.

Here's an example using a Series of strings s which has the object dtype:

>>> s = pd.Series(['1', '2', '4.7', 'pandas', '10'])
>>> s
0         1
1         2
2       4.7
3    pandas
4        10
dtype: object

The default behaviour is to raise if it can't convert a value. In this case, it can't cope with the string 'pandas':

>>> pd.to_numeric(s) # or pd.to_numeric(s, errors='raise')
ValueError: Unable to parse string

Rather than fail, we might want 'pandas' to be considered a missing/bad numeric value. We can coerce invalid values to NaN as follows using the errors keyword argument:

>>> pd.to_numeric(s, errors='coerce')
0     1.0
1     2.0
2     4.7
3     NaN
4    10.0
dtype: float64

The third option for errors is just to ignore the operation if an invalid value is encountered:

>>> pd.to_numeric(s, errors='ignore')
# the original Series is returned untouched

This last option is particularly useful when you want to convert your entire DataFrame, but don't not know which of our columns can be converted reliably to a numeric type. In that case just write:

df.apply(pd.to_numeric, errors='ignore')

The function will be applied to each column of the DataFrame. Columns that can be converted to a numeric type will be converted, while columns that cannot (e.g. they contain non-digit strings or dates) will be left alone.

Downcasting

By default, conversion with to_numeric() will give you either a int64 or float64 dtype (or whatever integer width is native to your platform).

That's usually what you want, but what if you wanted to save some memory and use a more compact dtype, like float32, or int8?

to_numeric() gives you the option to downcast to either 'integer', 'signed', 'unsigned', 'float'. Here's an example for a simple series s of integer type:

>>> s = pd.Series([1, 2, -7])
>>> s
0    1
1    2
2   -7
dtype: int64

Downcasting to 'integer' uses the smallest possible integer that can hold the values:

>>> pd.to_numeric(s, downcast='integer')
0    1
1    2
2   -7
dtype: int8

Downcasting to 'float' similarly picks a smaller than normal floating type:

>>> pd.to_numeric(s, downcast='float')
0    1.0
1    2.0
2   -7.0
dtype: float32

2. astype()

The astype() method enables you to be explicit about the dtype you want your DataFrame or Series to have. It's very versatile in that you can try and go from one type to the any other.

Basic usage

Just pick a type: you can use a NumPy dtype (e.g. np.int16), some Python types (e.g. bool), or pandas-specific types (like the categorical dtype).

Call the method on the object you want to convert and astype() will try and convert it for you:

# convert all DataFrame columns to the int64 dtype
df = df.astype(int)

# convert column "a" to int64 dtype and "b" to complex type
df = df.astype({"a": int, "b": complex})

# convert Series to float16 type
s = s.astype(np.float16)

# convert Series to Python strings
s = s.astype(str)

# convert Series to categorical type - see docs for more details
s = s.astype('category')

Notice I said "try" - if astype() does not know how to convert a value in the Series or DataFrame, it will raise an error. For example if you have a NaN or inf value you'll get an error trying to convert it to an integer.

As of pandas 0.20.0, this error can be suppressed by passing errors='ignore'. Your original object will be return untouched.

Be careful

astype() is powerful, but it will sometimes convert values "incorrectly". For example:

>>> s = pd.Series([1, 2, -7])
>>> s
0    1
1    2
2   -7
dtype: int64

These are small integers, so how about converting to an unsigned 8-bit type to save memory?

>>> s.astype(np.uint8)
0      1
1      2
2    249
dtype: uint8

The conversion worked, but the -7 was wrapped round to become 249 (i.e. 28 - 7)!

Trying to downcast using pd.to_numeric(s, downcast='unsigned') instead could help prevent this error.


3. infer_objects()

Version 0.21.0 of pandas introduced the method infer_objects() for converting columns of a DataFrame that have an object datatype to a more specific type (soft conversions).

For example, here's a DataFrame with two columns of object type. One holds actual integers and the other holds strings representing integers:

>>> df = pd.DataFrame({'a': [7, 1, 5], 'b': ['3','2','1']}, dtype='object')
>>> df.dtypes
a    object
b    object
dtype: object

Using infer_objects(), you can change the type of column 'a' to int64:

>>> df = df.infer_objects()
>>> df.dtypes
a     int64
b    object
dtype: object

Column 'b' has been left alone since its values were strings, not integers. If you wanted to try and force the conversion of both columns to an integer type, you could use df.astype(int) instead.


4. convert_dtypes()

Version 1.0 and above includes a method convert_dtypes() to convert Series and DataFrame columns to the best possible dtype that supports the pd.NA missing value.

Here "best possible" means the type most suited to hold the values. For example, this a pandas integer type if all of the values are integers (or missing values): an object column of Python integer objects is converted to Int64, a column of NumPy int32 values will become the pandas dtype Int32.

With our object DataFrame df, we get the following result:

>>> df.convert_dtypes().dtypes                                             
a     Int64
b    string
dtype: object

Since column 'a' held integer values, it was converted to the Int64 type (which is capable of holding missing values, unlike int64).

Column 'b' contained string objects, so was changed to pandas' string dtype.

By default, this method will infer the type from object values in each column. We can change this by passing infer_objects=False:

>>> df.convert_dtypes(infer_objects=False).dtypes                          
a    object
b    string
dtype: object

Now column 'a' remained an object column: pandas knows it can be described as an 'integer' column (internally it ran infer_dtype) but didn't infer exactly what dtype of integer it should have so did not convert it. Column 'b' was again converted to 'string' dtype as it was recognised as holding 'string' values.

How to parse JSON array in jQuery?

I am trying to parse JSON data returned from an ajax call, and the following is working for me:

Sample PHP code

$portfolio_array= Array('desc'=>'This is test description1','item1'=>'1.jpg','item2'=>'2.jpg');

echo json_encode($portfolio_array);

And in the .js, i am parsing like this:

var req=$.post("json.php", { id: "" + id + ""},
function(data) {
    data=$.parseJSON(data);
    alert(data.desc);
    $.each(data, function(i,item){
    alert(item);
    });
})
.success(function(){})
.error(function(){alert('There was problem loading portfolio details.');})
.complete(function(){});

If you have multidimensional array like below

$portfolio_array= Array('desc'=>'This is test description 1','items'=> array('item1'=>'1.jpg','item2'=>'2.jpg'));
echo json_encode($portfolio_array);

Then the code below should work:

var req=$.post("json.php", { id: "" + id + 
    function(data) {
    data=$.parseJSON(data);
    alert(data.desc);
    $.each(data.items, function(i,item){
    alert(item);
    });
})
.success(function(){})
.error(function(){alert('There was problem loading portfolio details.');})
.complete(function(){});

Please note the sub array key here is items, and suppose if you have xyz then in place of data.items use data.xyz

what is the use of xsi:schemaLocation?

An xmlns is a unique identifier within the document - it doesn't have to be a URI to the schema:

XML namespaces provide a simple method for qualifying element and attribute names used in Extensible Markup Language documents by associating them with namespaces identified by URI references.

xsi:schemaLocation is supposed to give a hint as to the actual schema location:

can be used in a document to provide hints as to the physical location of schema documents which may be used for assessment.

Why do you need ./ (dot-slash) before executable or script name to run it in bash?

Because on Unix, usually, the current directory is not in $PATH.

When you type a command the shell looks up a list of directories, as specified by the PATH variable. The current directory is not in that list.

The reason for not having the current directory on that list is security.

Let's say you're root and go into another user's directory and type sl instead of ls. If the current directory is in PATH, the shell will try to execute the sl program in that directory (since there is no other sl program). That sl program might be malicious.

It works with ./ because POSIX specifies that a command name that contain a / will be used as a filename directly, suppressing a search in $PATH. You could have used full path for the exact same effect, but ./ is shorter and easier to write.

EDIT

That sl part was just an example. The directories in PATH are searched sequentially and when a match is made that program is executed. So, depending on how PATH looks, typing a normal command may or may not be enough to run the program in the current directory.

date format yyyy-MM-ddTHH:mm:ssZ

Using UTC

ISO 8601 (MSDN datetime formats)

Console.WriteLine(DateTime.UtcNow.ToString("s") + "Z");

2009-11-13T10:39:35Z

The Z is there because

If the time is in UTC, add a 'Z' directly after the time without a space. 'Z' is the zone designator for the zero UTC offset. "09:30 UTC" is therefore represented as "09:30Z" or "0930Z". "14:45:15 UTC" would be "14:45:15Z" or "144515Z".

If you want to include an offset

int hours = TimeZoneInfo.Local.BaseUtcOffset.Hours;
string offset = string.Format("{0}{1}",((hours >0)? "+" :""),hours.ToString("00"));
string isoformat = DateTime.Now.ToString("s") + offset;
Console.WriteLine(isoformat);

Two things to note: + or - is needed after the time but obviously + doesn't show on positive numbers. According to wikipedia the offset can be in +hh format or +hh:mm. I've kept to just hours.

As far as I know, RFC1123 (HTTP date, the "u" formatter) isn't meant to give time zone offsets. All times are intended to be GMT/UTC.

Get list from pandas dataframe column or row?

As this question attained a lot of attention and there are several ways to fulfill your task, let me present several options.

Those are all one-liners by the way ;)

Starting with:

df
  cluster load_date budget actual fixed_price
0       A  1/1/2014   1000   4000           Y
1       A  2/1/2014  12000  10000           Y
2       A  3/1/2014  36000   2000           Y
3       B  4/1/2014  15000  10000           N
4       B  4/1/2014  12000  11500           N
5       B  4/1/2014  90000  11000           N
6       C  7/1/2014  22000  18000           N
7       C  8/1/2014  30000  28960           N
8       C  9/1/2014  53000  51200           N

Overview of potential operations:

ser_aggCol (collapse each column to a list)
cluster          [A, A, A, B, B, B, C, C, C]
load_date      [1/1/2014, 2/1/2014, 3/1/2...
budget         [1000, 12000, 36000, 15000...
actual         [4000, 10000, 2000, 10000,...
fixed_price      [Y, Y, Y, N, N, N, N, N, N]
dtype: object


ser_aggRows (collapse each row to a list)
0     [A, 1/1/2014, 1000, 4000, Y]
1    [A, 2/1/2014, 12000, 10000...
2    [A, 3/1/2014, 36000, 2000, Y]
3    [B, 4/1/2014, 15000, 10000...
4    [B, 4/1/2014, 12000, 11500...
5    [B, 4/1/2014, 90000, 11000...
6    [C, 7/1/2014, 22000, 18000...
7    [C, 8/1/2014, 30000, 28960...
8    [C, 9/1/2014, 53000, 51200...
dtype: object


df_gr (here you get lists for each cluster)
                             load_date                 budget                 actual fixed_price
cluster                                                                                         
A        [1/1/2014, 2/1/2014, 3/1/2...   [1000, 12000, 36000]    [4000, 10000, 2000]   [Y, Y, Y]
B        [4/1/2014, 4/1/2014, 4/1/2...  [15000, 12000, 90000]  [10000, 11500, 11000]   [N, N, N]
C        [7/1/2014, 8/1/2014, 9/1/2...  [22000, 30000, 53000]  [18000, 28960, 51200]   [N, N, N]


a list of separate dataframes for each cluster

df for cluster A
  cluster load_date budget actual fixed_price
0       A  1/1/2014   1000   4000           Y
1       A  2/1/2014  12000  10000           Y
2       A  3/1/2014  36000   2000           Y

df for cluster B
  cluster load_date budget actual fixed_price
3       B  4/1/2014  15000  10000           N
4       B  4/1/2014  12000  11500           N
5       B  4/1/2014  90000  11000           N

df for cluster C
  cluster load_date budget actual fixed_price
6       C  7/1/2014  22000  18000           N
7       C  8/1/2014  30000  28960           N
8       C  9/1/2014  53000  51200           N

just the values of column load_date
0    1/1/2014
1    2/1/2014
2    3/1/2014
3    4/1/2014
4    4/1/2014
5    4/1/2014
6    7/1/2014
7    8/1/2014
8    9/1/2014
Name: load_date, dtype: object


just the values of column number 2
0     1000
1    12000
2    36000
3    15000
4    12000
5    90000
6    22000
7    30000
8    53000
Name: budget, dtype: object


just the values of row number 7
cluster               C
load_date      8/1/2014
budget            30000
actual            28960
fixed_price           N
Name: 7, dtype: object


============================== JUST FOR COMPLETENESS ==============================


you can convert a series to a list
['C', '8/1/2014', '30000', '28960', 'N']
<class 'list'>


you can convert a dataframe to a nested list
[['A', '1/1/2014', '1000', '4000', 'Y'], ['A', '2/1/2014', '12000', '10000', 'Y'], ['A', '3/1/2014', '36000', '2000', 'Y'], ['B', '4/1/2014', '15000', '10000', 'N'], ['B', '4/1/2014', '12000', '11500', 'N'], ['B', '4/1/2014', '90000', '11000', 'N'], ['C', '7/1/2014', '22000', '18000', 'N'], ['C', '8/1/2014', '30000', '28960', 'N'], ['C', '9/1/2014', '53000', '51200', 'N']]
<class 'list'>

the content of a dataframe can be accessed as a numpy.ndarray
[['A' '1/1/2014' '1000' '4000' 'Y']
 ['A' '2/1/2014' '12000' '10000' 'Y']
 ['A' '3/1/2014' '36000' '2000' 'Y']
 ['B' '4/1/2014' '15000' '10000' 'N']
 ['B' '4/1/2014' '12000' '11500' 'N']
 ['B' '4/1/2014' '90000' '11000' 'N']
 ['C' '7/1/2014' '22000' '18000' 'N']
 ['C' '8/1/2014' '30000' '28960' 'N']
 ['C' '9/1/2014' '53000' '51200' 'N']]
<class 'numpy.ndarray'>

code:

# prefix ser refers to pd.Series object
# prefix df refers to pd.DataFrame object
# prefix lst refers to list object

import pandas as pd
import numpy as np

df=pd.DataFrame([
        ['A',   '1/1/2014',    '1000',    '4000',    'Y'],
        ['A',   '2/1/2014',    '12000',   '10000',   'Y'],
        ['A',   '3/1/2014',    '36000',   '2000',    'Y'],
        ['B',   '4/1/2014',    '15000',   '10000',   'N'],
        ['B',   '4/1/2014',    '12000',   '11500',   'N'],
        ['B',   '4/1/2014',    '90000',   '11000',   'N'],
        ['C',   '7/1/2014',    '22000',   '18000',   'N'],
        ['C',   '8/1/2014',    '30000',   '28960',   'N'],
        ['C',   '9/1/2014',    '53000',   '51200',   'N']
        ], columns=['cluster', 'load_date',   'budget',  'actual',  'fixed_price'])
print('df',df, sep='\n', end='\n\n')

ser_aggCol=df.aggregate(lambda x: [x.tolist()], axis=0).map(lambda x:x[0])
print('ser_aggCol (collapse each column to a list)',ser_aggCol, sep='\n', end='\n\n\n')

ser_aggRows=pd.Series(df.values.tolist()) 
print('ser_aggRows (collapse each row to a list)',ser_aggRows, sep='\n', end='\n\n\n')

df_gr=df.groupby('cluster').agg(lambda x: list(x))
print('df_gr (here you get lists for each cluster)',df_gr, sep='\n', end='\n\n\n')

lst_dfFiltGr=[ df.loc[df['cluster']==val,:] for val in df['cluster'].unique() ]
print('a list of separate dataframes for each cluster', sep='\n', end='\n\n')
for dfTmp in lst_dfFiltGr:
    print('df for cluster '+str(dfTmp.loc[dfTmp.index[0],'cluster']),dfTmp, sep='\n', end='\n\n')

ser_singleColLD=df.loc[:,'load_date']
print('just the values of column load_date',ser_singleColLD, sep='\n', end='\n\n\n')

ser_singleCol2=df.iloc[:,2]
print('just the values of column number 2',ser_singleCol2, sep='\n', end='\n\n\n')

ser_singleRow7=df.iloc[7,:]
print('just the values of row number 7',ser_singleRow7, sep='\n', end='\n\n\n')

print('='*30+' JUST FOR COMPLETENESS '+'='*30, end='\n\n\n')

lst_fromSer=ser_singleRow7.tolist()
print('you can convert a series to a list',lst_fromSer, type(lst_fromSer), sep='\n', end='\n\n\n')

lst_fromDf=df.values.tolist()
print('you can convert a dataframe to a nested list',lst_fromDf, type(lst_fromDf), sep='\n', end='\n\n')

arr_fromDf=df.values
print('the content of a dataframe can be accessed as a numpy.ndarray',arr_fromDf, type(arr_fromDf), sep='\n', end='\n\n')

as pointed out by cs95 other methods should be preferred over pandas .values attribute from pandas version 0.24 on see here. I use it here, because most people will (by 2019) still have an older version, which does not support the new recommendations. You can check your version with print(pd.__version__)

trying to align html button at the center of the my page

There are multiple ways to fix the same. PFB two of them -

1st Way using position: fixed - position: fixed; positions relative to the viewport, which means it always stays in the same place even if the page is scrolled. Adding the left and top value to 50% will place it into the middle of the screen.

 button {
   position: fixed;
   left: 50%;
   top:50%;
 }

2nd Way using margin: auto -margin: 0 auto; for horizontal centering, but margin: auto; has refused to work for vertical centering… until now! But actually absolute centering only requires a declared height and these styles:

button {
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  height: 40px;
}

HTML: Is it possible to have a FORM tag in each TABLE ROW in a XHTML valid way?

In fact I have the problem with a form on each row of a table, with javascript (actually jquery) :

like Lothre1 said, "some browsers in the process of rendering will close form tag right after the declaration leaving inputs outside of the element"

which makes my input fields OUTSIDE the form, therefore I can't access the children of my form through the DOM with JAVASCRIPT..

typically, the following JQUERY code won't work :

$('#id_form :input').each(function(){/*action*/});
// this is supposed to select all inputS 
// within the form that has an id ='id_form'

BUT the above exemple doesn't work with the rendered HTML :

<table>
    <form id="id_form"></form>
    <tr id="tr_id">
    <td><input type="text"/></td>
    <td><input type="submit"/></td>
    </tr>
    </table>

I'm still looking for a clean solution (though using the TR 'id' parameter to walk the DOM would fix this specific problem)

dirty solution would be (for jquery):

$('#tr_id :input').each(function(){/*action*/});
// this will select all the inputS
// fields within the TR with the id='tr_id'

the above exemple will work, but it's not really "clean", because it refers to the TR instead of the FORM, AND it requires AJAX ...

EDIT : complete process with jquery/ajax would be :

//init data string
// the dummy init value (1=1)is just here 
// to avoid dealing with trailing &
// and should not be implemented
// (though it works)
var data_str = '1=1'; 
// for each input in the TR
$('#tr_id :input').each(function(){

 //retrieve field name and value from the DOM
 var field = $(this).attr('name');
 var value = $(this).val();

 //iterate the string to pass the datas
 // so in the end it will render s/g like
 // "1=1&field1_name=value1&field2_name=value2"...
 data_str += '&' + field + '=' + value; 


});

//Sendind fields datawith ajax 
// to be treated 
$.ajax({
 type:"POST",
 url: "target_for_the_form_treatment",
 data:data_string,
 success:function(msg){
    /*actions on success of the request*/
 });
});

this way, the "target_for_the_form_treatment" should receive POST data as if a form was sent to him (appart from the post[1] = 1, but to implement this solution i would recommand dealing with the trailing '&' of the data_str instead).

still I don't like this solution, but I'm forced to use TABLE structure because of the dataTables jquery plugin...

Insert auto increment primary key to existing table

How to write PHP to ALTER the already existing field (name, in this example) to make it a primary key? W/o, of course, adding any additional 'id' fields to the table..

This a table currently created - Number of Records found: 4 name VARCHAR(20) YES breed VARCHAR(30) YES color VARCHAR(20) YES weight SMALLINT(7) YES

This an end result sought (TABLE DESCRIPTION) -

Number of records found: 4 name VARCHAR(20) NO PRI breed VARCHAR(30) YES color VARCHAR(20) YES weight SMALLINT(7) YES

Instead of getting this -

Number of Records found: 5 id int(11) NO PRI name VARCHAR(20) YES breed VARCHAR(30) YES color VARCHAR(20) YES weight SMALLINT(7) YES

after trying..

$query = "ALTER TABLE racehorses ADD id INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (id)";

how to get this? -

Number of records found: 4 name VARCHAR(20) NO PRI breed VARCHAR(30) YES color VARCHAR(20) YES weight SMALLINT(7) YES

i.e. INSERT/ADD.. etc. the primary key INTO the first field record (w/o adding an additional 'id' field, as stated earlier.

Use jQuery to scroll to the bottom of a div with lots of text

jQuery simple solution, one line, no external lib required :

$("#myDivID").animate({ scrollTop: $('#myDivID')[0].scrollHeight }, 1000);

Change 1000 to another value (this is the duration of the animation).

How to Determine the Screen Height and Width in Flutter

You can use:

  • double width = MediaQuery.of(context).size.width;
  • double height = MediaQuery.of(context).size.height;

To get height just of SafeArea (for iOS 11 and above):

  • var padding = MediaQuery.of(context).padding;
  • double newheight = height - padding.top - padding.bottom;

Font size relative to the user's screen resolution?

<script>
function getFontsByScreenWidth(actuallFontSize, maxScreenWidth){
     return (actualFontSize / maxScreenWidth) * window.innerWidth;
}

// Example:
fontSize = 18;
maxScreenWidth = 1080;
fontSize = getFontsByScreenWidth(fontSize, maxScreenWidth)

</script>

I hope this will help. I am using this formula for my Phase game.

Early exit from function?

I dislike answering things that aren't a real solution...

...but when I encountered this same problem, I made below workaround:

function doThis() {
  var err=0
  if (cond1) { alert('ret1'); err=1; }
  if (cond2) { alert('ret2'); err=1; }
  if (cond3) { alert('ret3'); err=1; }
  if (err < 1) {
    // do the rest (or have it skipped)
  }
}

Hope it can be useful for anyone.

How to get the full path of running process?

You can use pInvoke and a native call such as the following. This doesn't seem to have the 32 / 64 bit limitation (at least in my testing)

Here is the code

using System.Runtime.InteropServices;

    [DllImport("Kernel32.dll")]
    static extern uint QueryFullProcessImageName(IntPtr hProcess, uint flags, StringBuilder text, out uint size);

    //Get the path to a process
    //proc = the process desired
    private string GetPathToApp (Process proc)
    {
        string pathToExe = string.Empty;

        if (null != proc)
        {
            uint nChars = 256;
            StringBuilder Buff = new StringBuilder((int)nChars);

            uint success = QueryFullProcessImageName(proc.Handle, 0, Buff, out nChars);

            if (0 != success)
            {
                pathToExe = Buff.ToString();
            }
            else
            {
                int error = Marshal.GetLastWin32Error();
                pathToExe = ("Error = " + error + " when calling GetProcessImageFileName");
            }
        }

        return pathToExe;
    }