Programs & Examples On #Xmlblaster

Converting String to Int using try/except in Python

You can do :

try : 
   string_integer = int(string)
except ValueError  :
   print("This string doesn't contain an integer")

What's HTML character code 8203?

If you're seeing these in a source be aware that it may be someone attempting to fingerprint text documents to reveal who is leaking information. It also may be an attempt to bypass a spam filter by making the same looking information different on a byte-by-byte level.

See my article on mitigating fingerprinting if you're interested in learning more.

Storing a Key Value Array into a compact JSON string

For use key/value pair in json use an object and don't use array

Find name/value in array is hard but in object is easy

Ex:

_x000D_
_x000D_
var exObj = {_x000D_
  "mainData": {_x000D_
    "slide0001.html": "Looking Ahead",_x000D_
    "slide0008.html": "Forecast",_x000D_
    "slide0021.html": "Summary",_x000D_
    // another THOUSANDS KEY VALUE PAIRS_x000D_
    // ..._x000D_
  },_x000D_
  "otherdata" : { "one": "1", "two": "2", "three": "3" }_x000D_
};_x000D_
var mainData = exObj.mainData;_x000D_
// for use:_x000D_
Object.keys(mainData).forEach(function(n,i){_x000D_
  var v = mainData[n];_x000D_
  console.log('name' + i + ': ' + n + ', value' + i + ': ' + v);_x000D_
});_x000D_
_x000D_
// and string length is minimum_x000D_
console.log(JSON.stringify(exObj));_x000D_
console.log(JSON.stringify(exObj).length);
_x000D_
_x000D_
_x000D_

PHP function to make slug (URL string)

Instead of a lengthy replace, try this one:

public static function slugify($text)
{
  // replace non letter or digits by -
  $text = preg_replace('~[^\pL\d]+~u', '-', $text);

  // transliterate
  $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);

  // remove unwanted characters
  $text = preg_replace('~[^-\w]+~', '', $text);

  // trim
  $text = trim($text, '-');

  // remove duplicate -
  $text = preg_replace('~-+~', '-', $text);

  // lowercase
  $text = strtolower($text);

  if (empty($text)) {
    return 'n-a';
  }

  return $text;
}

This was based off the one in Symfony's Jobeet tutorial.

Getting "unixtime" in Java

Java 8 added a new API for working with dates and times. With Java 8 you can use

import java.time.Instant
...
long unixTimestamp = Instant.now().getEpochSecond();

Instant.now() returns an Instant that represents the current system time. With getEpochSecond() you get the epoch seconds (unix time) from the Instant.

Get the latest record with filter in Django

obj= Model.objects.filter(testfield=12).order_by('-id')[:1] is the right solution

Counting the Number of keywords in a dictionary in python

Some modifications were made on posted answer UnderWaterKremlin to make it python3 proof. A surprising result below as answer.

System specs:

  • python =3.7.4,
  • conda = 4.8.0
  • 3.6Ghz, 8 core, 16gb.
import timeit

d = {x: x**2 for x in range(1000)}
#print (d)
print (len(d))
# 1000

print (len(d.keys()))
# 1000

print (timeit.timeit('len({x: x**2 for x in range(1000)})', number=100000))        # 1

print (timeit.timeit('len({x: x**2 for x in range(1000)}.keys())', number=100000)) # 2

Result:

1) = 37.0100378

2) = 37.002148899999995

So it seems that len(d.keys()) is currently faster than just using len().

Attempt to set a non-property-list object as an NSUserDefaults

Swift 5: The Codable protocol can be used instead of NSKeyedArchiever.

struct User: Codable {
    let id: String
    let mail: String
    let fullName: String
}

The Pref struct is custom wrapper around the UserDefaults standard object.

struct Pref {
    static let keyUser = "Pref.User"
    static var user: User? {
        get {
            if let data = UserDefaults.standard.object(forKey: keyUser) as? Data {
                do {
                    return try JSONDecoder().decode(User.self, from: data)
                } catch {
                    print("Error while decoding user data")
                }
            }
            return nil
        }
        set {
            if let newValue = newValue {
                do {
                    let data = try JSONEncoder().encode(newValue)
                    UserDefaults.standard.set(data, forKey: keyUser)
                } catch {
                    print("Error while encoding user data")
                }
            } else {
                UserDefaults.standard.removeObject(forKey: keyUser)
            }
        }
    }
}

So you can use it this way:

Pref.user?.name = "John"

if let user = Pref.user {...

How to add a custom right-click menu to a webpage?

You could try simply blocking the context menu by adding the following to your body tag:

<body oncontextmenu="return false;">

This will block all access to the context menu (not just from the right mouse button but from the keyboard as well).

P.S. you can add this to any tag you want to disable the context menu on

for example:

<div class="mydiv" oncontextmenu="return false;">

Will disable the context menu in that particular div only

UIView Infinite 360 degree rotation animation?

If all you want to do is rotate the image endlessly, this works quite well, and is very simple:

NSTimeInterval duration = 10.0f;
CGFloat angle = M_PI / 2.0f;
CGAffineTransform rotateTransform = CGAffineTransformRotate(imageView.transform, angle);

[UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionRepeat| UIViewAnimationOptionCurveLinear animations:^{
    imageView.transform = rotateTransform;
} completion:nil];

In my experience, this works flawlessly, but be sure your image is capable of being rotated around its center without any offsets, or the image animation will "jump" once it makes it around to PI.

To change the direction of the spin, change the sign of angle (angle *= -1).

Update Comments by @AlexPretzlav made me revisit this, and I realized that when I wrote this the image I was rotating was mirrored along both the vertical and horizontal axis, meaning the image was indeed only rotating 90 degrees and then resetting, though it looked like it was continuing to rotate all the way around.

So, if your image is like mine was, this will work great, however, if the image is not symmetrical, you'll notice the "snap" back to the original orientation after 90 degrees.

To rotate a non-symmetrical image, you're better off with the accepted answer.

One of these less elegant solutions, seen below, will truly rotate the image, but there may be a noticeable stutter when the animation is restarted:

- (void)spin
{
    NSTimeInterval duration = 0.5f;
    CGFloat angle = M_PI_2;
    CGAffineTransform rotateTransform = CGAffineTransformRotate(self.imageView.transform, angle);

    [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        self.imageView.transform = rotateTransform;
    } completion:^(BOOL finished) {
        [self spin];
    }];
}

You could also do this just with blocks, as @richard-j-ross-iii suggests, but you will get a retain loop warning since the block is capturing itself:

__block void(^spin)() = ^{
    NSTimeInterval duration = 0.5f;
    CGFloat angle = M_PI_2;
    CGAffineTransform rotateTransform = CGAffineTransformRotate(self.imageView.transform, angle);

    [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        self.imageView.transform = rotateTransform;
    } completion:^(BOOL finished) {
        spin();
    }];
};
spin();

How to add a "open git-bash here..." context menu to the windows explorer?

When you install git-scm found in "https://git-scm.com/downloads" uncheck the "Only show new options" located at the very bottom of the installation window

Make sure you check

  • Windows Explorer integration
    • Git Bash Here
    • Git GUI Here

Click Next and you're good to go!

Refused to load the script because it violates the following Content Security Policy directive

Try replacing your meta tag with this below:

<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' http://* 'unsafe-inline'; script-src 'self' http://* 'unsafe-inline' 'unsafe-eval'" />

Or in addition to what you have, you should add http://* to both style-src and script-src as seen above added after 'self'.

If your server is including the Content-Security-Policy header, the header will override the meta.

Is there StartsWith or Contains in t sql with variables?

StartsWith

a) left(@edition, 15) = 'Express Edition'
b) charindex('Express Edition', @edition) = 1

Contains

charindex('Express Edition', @edition) >= 1

Examples

left function

set @isExpress = case when left(@edition, 15) = 'Express Edition' then 1 else 0 end

iif function (starting with SQL Server 2012)

set @isExpress = iif(left(@edition, 15) = 'Express Edition', 1, 0);

charindex function

set @isExpress = iif(charindex('Express Edition', @edition) = 1, 1, 0);

Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings

If it is IIS 8.0 check if HTTP Activation is enabled. Server manager -> IIS -> Manage (see right top) -> Add Roles and Features -> ... -> get to WCF configuration and then select HTTP Activation.

CSS: how to get scrollbars for div inside container of fixed height

Code from the above answer by Dutchie432

.FixedHeightContainer {
    float:right;
    height: 250px;
    width:250px; 
    padding:3px; 
    background:#f00;
}

.Content {
    height:224px;
    overflow:auto;
    background:#fff;
}

Python, print all floats to 2 decimal places in output

Well I would atleast clean it up as follows:

print "%.2f kg = %.2f lb = %.2f gal = %.2f l" % (var1, var2, var3, var4)

How to cache Google map tiles for offline usage?

On http://www.google.com/earth/media/licensing.html there is a "Mobile" section containing :

Similar to our online terms, if you use our APIs or a mobile device’s native Google Maps implementation (such as on an Android-powered phone or iPhone), no special permission is required, but you must always keep the Google name visible. Offline caching of our content is never allowed.

Java switch statement: Constant expression required, but it IS constant

This was answered ages ago and probably not relevant, but just in case. When I was confronted with this issue, I simply used an if statement instead of switch, it solved the error. It is of course a workaround and probably not the "right" solution, but in my case it was just enough.

Edit: 2021.01.21

This Answer is a bit misleading, And I would like to clarify it.

  1. Replacing a switch statement with an if should not be considered as a goto solution, there are very good reasons why both concepts of switch and if exist in software development, as well as performance matters to consider when choosing between the two.
  2. Although I provide a solution to the presented error, My answer sheds no light on "why" the problem occurs but instead offers a way around the problem.

In my specific case, using an if statement instead was just enough to solve the problem. Developers should take the time and decide if this is the right solution for the current problem you have at hand.

Thus this answer should be considered solely as a workaround in specific cases as stated in my first response, and by no means as the correct answer to this question

SQL set values of one column equal to values of another column in the same table

Sounds like you're working in just one table so something like this:

update your_table
set B = A
where B is null

MySQL server has gone away - in exactly 60 seconds

This is something I do, (but usually with the MySQLi class).

$link = mysql_connect("$MYSQL_Host","$MYSQL_User","$MYSQL_Pass");
mysql_select_db($MYSQL_db, $link);

// RUN REALLY LONG QUERY HERE

// Reconnect if needed

if( !mysql_ping($link) ) $link = mysql_connect("$MYSQL_Host","$MYSQL_User","$MYSQL_Pass", true);

// RUN ANOTHER QUERY

How to show loading spinner in jQuery?

$('#message').load('index.php?pg=ajaxFlashcard', null, showResponse);
showLoad();

function showResponse() {
    hideLoad();
    ...
}

http://docs.jquery.com/Ajax/load#urldatacallback

HTML img align="middle" doesn't align an image

The attribute align=middle sets vertical alignment. To set horizontal alignment using HTML, you can wrap the element inside a center element and remove all the CSS you have now.

_x000D_
_x000D_
<center><img src=_x000D_
"http://icons.iconarchive.com/icons/rokey/popo-emotions/128/big-smile-icon.png"_x000D_
width="42" height="42"></center>
_x000D_
_x000D_
_x000D_

If you would rather do it in CSS, there are several ways. A simple one is to set text-align on a container:

_x000D_
_x000D_
<div style="text-align: center"><img src=_x000D_
"http://icons.iconarchive.com/icons/rokey/popo-emotions/128/big-smile-icon.png"_x000D_
width="42" height="42"></div>
_x000D_
_x000D_
_x000D_

C# string replace

Set your Textbox value in a string like:

string MySTring = textBox1.Text;

Then replace your string. For example, replace "Text" with "Hex":

MyString = MyString.Replace("Text", "Hex");

Or for your problem (replace "," with ;) :

MyString = MyString.Replace(@""",""", ",");

Note: If you have "" in your string you have to use @ in the back of "", like:

@"","";

Check if element is visible on screen

--- Shameless plug ---
I have added this function to a library I created vanillajs-browser-helpers: https://github.com/Tokimon/vanillajs-browser-helpers/blob/master/inView.js
-------------------------------

Well BenM stated, you need to detect the height of the viewport + the scroll position to match up with your top position. The function you are using is ok and does the job, though its a bit more complex than it needs to be.

If you don't use jQuery then the script would be something like this:

function posY(elm) {
    var test = elm, top = 0;

    while(!!test && test.tagName.toLowerCase() !== "body") {
        top += test.offsetTop;
        test = test.offsetParent;
    }

    return top;
}

function viewPortHeight() {
    var de = document.documentElement;

    if(!!window.innerWidth)
    { return window.innerHeight; }
    else if( de && !isNaN(de.clientHeight) )
    { return de.clientHeight; }
    
    return 0;
}

function scrollY() {
    if( window.pageYOffset ) { return window.pageYOffset; }
    return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}

function checkvisible( elm ) {
    var vpH = viewPortHeight(), // Viewport Height
        st = scrollY(), // Scroll Top
        y = posY(elm);
    
    return (y > (vpH + st));
}

Using jQuery is a lot easier:

function checkVisible( elm, evalType ) {
    evalType = evalType || "visible";

    var vpH = $(window).height(), // Viewport Height
        st = $(window).scrollTop(), // Scroll Top
        y = $(elm).offset().top,
        elementHeight = $(elm).height();

    if (evalType === "visible") return ((y < (vpH + st)) && (y > (st - elementHeight)));
    if (evalType === "above") return ((y < (vpH + st)));
}

This even offers a second parameter. With "visible" (or no second parameter) it strictly checks whether an element is on screen. If it is set to "above" it will return true when the element in question is on or above the screen.

See in action: http://jsfiddle.net/RJX5N/2/

I hope this answers your question.

-- IMPROVED VERSION--

This is a lot shorter and should do it as well:

function checkVisible(elm) {
  var rect = elm.getBoundingClientRect();
  var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
  return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}

with a fiddle to prove it: http://jsfiddle.net/t2L274ty/1/

And a version with threshold and mode included:

function checkVisible(elm, threshold, mode) {
  threshold = threshold || 0;
  mode = mode || 'visible';

  var rect = elm.getBoundingClientRect();
  var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
  var above = rect.bottom - threshold < 0;
  var below = rect.top - viewHeight + threshold >= 0;

  return mode === 'above' ? above : (mode === 'below' ? below : !above && !below);
}

and with a fiddle to prove it: http://jsfiddle.net/t2L274ty/2/

Animate visibility modes, GONE and VISIBLE

To animate layout changes, you can add the following attribute to your LinearLayout

android:animateLayoutChanges="true"

and it will animate changes automatically for you.


For information, if android:animateLayoutChanges="true" is used, then custom animation via anim xml will not work.

How to make a 3-level collapsing menu in Bootstrap?

Bootstrap 2.3.x and later supports the dropdown-submenu..

<ul class="dropdown-menu">
            <li><a href="#">Login</a></li>
            <li class="dropdown-submenu">
                <a tabindex="-1" href="#">More options</a>
                <ul class="dropdown-menu">
                    <li><a tabindex="-1" href="#">Second level</a></li>
                    <li><a href="#">Second level</a></li>
                    <li><a href="#">Second level</a></li>
                </ul>
            </li>
            <li><a href="#">Logout</a></li>
</ul>

Working demo on Bootply.com

Bootstrap 3 offset on right not left

I modified Bootstrap SASS (v3.3.5) based on Rukshan's answer

Add this in the end of the calc-grid-column mixin in mixins/_grid-framework.scss, right below the $type == offset if condition.

@if ($type == offset-right) {
      .col-#{$class}-offset-right-#{$index} {
          margin-right: percentage(($index / $grid-columns));
      }
  }

Modify the make-grid mixin in mixins/_grid-framework.scss to generate the offset-right classes.

// Create grid for specific class
@mixin make-grid($class) {
  @include float-grid-columns($class);
  @include loop-grid-columns($grid-columns, $class, width);
  @include loop-grid-columns($grid-columns, $class, pull);
  @include loop-grid-columns($grid-columns, $class, push);
  @include loop-grid-columns($grid-columns, $class, offset);
  @include loop-grid-columns($grid-columns, $class, offset-right);
}

You can then use the classes like col-sm-offset-right-2 and col-md-offset-right-1

How do I access ViewBag from JS

ViewBag is server side code.
Javascript is client side code.

You can't really connect them.

You can do something like this:

var x = $('#' + '@(ViewBag.CC)').val();

But it will get parsed on the server, so you didn't really connect them.

Get current URL path in PHP

<?php
function current_url()
{
    $url      = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $validURL = str_replace("&", "&amp", $url);
    return $validURL;
}
//echo "page URL is : ".current_url();

$offer_url = current_url();

?>



<?php

if ($offer_url == "checking url name") {
?> <p> hi this is manip5595 </p>

<?php
}
?>

How line ending conversions work with git core.autocrlf between different operating systems

The issue of EOLs in mixed-platform projects has been making my life miserable for a long time. The problems usually arise when there are already files with different and mixed EOLs already in the repo. This means that:

  1. The repo may have different files with different EOLs
  2. Some files in the repo may have mixed EOL, e.g. a combination of CRLF and LF in the same file.

How this happens is not the issue here, but it does happen.

I ran some conversion tests on Windows for the various modes and their combinations.
Here is what I got, in a slightly modified table:

                 | Resulting conversion when       | Resulting conversion when 
                 | committing files with various   | checking out FROM repo - 
                 | EOLs INTO repo and              | with mixed files in it and
                 |  core.autocrlf value:           | core.autocrlf value:           
--------------------------------------------------------------------------------
File             | true       | input      | false | true       | input | false
--------------------------------------------------------------------------------
Windows-CRLF     | CRLF -> LF | CRLF -> LF | as-is | as-is      | as-is | as-is
Unix -LF         | as-is      | as-is      | as-is | LF -> CRLF | as-is | as-is
Mac  -CR         | as-is      | as-is      | as-is | as-is      | as-is | as-is
Mixed-CRLF+LF    | as-is      | as-is      | as-is | as-is      | as-is | as-is
Mixed-CRLF+LF+CR | as-is      | as-is      | as-is | as-is      | as-is | as-is

As you can see, there are 2 cases when conversion happens on commit (3 left columns). In the rest of the cases the files are committed as-is.

Upon checkout (3 right columns), there is only 1 case where conversion happens when:

  1. core.autocrlf is true and
  2. the file in the repo has the LF EOL.

Most surprising for me, and I suspect, the cause of many EOL problems is that there is no configuration in which mixed EOL like CRLF+LF get normalized.

Note also that "old" Mac EOLs of CR only also never get converted.
This means that if a badly written EOL conversion script tries to convert a mixed ending file with CRLFs+LFs, by just converting LFs to CRLFs, then it will leave the file in a mixed mode with "lonely" CRs wherever a CRLF was converted to CRCRLF.
Git will then not convert anything, even in true mode, and EOL havoc continues. This actually happened to me and messed up my files really badly, since some editors and compilers (e.g. VS2010) don't like Mac EOLs.

I guess the only way to really handle these problems is to occasionally normalize the whole repo by checking out all the files in input or false mode, running a proper normalization and re-committing the changed files (if any). On Windows, presumably resume working with core.autocrlf true.

How do I enable NuGet Package Restore in Visual Studio?

As already mentioned by Mike, there is no option 'Enable NuGet Package Restore' in VS2015. You'll have to invoke the restore process manually. A nice way - without messing with files and directories - is using the NuGet Package Management Console: Click into the 'Quick start' field (usually in the upper right corner), enter console, open the management console, and enter command:

Update-Package –reinstall

This will re-install all packages of all projects in your solution. To specify a single project, enter:

Update-Package –reinstall -ProjectName MyProject

Of course this is only necessary when the Restore button - sometimes offered by VS2015 - is not available. More useful update commands are listed and explained here: https://docs.microsoft.com/en-us/nuget/consume-packages/reinstalling-and-updating-packages

Declare and Initialize String Array in VBA

Public Function _
CreateTextArrayFromSourceTexts(ParamArray SourceTexts() As Variant) As String()

    ReDim TargetTextArray(0 To UBound(SourceTexts)) As String
    
    For SourceTextsCellNumber = 0 To UBound(SourceTexts)
        TargetTextArray(SourceTextsCellNumber) = SourceTexts(SourceTextsCellNumber)
    Next SourceTextsCellNumber

    CreateTextArrayFromSourceTexts = TargetTextArray
End Function

Example:

Dim TT() As String
TT = CreateTextArrayFromSourceTexts("hi", "bye", "hi", "bcd", "bYe")

Result:

TT(0)="hi"
TT(1)="bye"
TT(2)="hi"
TT(3)="bcd"
TT(4)="bYe"

Enjoy!

Edit: I removed the duplicatedtexts deleting feature and made the code smaller and easier to use.

Is there any advantage of using map over unordered_map in case of trivial keys?

Reasons have been given in other answers; here is another.

std::map (balanced binary tree) operations are amortized O(log n) and worst case O(log n). std::unordered_map (hash table) operations are amortized O(1) and worst case O(n).

How this plays out in practice is that the hash table "hiccups" every once in a while with an O(n) operation, which may or may not be something your application can tolerate. If it can't tolerate it, you'd prefer std::map over std::unordered_map.

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

How to scale an Image in ImageView to keep the aspect ratio

Use these properties in ImageView to keep aspect ratio:

android:adjustViewBounds="true"
android:scaleType="fitXY"

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:scaleType="fitXY"
    />

ssh_exchange_identification: Connection closed by remote host under Git bash

Similar to Arun Sangal the problem lied in an in .ssh/config entry

Host my.sshhost.com
  ProxyCommand ssh -q -W %h:%p myremotemachine.my.company.com

The remote machine was added to avoid with ssh for VPN connections and worked well. But for the vacation period I switched off the myremotemachine and run into the described problem.

The declared package does not match the expected package ""

  1. Create directory [your.project.name] in workspace root directory of your project.

  2. Copy *.java from "src" to that directory.

  3. Close and reopen project.

querying WHERE condition to character length?

I think you want this:

select *
from dbo.table
where DATALENGTH(column_name) = 3

Bootstrap 3 - set height of modal window according to screen size

Try:

$('#myModal').on('show.bs.modal', function () {
$('.modal-content').css('height',$( window ).height()*0.8);
});

Object Dump JavaScript

console.log("my object: %o", myObj)

Otherwise you'll end up with a string representation sometimes displaying:

[object Object]

or some such.

Array.push() if does not exist?

http://api.jquery.com/jQuery.unique/

var cleanArray = $.unique(clutteredArray);

you might be interested in makeArray too

The previous example is best in saying that check if it exists before pushing. I see in hindsight it also states you can declare it as part of the prototype (I guess that's aka Class Extension), so no big enhancement below.

Except I'm not sure if indexOf is a faster route then inArray? probably.

Array.prototype.pushUnique = function (item){
    if(this.indexOf(item) == -1) {
    //if(jQuery.inArray(item, this) == -1) {
        this.push(item);
        return true;
    }
    return false;
}

Material UI and Grid system

I hope this is not too late to give a response.

I was also looking for a simple, robust, flexible and highly customizable bootstrap like react grid system to use in my projects.

The best I know of is react-pure-grid https://www.npmjs.com/package/react-pure-grid

react-pure-grid gives you the power to customize every aspect of your grid system, while at the same time it has built in defaults which probably suits any project

Usage

npm install react-pure-grid --save

-

import {Container, Row, Col} from 'react-pure-grid';

const App = () => (
      <Container>
        <Row>
          <Col xs={6} md={4} lg={3}>Hello, world!</Col>
        </Row>
        <Row>
            <Col xsOffset={5} xs={7}>Welcome!</Col>
        </Row>
      </Container>
);

How to insert values in two dimensional array programmatically?

You can't "add" values to an array as the array length is immutable. You can set values at specific array positions.

If you know how to do it with one-dimensional arrays then you know how to do it with n-dimensional arrays: There are no n-dimensional arrays in Java, only arrays of arrays (of arrays...).

But you can chain the index operator for array element access.

String[][] x = new String[2][];
x[0] = new String[1];
x[1] = new String[2];

x[0][0] = "a1";
    // No x[0][1] available
x[1][0] = "b1";
x[1][1] = "b2";

Note the dimensions of the child arrays don't need to match.

jQuery select box validation

To put a require rule on a select list you just need an option with an empty value

<option value="">Year</option>

then just applying required on its own is enough

<script>
    $(function () {
        $("form").validate();
    });
</script>

with form

<form>
<select name="year" id="year" class="required">
    <option value="">Year</option>
    <option value="1">1919</option>
    <option value="2">1920</option>
    <option value="3">1921</option>
    <option value="4">1922</option>
</select>
<input type="submit" />
</form>

fiddle is here

How can I remove a style added with .css() function?

Just using:

$('.tag-class').removeAttr('style');

or

$('#tag-id').removeAttr('style');

How to use Utilities.sleep() function

Some Google services do not like to be used to much. Quite recently my account was locked because of script, which was sending two e-mails per second to the same user. Google considered it as a spam. So using sleep here is also justified to prevent such situations.

What is the use of the init() usage in JavaScript?

In JavaScript when you create any object through a constructor call like below

step 1 : create a function say Person..

function Person(name){
this.name=name;
}
person.prototype.print=function(){
console.log(this.name);
}

step 2 : create an instance for this function..

var obj=new Person('venkat')

//above line will instantiate this function(Person) and return a brand new object called Person {name:'venkat'}

if you don't want to instantiate this function and call at same time.we can also do like below..

var Person = {
  init: function(name){
    this.name=name;
  },
  print: function(){
    console.log(this.name);
  }
};
var obj=Object.create(Person);
obj.init('venkat');
obj.print();

in the above method init will help in instantiating the object properties. basically init is like a constructor call on your class.

How do I run a single test using Jest?

Jest documentation recommends the following:

If a test is failing, one of the first things to check should be whether the test is failing when it's the only test that runs. In Jest it's simple to run only one test - just temporarily change that test command to a test.only

test.only('this will be the only test that runs', () => {
   expect(true).toBe(false);
});

or

it.only('this will be the only test that runs', () => {
   expect(true).toBe(false);
});

Check if a string is not NULL or EMPTY

if (-not ([string]::IsNullOrEmpty($version)))
{
    $request += "/" + $version
}

You can also use ! as an alternative to -not.

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app

I just had this issue after installing and removing some npm packages and spent almost 5 hours to figure out what was going on.

What I did is basically copied my src/components in a different directory, then removed all the node modules and package-lock.json (if you are running your app in the Docker container, remove images and rebuild it just to be safe); then reset it to my last commit and then put back my src/components then ran npm i.

I hope it helps.

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

When I had this issue with tf.train.string_input_producer() and tf.train.batch() initializing the local variables before I started the Coordinator solved the problem. I had been getting the error when I initialized the local variables after starting the Coordinator.

.htaccess - how to force "www." in a generic way?

I would use this rule:

RewriteEngine On
RewriteCond %{HTTP_HOST} !=""
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

The first condition checks whether the Host value is not empty (in case of HTTP/1.0); the second checks whether the the Host value does not begin with www.; the third checks for HTTPS (%{HTTPS} is either on or off, so %{HTTPS}s is either ons or offs and in case of ons the s is matched). The substitution part of RewriteRule then just merges the information parts to a full URL.

Launch Pycharm from command line (terminal)

This worked for me on my 2017 imac macOS Mojave (Version 10.14.3).

  1. Open your ~/.bash_profile: nano ~/.bash_profile

  2. Append the alias: alias pycharm="open /Applications/PyCharm\ CE.app"

  3. Update terminal: source ~/.bash_profile

  4. Assert that it works: pycharm

convert from Color to brush

I had same issue before, here is my class which solved color conversions Use it and enjoy :

Here U go, Use my Class to Multi Color Conversion

using System;
using System.Windows.Media;
using SDColor = System.Drawing.Color;
using SWMColor = System.Windows.Media.Color;
using SWMBrush = System.Windows.Media.Brush;

//Developed by ???? ????? ?????
namespace APREndUser.CodeAssist
{
    public static class ColorHelper
    {
        public static SWMColor ToSWMColor(SDColor color) => SWMColor.FromArgb(color.A, color.R, color.G, color.B);
        public static SDColor ToSDColor(SWMColor color) => SDColor.FromArgb(color.A, color.R, color.G, color.B);
        public static SWMBrush ToSWMBrush(SDColor color) => (SolidColorBrush)(new BrushConverter().ConvertFrom(ToHexColor(color)));
        public static string ToHexColor(SDColor c) => "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
        public static string ToRGBColor(SDColor c) => "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")";
        public static Tuple<SDColor, SDColor> GetColorFromRYGGradient(double percentage)
        {
            var red = (percentage > 50 ? 1 - 2 * (percentage - 50) / 100.0 : 1.0) * 255;
            var green = (percentage > 50 ? 1.0 : 2 * percentage / 100.0) * 255;
            var blue = 0.0;
            SDColor result1 = SDColor.FromArgb((int)red, (int)green, (int)blue);
            SDColor result2 = SDColor.FromArgb((int)green, (int)red, (int)blue);
            return new Tuple<SDColor, SDColor>(result1, result2);
        }
    }

}

How to pass a textbox value from view to a controller in MVC 4?

I'll just try to answer the question but my examples very simple because I'm new at mvc. Hope this help somebody.

    [HttpPost]  ///This function is in my controller class
    public ActionResult Delete(string txtDelete)
    {
        int _id = Convert.ToInt32(txtDelete); // put your code           
    }

This code is in my controller's cshtml

  >   @using (Html.BeginForm("Delete", "LibraryManagement"))
 {
<button>Delete</button>
@Html.Label("Enter an ID number");
@Html.TextBox("txtDelete")  }  

Just make sure the textbox name and your controller's function input are the same name and type(string).This way, your function get the textbox input.

How to style a div to be a responsive square?

To achieve what you are looking for you can use the viewport-percentage length vw.

Here is a quick example I made on jsfiddle.

HTML:

<div class="square">
    <h1>This is a Square</h1>
</div>

CSS:

.square {
    background: #000;
    width: 50vw;
    height: 50vw;
}
.square h1 {
    color: #fff;
}

I am sure there are many other ways to do this but this way seemed the best to me.

'tsc command not found' in compiling typescript

If your TSC command is not found in MacOS after proper installation of TypeScript (using the following command: $ sudo npm install -g typescript, then ensure Node /bin path is added to the PATH variable in .bash_profile.

Open .bash_profile using terminal: $ open ~/.bash_profile;

Edit/Verify bash profile to include the following line (using your favorite text editor):

export PATH="$PATH:"/usr/local/lib/node_modules/node/bin"";

Load the latest bash profile using terminal: source ~/.bash_profile;

Lastly, try the command: $ tsc --version.

Can't include C++ headers like vector in Android NDK

Even Sebastian had given a good answer there 3 more years ago, I still would like to share a new experience here, in case you will face same problem as me in new ndk version.

I have compilation error such as:

fatal error: map: No such file or directory
fatal error: vector: No such file or directory

My environment is android-ndk-r9d and adt-bundle-linux-x86_64-20140702. I add Application.mk file in same jni folder and insert one (and only one) line:

APP_STL := stlport_static

But unfortunately, it doesn't solve my problem! I have to add these 3 lines into Android.mk to solve it:

ifndef NDK_ROOT
include external/stlport/libstlport.mk
endif

And I saw a good sharing from here that says "'stlport_shared' is preferred". So maybe it's a better solution to use stlport as a shared library instead of static. Just add the following lines into Android.mk and then no need to add file Application.mk.

ifndef NDK_ROOT
include external/stlport/libstlport.mk
endif
LOCAL_SHARED_LIBRARIES += libstlport

Hope this is helpful.

Python nonlocal statement

with 'nonlocal' inner functions(ie;nested inner functions) can get read & 'write' permission for that specific variable of the outer parent function. And nonlocal can be used only inside inner functions eg:

a = 10
def Outer(msg):
    a = 20
    b = 30
    def Inner():
        c = 50
        d = 60
        print("MU LCL =",locals())
        nonlocal a
        a = 100
        ans = a+c
        print("Hello from Inner",ans)       
        print("value of a Inner : ",a)
    Inner()
    print("value of a Outer : ",a)

res = Outer("Hello World")
print(res)
print("value of a Global : ",a)

Deck of cards JAVA

Here is some code. It uses 2 classes (Card.java and Deck.java) to accomplish this issue, and to top it off it auto sorts it for you when you create the deck object. :)

import java.util.*;

public class deck2 {
    ArrayList<Card> cards = new ArrayList<Card>();

    String[] values = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
    String[] suit = {"Club", "Spade", "Diamond", "Heart"};

    static boolean firstThread = true;
    public deck2(){
        for (int i = 0; i<suit.length; i++) {
            for(int j=0; j<values.length; j++){
                this.cards.add(new Card(suit[i],values[j]));
            }
        }
        //shuffle the deck when its created
        Collections.shuffle(this.cards);

    }

    public ArrayList<Card> getDeck(){
        return cards;
    }

    public static void main(String[] args){
        deck2 deck = new deck2();

        //print out the deck.
        System.out.println(deck.getDeck());
    }

}


//separate class

public class Card {


    private String suit;
    private String value;


    public Card(String suit, String value){
        this.suit = suit;
        this.value = value;
    }
    public Card(){}
    public String getSuit(){
        return suit;
    }
    public void setSuit(String suit){
        this.suit = suit;
    }
    public String getValue(){
        return value;
    }
    public void setValue(String value){
        this.value = value;
    }

    public String toString(){
        return "\n"+value + " of "+ suit;
    }
}

mysql data directory location

If the software is Sequel pro the default install mysql on Mac OSX has data located here:

/usr/local/var/mysql

Android studio, gradle and NDK

While I believe SJoshi (oracle guy) has the most complete answer, the SWIG project is a special case, interesting and useful one, at that, but not generalized for the majority of projects that have done well with the standard SDK ant based projects + NDK. We all would like to be using Android studio now most likely, or want a more CI friendly build toolchain for mobile, which gradle theoretically offers.

I've posted my approach, borrowed from somewhere (I found this on SO, but posted a gist for the app build.gradle: https://gist.github.com/truedat101/c45ff2b69e91d5c8e9c7962d4b96e841 ). In a nutshell, I recommend the following:

  • Don't upgrade your project to the latest gradle build
  • Use com.android.tools.build:gradle:1.5.0 in your Project root
  • Use com.android.application in your app project
  • Make sure gradle.properties has: android.useDeprecatedNdk=true (in case it's complaining)
  • Use the above approach to ensure that your hours and hours of effort creating Android.mk files won't be tossed away. You control which targets arch(s) to build. And these instructions are kind to Windows users, who should theoretically be able to build on windows without special issues.

Gradle for Android has been a mess in my opinion, much as I like the maven concepts borrowed and the opinionated structure of directories for a project. This NDK feature has been "coming soon" for almost 3+ years.

How can I get a list of all functions stored in the database of a particular schema in PostgreSQL?

Is a good idea named the functions with commun alias on the first words for filtre the name with LIKE Example with public schema in Postgresql 9.4, be sure to replace with his scheme

SELECT routine_name 
FROM information_schema.routines 
WHERE routine_type='FUNCTION' 
  AND specific_schema='public'
  AND routine_name LIKE 'aliasmyfunctions%';

Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

I suspect the problem is the slashes in the format string versus the ones in the data. That's a culture-sensitive date separator character in the format string, and the final argument being null means "use the current culture". If you either escape the slashes ("M'/'d'/'yyyy") or you specify CultureInfo.InvariantCulture, it will be okay.

If anyone's interested in reproducing this:

// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M'/'d'/'yyyy", 
                                  new CultureInfo("de-DE"));

// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy", 
                                  new CultureInfo("en-US"));

// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy", 
                                  CultureInfo.InvariantCulture);

// Fails
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy", 
                                  new CultureInfo("de-DE"));

Pure JavaScript Send POST Data Without a Form

navigator.sendBeacon()

If you simply need to POST data and do not require a response from the server, the shortest solution would be to use navigator.sendBeacon():

const data = JSON.stringify({
  example_1: 123,
  example_2: 'Hello, world!',
});

navigator.sendBeacon('example.php', data);

Using tr to replace newline with space

Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings

or use:

tr '\r\n' ' '

Background Image for Select (dropdown) does not work in Chrome

select 
{
    -webkit-appearance: none;
}

If you need to you can also add an image that contains the arrow as part of the background.

mysql delete under safe mode

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

DELETE FROM MyTable WHERE MyField IS_NOT_EQUAL AnyValueNoItemOnMyFieldWillEverHave

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

Object of class stdClass could not be converted to string

I use codeignator and I got the error:

Object of class stdClass could not be converted to string.

for this post I get my result

I use in my model section

$query = $this->db->get('user', 10);
        return $query->result();

and from this post I use

$query = $this->db->get('user', 10);
        return $query->row();

and I solved my problem

Xcode variables

The best source is probably Apple's official documentation. The specific variable you are looking for is CONFIGURATION.

Simple state machine example in C#?

Not sure whether I miss the point, but I think none of the answers here are "simple" state machines. What i usually call a simple state machine is using a loop with a switch inside. That is what we used in PLC / microchip programming or in C/C++ programming at the university.

advantages:

  • easy to write. no special objects and stuff required. you dont even need object orientation for it.
  • when it is small, it is easy to understand.

disadvantages:

  • can become quite big and hard to read, when there are many states.

It looked like that:

public enum State
{
    First,
    Second,
    Third,
}

static void Main(string[] args)
{
    var state = State.First;
    // x and i are just examples for stuff that you could change inside the state and use for state transitions
    var x     = 0; 
    var i     = 0;

    // does not have to be a while loop. you could loop over the characters of a string too
    while (true)  
    {
        switch (state)
        {
            case State.First:
                // Do sth here
                if (x == 2)
                    state = State.Second;  
                    // you may or may not add a break; right after setting the next state
                // or do sth here
                if (i == 3)
                    state = State.Third;
                // or here
                break;
            case State.Second:
                // Do sth here
                if (x == 10)
                    state = State.First;
                // or do sth here
                break;
            case State.Third:
                // Do sth here
                if (x == 10)
                    state = State.First;
                // or do sth here
                break;
            default:
                // you may wanna throw an exception here.
                break;
        }
    }
}

enter image description here

if it should be really a state machine on which you call methods which react depending on which state you are in differently: state design pattern is the better approach

How to read .pem file to get private and public key

If a PEM contains only one RSA private key without encryption, it must be an ASN.1 sequence structure including 9 numbers to present a Chinese Remainder Theorem (CRT) key:

  1. version (always 0)
  2. modulus (n)
  3. public exponent (e, always 65537)
  4. private exponent (d)
  5. prime p
  6. prime q
  7. d mod (p - 1) (dp)
  8. d mod (q - 1) (dq)
  9. q^-1 mod p (qinv)

We can implement an RSAPrivateCrtKey:

class RSAPrivateCrtKeyImpl implements RSAPrivateCrtKey {
    private static final long serialVersionUID = 1L;

    BigInteger n, e, d, p, q, dp, dq, qinv;

    @Override
    public BigInteger getModulus() {
        return n;
    }

    @Override
    public BigInteger getPublicExponent() {
        return e;
    }

    @Override
    public BigInteger getPrivateExponent() {
        return d;
    }

    @Override
    public BigInteger getPrimeP() {
        return p;
    }

    @Override
    public BigInteger getPrimeQ() {
        return q;
    }

    @Override
    public BigInteger getPrimeExponentP() {
        return dp;
    }

    @Override
    public BigInteger getPrimeExponentQ() {
        return dq;
    }

    @Override
    public BigInteger getCrtCoefficient() {
        return qinv;
    }

    @Override
    public String getAlgorithm() {
        return "RSA";
    }

    @Override
    public String getFormat() {
        throw new UnsupportedOperationException();
    }

    @Override
    public byte[] getEncoded() {
        throw new UnsupportedOperationException();
    }
}

Then read the private key from a PEM file:

import sun.security.util.DerInputStream;
import sun.security.util.DerValue;

static RSAPrivateCrtKey getRSAPrivateKey(String keyFile) {
    RSAPrivateCrtKeyImpl prvKey = new RSAPrivateCrtKeyImpl();
    try (BufferedReader in = new BufferedReader(new FileReader(keyFile))) {
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null) {
            // skip "-----BEGIN/END RSA PRIVATE KEY-----"
            if (!line.startsWith("--") || !line.endsWith("--")) {
                sb.append(line);
            }
        }
        DerInputStream der = new DerValue(Base64.
                getDecoder().decode(sb.toString())).getData();
        der.getBigInteger(); // 0
        prvKey.n = der.getBigInteger();
        prvKey.e = der.getBigInteger(); // 65537
        prvKey.d = der.getBigInteger();
        prvKey.p = der.getBigInteger();
        prvKey.q = der.getBigInteger();
        prvKey.dp = der.getBigInteger();
        prvKey.dq = der.getBigInteger();
        prvKey.qinv = der.getBigInteger();
    } catch (IllegalArgumentException | IOException e) {
        logger.warn(keyFile + ": " + e.getMessage());
        return null;
    }
}

How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?

Your syntax is wrong.

You need to call attr with two parameters, like this:

$('.salesperson', newOption).attr('defaultSelected', "selected");

Your current code assigns the value "selected" to the variable defaultSelected, then passes that value to the attr function, which will then return the value of the selected attribute.

How to store Configuration file and read it using React

In case you have a .properties file or a .ini file

Actually in case if you have any file that has key value pairs like this:

someKey=someValue
someOtherKey=someOtherValue

You can import that into webpack by a npm module called properties-reader

I found this really helpful since I'm integrating react with Java Spring framework where there is already an application.properties file. This helps me to keep all config together in one place.

  1. Import that from dependencies section in package.json

"properties-reader": "0.0.16"

  1. Import this module into webpack.config.js on top

const PropertiesReader = require('properties-reader');

  1. Read the properties file

const appProperties = PropertiesReader('Path/to/your/properties.file')._properties;

  1. Import this constant as config

externals: { 'Config': JSON.stringify(appProperties) }

  1. Use it as the same way as mentioned in the accepted answer

var Config = require('Config') fetchData(Config.serverUrl + '/Enterprises/...')

How to see tomcat is running or not

for localhost,the defaut port is 8080,you can test the link http://localhost:8080 in you browser.if you can see tomcat home page,your tomcat is running

MySQL limit from descending order

This way is comparatively more easy

SELECT doc_id,serial_number,status FROM date_time ORDER BY  date_time DESC LIMIT 0,1;

Performance of FOR vs FOREACH in PHP

I think but I am not sure : the for loop takes two operations for checking and incrementing values. foreach loads the data in memory then it will iterate every values.

Creating a new column based on if-elif-else condition

df.loc[df['A'] == df['B'], 'C'] = 0
df.loc[df['A'] > df['B'], 'C'] = 1
df.loc[df['A'] < df['B'], 'C'] = -1

Easy to solve using indexing. The first line of code reads like so, if column A is equal to column B then create and set column C equal to 0.

Set bootstrap modal body height by percentage

This should work for everyone, any screen resolutions:

.modal-body {
    max-height: calc(100vh - 143px);
    overflow-y: auto; }

First, count your modal header and footer height, in my case I have H4 heading so I have them on 141px, already counted default modal margin in 20px(top+bottom).

So that subtract 141px is the max-height for my modal height, for the better result there are both border top and bottom by 1px, for this, 143px will work perfectly.

In some case of styling you may like to use overflow-y: auto; instead of overflow-y: scroll;, try it.

Try it, and you get the best result in both computer or mobile devices. If you have a heading larger than H4, recount it see how much px you would like to subtract.

If you don't know what I am telling, just change the number of 143px, see what is the best result for your case.

Last, I'd suggest have it an inline CSS.

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

How do I change the font size of a UILabel in Swift?

label.font = UIFont.systemFontOfSize(20)

How to remove array element in mongodb?

This below code will remove the complete object element from the array, where the phone number is '+1786543589455'

db.collection.update(
  { _id: id },
  { $pull: { 'contact': { number: '+1786543589455' } } }
);

Changing text color onclick

A rewrite of the answer by Sarfraz would be something like this, I think:

<script>

    document.getElementById('change').onclick = changeColor;   

    function changeColor() {
        document.body.style.color = "purple";
        return false;
    }   

</script>

You'd either have to put this script at the bottom of your page, right before the closing body tag, or put the handler assignment in a function called onload - or if you're using jQuery there's the very elegant $(document).ready(function() { ... } );

Note that when you assign event handlers this way, it takes the functionality out of your HTML. Also note you set it equal to the function name -- no (). If you did onclick = myFunc(); the function would actually execute when the handler is being set.

And I'm curious -- you knew enough to script changing the background color, but not the text color? strange:)

String contains another two strings

That is because the if statements returns false since d doesn't contain b + a i.e "someonedamage"

javax.servlet.ServletException cannot be resolved to a type in spring web app

It seems to me that eclipse doesn't recognize the java ee web api (servlets, el, and so on). If you're using maven and don't want to configure eclipse with a specified server runtime, put the dependecy below in your web project pom:

<dependency>  
    <groupId>javax</groupId>    
    <artifactId>javaee-web-api</artifactId>    
    <version>7.0</version> <!-- Put here the version of your Java EE app, in my case 7.0 -->
    <scope>provided</scope>
</dependency>

unique() for more than one variable

How about using unique() itself?

df <- data.frame(yad = c("BARBIE", "BARBIE", "BAKUGAN", "BAKUGAN"),
                 per = c("AYLIK",  "AYLIK",  "2 AYLIK", "2 AYLIK"),
                 hmm = 1:4)

df
#       yad     per hmm
# 1  BARBIE   AYLIK   1
# 2  BARBIE   AYLIK   2
# 3 BAKUGAN 2 AYLIK   3
# 4 BAKUGAN 2 AYLIK   4

unique(df[c("yad", "per")])
#       yad     per
# 1  BARBIE   AYLIK
# 3 BAKUGAN 2 AYLIK

jQuery ID starts with

try:

$("td[id^=" + value + "]")

jQuery multiple events to trigger the same function

I was looking for a way to get the event type when jQuery listens for several events at once, and Google put me here.

So, for those interested, event.type is my answer :

$('#element').on('keyup keypress blur change', function(event) {
    alert(event.type); // keyup OR keypress OR blur OR change
});

More info in the jQuery doc.

Syntax error near unexpected token 'fi'

Use Notepad ++ and use the option to Convert the file to UNIX format. That should solve this problem.

What does ':' (colon) do in JavaScript?

These are generally the scenarios where colon ':' is used in JavaScript

1- Declaring and Initializing an Object

var Car = {model:"2015", color:"blue"}; //car object with model and color properties

2- Setting a Label (Not recommended since it results in complicated control structure and Spaghetti code)

List: 
while(counter < 50)
{
     userInput += userInput;
     counter++;
     if(userInput > 10000)
     {
          break List;
     }
}

3- In Switch Statement

switch (new Date().getDay()) {
    case 6:
        text = "Today is Saturday";
        break; 
    case 0:
        text = "Today is Sunday";
        break; 
    default: 
        text = "Looking forward to the Weekend";
}

4- In Ternary Operator

document.getElementById("demo").innerHTML = age>18? "True" : "False";

CSS-Only Scrollable Table with fixed headers

if it gets rock hard where all the mentioned solutions don't work (as it got for me), try a two-tabled solutioned, as I explained in this answer

https://stackoverflow.com/a/47722456/6488361

Deploying website: 500 - Internal server error

If you're using a custom HttpHandler (i.e., implementing IHttpModule), make sure you're inspecting calls to its Error method.

You could have your handler throw the actual HttpExceptions (which have a useful Message property) during local debugging like this:

    public void Error(object sender, EventArgs e)
    {
        if (!HttpContext.Current.Request.IsLocal)
            return;
        var ex = ((HttpApplication)sender).Server.GetLastError();
        if (ex.GetType() == typeof(HttpException))
            throw ex;
    }

Also make sure to inspect the Exception's InnerException.

Can you have multiple $(document).ready(function(){ ... }); sections?

Yes you can easily have multiple blocks. Just be careful with dependencies between them as the evaluation order might not be what you expect.

How do I group Windows Form radio buttons?

Put all radio buttons for a group in a container object like a Panel or a GroupBox. That will automatically group them together in Windows Forms.

Select all text inside EditText when it gets focus

I know you've found a solution, but really the proper way to do what you're asking is to just use the android:hint attribute in your EditText. This text shows up when the box is empty and not focused, but disappears upon selecting the EditText box.

SQLite Reset Primary Key Field

Try this:

delete from your_table;    
delete from sqlite_sequence where name='your_table';

SQLite Autoincrement

SQLite keeps track of the largest ROWID that a table has ever held using the special SQLITE_SEQUENCE table. The SQLITE_SEQUENCE table is created and initialized automatically whenever a normal table that contains an AUTOINCREMENT column is created. The content of the SQLITE_SEQUENCE table can be modified using ordinary UPDATE, INSERT, and DELETE statements. But making modifications to this table will likely perturb the AUTOINCREMENT key generation algorithm. Make sure you know what you are doing before you undertake such changes.

Structure padding and packing

Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding. When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system) or larger. Data alignment means putting the data at a memory address equal to some multiple of the word size, which increases the system’s performance due to the way the CPU handles memory. To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.

  1. In order to align the data in memory, one or more empty bytes (addresses) are inserted (or left empty) between memory addresses which are allocated for other structure members while memory allocation. This concept is called structure padding.
  2. Architecture of a computer processor is such a way that it can read 1 word (4 byte in 32 bit processor) from memory at a time.
  3. To make use of this advantage of processor, data are always aligned as 4 bytes package which leads to insert empty addresses between other member’s address.
  4. Because of this structure padding concept in C, size of the structure is always not same as what we think.

What is a daemon thread in Java?

For me, daemon thread it's like house keeper for user threads. If all user threads finished , the daemon thread has no job and killed by JVM. I explained it in the YouTube video.

Jquery Smooth Scroll To DIV - Using ID value from Link

Here is my solution:

<!-- jquery smooth scroll to id's -->   
<script>
$(function() {
  $('a[href*=\\#]:not([href=\\#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 500);
        return false;
      }
    }
  });
});
</script>

With just this snippet you can use an unlimited number of hash-links and corresponding ids without having to execute a new script for each.

I already explained how it works in another thread here: https://stackoverflow.com/a/28631803/4566435 (or here's a direct link to my blog post)

For clarifications, let me know. Hope it helps!

Finding what branch a Git commit came from

If the OP is trying to determine the history that was traversed by a branch when a particular commit was created ("find out what branch a commit comes from given its SHA-1 hash value"), then without the reflog there aren't any records in the Git object database that shows what named branch was bound to what commit history.

(I posted this as an answer in reply to a comment.)

Hopefully this script illustrates my point:

rm -rf /tmp/r1 /tmp/r2; mkdir /tmp/r1; cd /tmp/r1
git init; git config user.name n; git config user.email [email protected]
git commit -m"empty" --allow-empty; git branch -m b1; git branch b2
git checkout b1; touch f1; git add f1; git commit -m"Add f1"
git checkout b2; touch f2; git add f2; git commit -m"Add f2"
git merge -m"merge branches" b1; git checkout b1; git merge b2
git clone /tmp/r1 /tmp/r2; cd /tmp/r2; git fetch origin b2:b2
set -x;
cd /tmp/r1; git log --oneline --graph --decorate; git reflog b1; git reflog b2;
cd /tmp/r2; git log --oneline --graph --decorate; git reflog b1; git reflog b2;

The output shows the lack of any way to know whether the commit with 'Add f1' came from branch b1 or b2 from the remote clone /tmp/r2.

(Last lines of the output here)

+ cd /tmp/r1
+ git log --oneline --graph --decorate
*   f0c707d (HEAD, b2, b1) merge branches
|\
| * 086c9ce Add f1
* | 80c10e5 Add f2
|/
* 18feb84 empty
+ git reflog b1
f0c707d b1@{0}: merge b2: Fast-forward
086c9ce b1@{1}: commit: Add f1
18feb84 b1@{2}: Branch: renamed refs/heads/master to refs/heads/b1
18feb84 b1@{3}: commit (initial): empty
+ git reflog b2
f0c707d b2@{0}: merge b1: Merge made by the 'recursive' strategy.
80c10e5 b2@{1}: commit: Add f2
18feb84 b2@{2}: branch: Created from b1
+ cd /tmp/r2
+ git log --oneline --graph --decorate
*   f0c707d (HEAD, origin/b2, origin/b1, origin/HEAD, b2, b1) merge branches
|\
| * 086c9ce Add f1
* | 80c10e5 Add f2
|/
* 18feb84 empty
+ git reflog b1
f0c707d b1@{0}: clone: from /tmp/r1
+ git reflog b2
f0c707d b2@{0}: fetch origin b2:b2: storing head

Easy way to use variables of enum types as string in C?

I know you have a couple good solid answers, but do you know about the # operator in the C preprocessor?

It lets you do this:

#define MACROSTR(k) #k

typedef enum {
    kZero,
    kOne,
    kTwo,
    kThree
} kConst;

static char *kConstStr[] = {
    MACROSTR(kZero),
    MACROSTR(kOne),
    MACROSTR(kTwo),
    MACROSTR(kThree)
};

static void kConstPrinter(kConst k)
{
    printf("%s", kConstStr[k]);
}

What does Docker add to lxc-tools (the userspace LXC tools)?

The above post & answers are rapidly becoming dated as the development of LXD continues to enhance LXC. Yes, I know Docker hasn't stood still either.

LXD now implements a repository for LXC container images which a user can push/pull from to contribute to or reuse.

LXD's REST api to LXC now enables both local & remote creation/deployment/management of LXC containers using a very simple command syntax.

Key features of LXD are:

  • Secure by design (unprivileged containers, resource restrictions and much more)
  • Scalable (from containers on your laptop to thousand of compute nodes)
  • Intuitive (simple, clear API and crisp command line experience)
  • Image based (no more distribution templates, only good, trusted images) Live migration

There is NCLXD plugin now for OpenStack allowing OpenStack to utilize LXD to deploy/manage LXC containers as VMs in OpenStack instead of using KVM, vmware etc.

However, NCLXD also enables a hybrid cloud of a mix of traditional HW VMs and LXC VMs.

The OpenStack nclxd plugin a list of features supported include:

stop/start/reboot/terminate container
Attach/detach network interface
Create container snapshot
Rescue/unrescue instance container
Pause/unpause/suspend/resume container
OVS/bridge networking
instance migration
firewall support

By the time Ubuntu 16.04 is released in Apr 2016 there will have been additional cool features such as block device support, live-migration support.

How to overcome root domain CNAME restrictions?

The reason this question still often arises is because, as you mentioned, somewhere somehow someone presumed as important wrote that the RFC states domain names without subdomain in front of them are not valid. If you read the RFC carefully, however, you'll find that this is not exactly what it says. In fact, RFC 1912 states:

Don't go overboard with CNAMEs. Use them when renaming hosts, but plan to get rid of them (and inform your users).

Some DNS hosts provide a way to get CNAME-like functionality at the zone apex (the root domain level, for the naked domain name) using a custom record type. Such records include, for example:

  • ALIAS at DNSimple
  • ANAME at DNS Made Easy
  • ANAME at easyDNS
  • CNAME at CloudFlare

For each provider, the setup is similar: point the ALIAS or ANAME entry for your apex domain to example.domain.com, just as you would with a CNAME record. Depending on the DNS provider, an empty or @ Name value identifies the zone apex.

ALIAS or ANAME or @ example.domain.com.

If your DNS provider does not support such a record-type, and you are unable to switch to one that does, you will need to use subdomain redirection, which is not that hard, depending on the protocol or server software that needs to do it.

I strongly disagree with the statement that it's done only by "amateur admins" or such ideas. It's a simple "What does the name and its service need to do?" deal, and then to adapt your DNS config to serve those wishes; If your main services are web and e-mail, I don' t see any VALID reason why dropping the CNAMEs for-good would be problematic. After all, who would prefer @subdomain.domain.org over @domain.org ? Who needs "www" if you're already set with the protocol itself? It's illogical to assume that use of a root-domainname would be invalid.

What is the bower (and npm) version syntax?

You can also use the latest keyword to install the most recent version available:

  "dependencies": {
    "fontawesome": "latest"
  }

How can you encode a string to Base64 in JavaScript?

To make a Base64 encoded String URL friendly, in JavaScript you could do something like this:

// if this is your Base64 encoded string
var str = 'VGhpcyBpcyBhbiBhd2Vzb21lIHNjcmlwdA=='; 

// make URL friendly:
str = str.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');

// reverse to original encoding
str = (str + '===').slice(0, str.length + (str.length % 4));
str = str.replace(/-/g, '+').replace(/_/g, '/');

See also this Fiddle: http://jsfiddle.net/magikMaker/7bjaT/

Custom designing EditText

enter image description here

For EditText in image above, You have to create two xml files in res-->drawable folder. First will be "bg_edittext_focused.xml" paste the lines of code in it

<?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >
        <solid android:color="#FFFFFF" />
        <stroke
            android:width="2dip"
            android:color="#F6F6F6" />
        <corners android:radius="2dip" />
        <padding
            android:bottom="7dip"
            android:left="7dip"
            android:right="7dip"
            android:top="7dip" />
    </shape>

Second file will be "bg_edittext_normal.xml" paste the lines of code in it

<?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >
        <solid android:color="#F6F6F6" />
        <stroke
            android:width="2dip"
            android:color="#F6F6F6" />
        <corners android:radius="2dip" />
        <padding
            android:bottom="7dip"
            android:left="7dip"
            android:right="7dip"
            android:top="7dip" />
    </shape>

In res-->drawable folder create another xml file with name "bg_edittext.xml" that will call above mentioned code. paste the following lines of code below in bg_edittext.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/bg_edittext_focused" android:state_focused="true"/>
    <item android:drawable="@drawable/bg_edittext_normal"/>
</selector>

Finally in res-->layout-->example.xml file in your case wherever you created your editText you'll call bg_edittext.xml as background

   <EditText
    :::::
    :::::  
    android:background="@drawable/bg_edittext"
    :::::
    :::::
    />

LINQ: combining join and group by

We did it like this:

from p in Products                         
join bp in BaseProducts on p.BaseProductId equals bp.Id                    
where !string.IsNullOrEmpty(p.SomeId) && p.LastPublished >= lastDate                         
group new { p, bp } by new { p.SomeId } into pg    
let firstproductgroup = pg.FirstOrDefault()
let product = firstproductgroup.p
let baseproduct = firstproductgroup.bp
let minprice = pg.Min(m => m.p.Price)
let maxprice = pg.Max(m => m.p.Price)
select new ProductPriceMinMax
{
SomeId = product.SomeId,
BaseProductName = baseproduct.Name,
CountryCode = product.CountryCode,
MinPrice = minprice, 
MaxPrice = maxprice
};

EDIT: we used the version of AakashM, because it has better performance

How to activate the Bootstrap modal-backdrop?

Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.

<div class="modal-backdrop"></div>

Made a small demo: http://jsfiddle.net/PfBnq/

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

Use the Apache commons StringUtils.normalizeSpace(String str) method. See docs here

Difference between float and decimal data type

This is what I found when I had this doubt.

mysql> create table numbers (a decimal(10,2), b float);
mysql> insert into numbers values (100, 100);
mysql> select @a := (a/3), @b := (b/3), @a * 3, @b * 3 from numbers \G
*************************** 1. row ***************************
  @a := (a/3): 33.333333333
  @b := (b/3): 33.333333333333
@a + @a + @a: 99.999999999000000000000000000000
@b + @b + @b: 100

The decimal did exactly what's supposed to do on this cases, it truncated the rest, thus losing the 1/3 part.

So for sums the decimal is better, but for divisions the float is better, up to some point, of course. I mean, using DECIMAL will not give you a "fail proof arithmetic" in any means.

Hope this helps.

How to prevent long words from breaking my div?

This is a complex issue, as we know, and not supported in any common way between browsers. Most browsers don't support this feature natively at all.

In some work done with HTML emails, where user content was being used, but script is not available (and even CSS is not supported very well) the following bit of CSS in a wrapper around your unspaced content block should at least help somewhat:

.word-break {
  /* The following styles prevent unbroken strings from breaking the layout */
  width: 300px; /* set to whatever width you need */
  overflow: auto;
  white-space: -moz-pre-wrap; /* Mozilla */
  white-space: -hp-pre-wrap; /* HP printers */
  white-space: -o-pre-wrap; /* Opera 7 */
  white-space: -pre-wrap; /* Opera 4-6 */
  white-space: pre-wrap; /* CSS 2.1 */
  white-space: pre-line; /* CSS 3 (and 2.1 as well, actually) */
  word-wrap: break-word; /* IE */
  -moz-binding: url('xbl.xml#wordwrap'); /* Firefox (using XBL) */
}

In the case of Mozilla-based browsers, the XBL file mentioned above contains:

<?xml version="1.0" encoding="utf-8"?>
<bindings xmlns="http://www.mozilla.org/xbl" 
          xmlns:html="http://www.w3.org/1999/xhtml">
  <!--
  More information on XBL:
  http://developer.mozilla.org/en/docs/XBL:XBL_1.0_Reference

  Example of implementing the CSS 'word-wrap' feature:
  http://blog.stchur.com/2007/02/22/emulating-css-word-wrap-for-mozillafirefox/
  -->
  <binding id="wordwrap" applyauthorstyles="false">
    <implementation>
      <constructor>
        //<![CDATA[
        var elem = this;

        doWrap();
        elem.addEventListener('overflow', doWrap, false);

        function doWrap() {
          var walker = document.createTreeWalker(elem, NodeFilter.SHOW_TEXT, null, false);
          while (walker.nextNode()) {
            var node = walker.currentNode;
            node.nodeValue = node.nodeValue.split('').join(String.fromCharCode('8203'));
          }
        }
        //]]>
      </constructor>
    </implementation>
  </binding>
</bindings>

Unfortunately, Opera 8+ don't seem to like any of the above solutions, so JavaScript will have to be the solution for those browsers (like Mozilla/Firefox.) Another cross-browser solution (JavaScript) that includes the later editions of Opera would be to use Hedger Wang's script found here: http://www.hedgerwow.com/360/dhtml/css-word-break.html

Other useful links/thoughts:

Incoherent Babble » Blog Archive » Emulating CSS word-wrap for Mozilla/Firefox
http://blog.stchur.com/2007/02/22/emulating-css-word-wrap-for-mozillafirefox/

[OU] No word wrap in Opera, displays fine in IE
http://list.opera.com/pipermail/opera-users/2004-November/024467.html
http://list.opera.com/pipermail/opera-users/2004-November/024468.html

MySQL Query GROUP BY day / month / year

I prefer to optimize the one year group selection like so:

SELECT COUNT(*)
  FROM stats
 WHERE record_date >= :year 
   AND record_date <  :year + INTERVAL 1 YEAR;

This way you can just bind the year in once, e.g. '2009', with a named parameter and don't need to worry about adding '-01-01' or passing in '2010' separately.

Also, as presumably we are just counting rows and id is never NULL, I prefer COUNT(*) to COUNT(id).

PHP - concatenate or directly insert variables in string

Double-quoted strings are more elegant because you don't have to break up your string every time you need to insert a variable (like you must do with single-quoted strings).

However, if you need to insert the return value of a function, this cannot be inserted into a double-quoted string--even if you surround it with braces!

//syntax error!!
//$s = "Hello {trim($world)}!"

//the only option
$s = "Hello " . trim($world) . "!";

how to change the dist-folder path in angular-cli after 'ng build'

Beware: The correct answer is below. This no longer works

Create a file called .ember-cli in your project, and include in it these contents:

{
   "output-path": "./location/to/your/dist/"
}

How do I create HTML table using jQuery dynamically?

An example with a little less stringified html:

var container = $('#my-container'),
  table = $('<table>');

users.forEach(function(user) {
  var tr = $('<tr>');
  ['ID', 'Name', 'Address'].forEach(function(attr) {
    tr.append('<td>' + user[attr] + '</td>');
  });
  table.append(tr);
});

container.append(table);

What's the best way to set a single pixel in an HTML5 canvas?

Draw a rectangle like sdleihssirhc said!

ctx.fillRect (10, 10, 1, 1);

^-- should draw a 1x1 rectangle at x:10, y:10

MySQL equivalent of DECODE function in Oracle

If additional table doesn't fit, you can write your own function for translation.

The plus of sql function over case is, that you can use it in various places, and keep translation logic in one place.

How can I remove a child node in HTML using JavaScript?

A jQuery solution

HTML

<select id="foo">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

Javascript

// remove child "option" element with a "value" attribute equal to "2"
$("#foo > option[value='2']").remove();

// remove all child "option" elements
$("#foo > option").remove();

References:

Attribute Equals Selector [name=value]

Selects elements that have the specified attribute with a value exactly equal to a certain value.

Child Selector (“parent > child”)

Selects all direct child elements specified by "child" of elements specified by "parent"

.remove()

Similar to .empty(), the .remove() method takes elements out of the DOM. We use .remove() when we want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

Read all files in a folder and apply a function to each data frame

Here is a tidyverse option that might not the most elegant, but offers some flexibility in terms of what is included in the summary:

library(tidyverse)
dir_path <- '~/path/to/data/directory/'
file_pattern <- 'Df\\.[0-9]\\.csv' # regex pattern to match the file name format

read_dir <- function(dir_path, file_name){
  read_csv(paste0(dir_path, file_name)) %>% 
    mutate(file_name = file_name) %>%                # add the file name as a column              
    gather(variable, value, A:B) %>%                 # convert the data from wide to long
    group_by(file_name, variable) %>% 
    summarize(sum = sum(value, na.rm = TRUE),
              min = min(value, na.rm = TRUE),
              mean = mean(value, na.rm = TRUE),
              median = median(value, na.rm = TRUE),
              max = max(value, na.rm = TRUE))
  }

df_summary <- 
  list.files(dir_path, pattern = file_pattern) %>% 
  map_df(~ read_dir(dir_path, .))

df_summary
# A tibble: 8 x 7
# Groups:   file_name [?]
  file_name variable   sum   min  mean median   max
  <chr>     <chr>    <int> <dbl> <dbl>  <dbl> <dbl>
1 Df.1.csv  A           34     4  5.67    5.5     8
2 Df.1.csv  B           22     1  3.67    3       9
3 Df.2.csv  A           21     1  3.5     3.5     6
4 Df.2.csv  B           16     1  2.67    2.5     5
5 Df.3.csv  A           30     0  5       5      11
6 Df.3.csv  B           43     1  7.17    6.5    15
7 Df.4.csv  A           21     0  3.5     3       8
8 Df.4.csv  B           42     1  7       6      16

Get the number of rows in a HTML table

Well it depends on what you have in your table.

its one of the following If you have only one table

var count = $('#gvPerformanceResult tr').length;

If you are concerned about sub tables but this wont work with tbody and thead (if you use them)

var count = $('#gvPerformanceResult>tr').length;

Where by this will work (but is quite frankly overkill.)

var count = $('#gvPerformanceResult>tbody>tr').length;

How can I insert vertical blank space into an html document?

write it like this

p {
    padding-bottom: 3cm;
}

or

p {
    margin-bottom: 3cm;
}

How do I set ANDROID_SDK_HOME environment variable?

ANDROID_HOME

Deprecated (in Android Studio), use ANDROID_SDK_ROOT instead.

ANDROID_SDK_ROOT

Installation directory of Android SDK package.

Example: C:\AndroidSDK or /usr/local/android-sdk/

ANDROID_NDK_ROOT

Installation directory of Android NDK package. (WITHOUT ANY SPACE)

Example: C:\AndroidNDK or /usr/local/android-ndk/

ANDROID_SDK_HOME

Location of SDK related data/user files.

Example: C:\Users\<USERNAME>\.android\ or ~/.android/

ANDROID_EMULATOR_HOME

Location of emulator-specific data files.

Example: C:\Users\<USERNAME>\.android\ or ~/.android/

ANDROID_AVD_HOME

Location of AVD-specific data files.

Example: C:\Users\<USERNAME>\.android\avd\ or ~/.android/avd/

JDK_HOME and JAVA_HOME

Installation directory of JDK (aka Java SDK) package.

Note: This is used to run Android Studio(and other Java-based applications). Actually when you run Android Studio, it checks for JDK_HOME then JAVA_HOME environment variables to use.

Is there a "do ... until" in Python?

No there isn't. Instead use a while loop such as:

while 1:
 ...statements...
  if cond:
    break

How to change time in DateTime?

DateTime is an immutable type, so you can't change it.

However, you can create a new DateTime instance based on your previous instance. In your case, it sounds like you need the Date property, and you can then add a TimeSpan that represents the time of day.

Something like this:

var newDt = s.Date + TimeSpan.FromHours(2);

C++/CLI Converting from System::String^ to std::string

C# uses the UTF16 format for its strings.
So, besides just converting the types, you should also be conscious about the string's actual format.

When compiling for Multi-byte Character set Visual Studio and the Win API assumes UTF8 (Actually windows encoding which is Windows-28591 ).
When compiling for Unicode Character set Visual studio and the Win API assume UTF16.

So, you must convert the string from UTF16 to UTF8 format as well, and not just convert to std::string.
This will become necessary when working with multi-character formats like some non-latin languages.

The idea is to decide that std::wstring always represents UTF16.
And std::string always represents UTF8.

This isn't enforced by the compiler, it's more of a good policy to have.

#include "stdafx.h"
#include <string>
#include <codecvt>
#include <msclr\marshal_cppstd.h>

using namespace System;

int main(array<System::String ^> ^args)
{
    System::String^ managedString = "test";

    msclr::interop::marshal_context context;

    //Actual format is UTF16, so represent as wstring
    std::wstring utf16NativeString = context.marshal_as<std::wstring>(managedString); 

    //C++11 format converter
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> convert;

    //convert to UTF8 and std::string
    std::string utf8NativeString = convert.to_bytes(utf16NativeString);

    return 0;
}

Or have it in a more compact syntax:

int main(array<System::String ^> ^args)
{
    System::String^ managedString = "test";

    msclr::interop::marshal_context context;
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> convert;

    std::string utf8NativeString = convert.to_bytes(context.marshal_as<std::wstring>(managedString));

    return 0;
}

cURL POST command line on WINDOWS RESTful service

We can use below Curl command in Windows Command prompt to send the request. Use the Curl command below, replace single quote with double quotes, remove quotes where they are not there in below format and use the ^ symbol.

curl http://localhost:7101/module/url ^
  -d @D:/request.xml ^
  -H "Content-Type: text/xml" ^
  -H "SOAPAction: process" ^
  -H "Authorization: Basic xyz" ^
  -X POST

Change the color of a bullet in a html list?

The bullet gets its color from the text. So if you want to have a different color bullet than text in your list you'll have to add some markup.

Wrap the list text in a span:

<ul>
  <li><span>item #1</span></li>
  <li><span>item #2</span></li>
  <li><span>item #3</span></li>
</ul>

Then modify your style rules slightly:

li {
  color: red; /* bullet color */
}
li span {
  color: black; /* text color */
}

Hadoop cluster setup - java.net.ConnectException: Connection refused

I was getting the same issue and found that OpenSSH service was not running and it was causing the issue. After starting the SSH service it worked.

To check if SSH service is running or not:

ssh localhost

To start the service, if OpenSSH is already installed:

sudo /etc/init.d/ssh start

How to clear all inputs, selects and also hidden fields in a form using jQuery?

To clear all inputs, including hidden fields, using JQuery:

// Behold the power of JQuery.
$('input').val('');

Selects are harder, because they have a fixed list. Do you want to clear that list, or just the selection.

Could be something like

$('option').attr('selected', false);

How do I copy a version of a single file from one git branch to another?

I would use git restore (available since git 2.23)

git restore --source otherbranch path/to/myfile.txt


Why it is better than other options?

git checkout otherbranch -- path/to/myfile.txt - It copy file to working directory but also to staging area (similar effect as if you would copy this file manually and executed git add on it). git restore doesn't touch staging area (unless told it to by --staged option).

git show otherbranch:path/to/myfile.txt > path/to/myfile.txt uses standard shell redirection. If you use Powershell then there might be problem with text enconding or you could get broken file if it's binary. With git restore changing files is done all by git executable.

Another advantage is that you can restore whole folder with:

git restore --source otherbranch path/to

or with git restore --overlay --source otherbranch path/to if you want to avoid deleting files. For example if there is less files on otherbranch than in current working directory (and these files are tracked) without --overlay option git restore will delete them. But this is good default bahaviour, you most likely want the state of directory to be "the same like in otherbranch", not "the same like in otherbranch but with additional files from my current branch"

Cannot read property 'map' of undefined

The error occur mainly becuase the array isnt found. Just check if you have mapped to the correct array. Check the array name or declaration.

Sort & uniq in Linux shell

I have worked on some servers where sort don't support '-u' option. there we have to use

sort xyz | uniq

Eclipse : Maven search dependencies doesn't work

It is neccesary to provide Group Id and Artifact Id to download the jar file you need. If you want to search it just use * , * for these fields.

NSUserDefaults - How to tell if a key exists

As mentioned above it wont work for primitive types where 0/NO could be a valid value. I am using this code.

NSUserDefaults *defaults= [NSUserDefaults standardUserDefaults];
if([[[defaults dictionaryRepresentation] allKeys] containsObject:@"mykey"]){

    NSLog(@"mykey found");
}

How to write a basic swap function in Java

In cases like that there is a quick and dirty solution using arrays with one element:

public void swap(int[] a, int[] b) {
  int temp = a[0];
  a[0] = b[0];
  b[0] = temp;
}

Of course your code has to work with these arrays too, which is inconvenient. The array trick is more useful if you want to modify a local final variable from an inner class:

public void test() {
  final int[] a = int[]{ 42 };  
  new Thread(new Runnable(){ public void run(){ a[0] += 10; }}).start();
  while(a[0] == 42) {
    System.out.println("waiting...");   
  }
  System.out.println(a[0]);   
} 

How to unzip a file in Powershell?

Here is a simple way using ExtractToDirectory from System.IO.Compression.ZipFile:

Add-Type -AssemblyName System.IO.Compression.FileSystem
function Unzip
{
    param([string]$zipfile, [string]$outpath)

    [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)
}

Unzip "C:\a.zip" "C:\a"

Note that if the target folder doesn't exist, ExtractToDirectory will create it. Other caveats:

See also:

cannot open shared object file: No such file or directory

Copied from my answer here: https://stackoverflow.com/a/9368199/485088

Run ldconfig as root to update the cache - if that still doesn't help, you need to add the path to the file ld.so.conf (just type it in on its own line) or better yet, add the entry to a new file (easier to delete) in directory ld.so.conf.d.

How to show "if" condition on a sequence diagram?

In Visual Studio UML sequence this can also be described as fragments which is nicely documented here: https://msdn.microsoft.com/en-us/library/dd465153.aspx

dotnet ef not found in .NET Core 3

Global tools can be installed in the default directory or in a specific location. The default directories are:

  • Linux/macOS ---> $HOME/.dotnet/tools

  • Windows ---> %USERPROFILE%\.dotnet\tools

If you're trying to run a global tool, check that the PATH environment variable on your machine contains the path where you installed the global tool and that the executable is in that path.

Troubleshoot .NET Core tool usage issues

Android: how to convert whole ImageView to Bitmap?

try {
        photo.setImageURI(Uri.parse("Location");
        BitmapDrawable drawable = (BitmapDrawable) photo.getDrawable();
        Bitmap bitmap = drawable.getBitmap();
        bitmap = Bitmap.createScaledBitmap(bitmap, 70, 70, true);
        photo.setImageBitmap(bitmap);

    } catch (Exception e) {

    }

How do I convert between ISO-8859-1 and UTF-8 in Java?

The easiest way to convert an ISO-8859-1 string to UTF-8 string.

private static String convertIsoToUTF8(String example) throws UnsupportedEncodingException {
    return new String(example.getBytes("ISO-8859-1"), "utf-8");
}

If we want to convert an UTF-8 string to ISO-8859-1 string.

private static String convertUTF8ToISO(String example) throws UnsupportedEncodingException {
    return new String(example.getBytes("utf-8"), "ISO-8859-1");
}

Moreover, a method that converts an ISO-8859-1 string to UTF-8 string without using the constructor of class String.

public static String convertISO_to_UTF8_personal(String strISO_8859_1) {
    String res = "";
    int i = 0;
    for (i = 0; i < strISO_8859_1.length() - 1; i++) {
        char ch = strISO_8859_1.charAt(i);
        char chNext = strISO_8859_1.charAt(i + 1);
        if (ch <= 127) {
            res += ch;
        } else if (ch == 194 && chNext >= 128 && chNext <= 191) {
            res += chNext;
        } else if(ch == 195 && chNext >= 128 && chNext <= 191){
            int resNum = chNext + 64;
            res += (char) resNum;
        } else if(ch == 194){
            res += (char) 173;
        } else if(ch == 195){
            res += (char) 224;
        }
    }
    char ch = strISO_8859_1.charAt(i);
    if (ch <= 127 ){
        res += ch;
    }
    return res;
}

}

That method is based on enconding utf-8 to iso-8859-1 of this website. Encoding utf-8 to iso-8859-1

How can I time a code segment for testing performance with Pythons timeit?

Focus on one specific thing. Disk I/O is slow, so I'd take that out of the test if all you are going to tweak is the database query.

And if you need to time your database execution, look for database tools instead, like asking for the query plan, and note that performance varies not only with the exact query and what indexes you have, but also with the data load (how much data you have stored).

That said, you can simply put your code in a function and run that function with timeit.timeit():

def function_to_repeat():
    # ...

duration = timeit.timeit(function_to_repeat, number=1000)

This would disable the garbage collection, repeatedly call the function_to_repeat() function, and time the total duration of those calls using timeit.default_timer(), which is the most accurate available clock for your specific platform.

You should move setup code out of the repeated function; for example, you should connect to the database first, then time only the queries. Use the setup argument to either import or create those dependencies, and pass them into your function:

def function_to_repeat(var1, var2):
    # ...

duration = timeit.timeit(
    'function_to_repeat(var1, var2)',
    'from __main__ import function_to_repeat, var1, var2', 
    number=1000)

would grab the globals function_to_repeat, var1 and var2 from your script and pass those to the function each repetition.

Getting net::ERR_UNKNOWN_URL_SCHEME while calling telephone number from HTML page in Android

I had this issue occurring with mailto: and tel: links inside an iframe (in Chrome, not a webview). Clicking the links would show the grey "page not found" page and inspecting the page showed it had a ERR_UNKNOWN_URL_SCHEME error.

Adding target="_blank", as suggested by this discussion of the issue fixed the problem for me.

How to safely open/close files in python 2.4

No need to close the file according to the docs if you use with:

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:

>>> with open('workfile', 'r') as f:
...     read_data = f.read()
>>> f.closed
True

More here: https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

How to convert a HTMLElement to a string

You can get the 'outer-html' by cloning the element, adding it to an empty,'offstage' container, and reading the container's innerHTML.

This example takes an optional second parameter.

Call document.getHTML(element, true) to include the element's descendents.

document.getHTML= function(who, deep){
    if(!who || !who.tagName) return '';
    var txt, ax, el= document.createElement("div");
    el.appendChild(who.cloneNode(false));
    txt= el.innerHTML;
    if(deep){
        ax= txt.indexOf('>')+1;
        txt= txt.substring(0, ax)+who.innerHTML+ txt.substring(ax);
    }
    el= null;
    return txt;
}

How to save select query results within temporary table?

select *
into #TempTable
from SomeTale

select *
from #TempTable

Paritition array into N chunks with Numpy

Not quite an answer, but a long comment with nice formatting of code to the other (correct) answers. If you try the following, you will see that what you are getting are views of the original array, not copies, and that was not the case for the accepted answer in the question you link. Be aware of the possible side effects!

>>> x = np.arange(9.0)
>>> a,b,c = np.split(x, 3)
>>> a
array([ 0.,  1.,  2.])
>>> a[1] = 8
>>> a
array([ 0.,  8.,  2.])
>>> x
array([ 0.,  8.,  2.,  3.,  4.,  5.,  6.,  7.,  8.])
>>> def chunks(l, n):
...     """ Yield successive n-sized chunks from l.
...     """
...     for i in xrange(0, len(l), n):
...         yield l[i:i+n]
... 
>>> l = range(9)
>>> a,b,c = chunks(l, 3)
>>> a
[0, 1, 2]
>>> a[1] = 8
>>> a
[0, 8, 2]
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8]

Redis: Show database size/size for keys

You can use .net application https://github.com/abhiyx/RedisSizeCalculator to calculate the size of redis key,

Please feel free to give your feedback for the same

How to update all MySQL table rows at the same time?

The default null value for a field is "not null". So you must set it to "null" before you can set that field value for any record to null. Then you can:

UPDATE `myTable` SET `myField` = null

What does Maven do, in theory and in practice? When is it worth to use it?

What it does

Maven is a "build management tool", it is for defining how your .java files get compiled to .class, packaged into .jar (or .war or .ear) files, (pre/post)processed with tools, managing your CLASSPATH, and all others sorts of tasks that are required to build your project. It is similar to Apache Ant or Gradle or Makefiles in C/C++, but it attempts to be completely self-contained in it that you shouldn't need any additional tools or scripts by incorporating other common tasks like downloading & installing necessary libraries etc.

It is also designed around the "build portability" theme, so that you don't get issues as having the same code with the same buildscript working on one computer but not on another one (this is a known issue, we have VMs of Windows 98 machines since we couldn't get some of our Delphi applications compiling anywhere else). Because of this, it is also the best way to work on a project between people who use different IDEs since IDE-generated Ant scripts are hard to import into other IDEs, but all IDEs nowadays understand and support Maven (IntelliJ, Eclipse, and NetBeans). Even if you don't end up liking Maven, it ends up being the point of reference for all other modern builds tools.

Why you should use it

There are three things about Maven that are very nice.

  1. Maven will (after you declare which ones you are using) download all the libraries that you use and the libraries that they use for you automatically. This is very nice, and makes dealing with lots of libraries ridiculously easy. This lets you avoid "dependency hell". It is similar to Apache Ant's Ivy.

  2. It uses "Convention over Configuration" so that by default you don't need to define the tasks you want to do. You don't need to write a "compile", "test", "package", or "clean" step like you would have to do in Ant or a Makefile. Just put the files in the places in which Maven expects them and it should work off of the bat.

  3. Maven also has lots of nice plug-ins that you can install that will handle many routine tasks from generating Java classes from an XSD schema using JAXB to measuring test coverage with Cobertura. Just add them to your pom.xml and they will integrate with everything else you want to do.

The initial learning curve is steep, but (nearly) every professional Java developer uses Maven or wishes they did. You should use Maven on every project although don't be surprised if it takes you a while to get used to it and that sometimes you wish you could just do things manually, since learning something new sometimes hurts. However, once you truly get used to Maven you will find that build management takes almost no time at all.

How to Start

The best place to start is "Maven in 5 Minutes". It will get you start with a project ready for you to code in with all the necessary files and folders set-up (yes, I recommend using the quickstart archetype, at least at first).

After you get started you'll want a better understanding over how the tool is intended to be used. For that "Better Builds with Maven" is the most thorough place to understand the guts of how it works, however, "Maven: The Complete Reference" is more up-to-date. Read the first one for understanding, but then use the second one for reference.

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

How to add url parameters to Django template url tag?

First you need to prepare your url to accept the param in the regex: (urls.py)

url(r'^panel/person/(?P<person_id>[0-9]+)$', 'apps.panel.views.person_form', name='panel_person_form'),

So you use this in your template:

{% url 'panel_person_form' person_id=item.id %}

If you have more than one param, you can change your regex and modify the template using the following:

{% url 'panel_person_form' person_id=item.id group_id=3 %}

HttpServletRequest get JSON POST data

Are you posting from a different source (so different port, or hostname)? If so, this very very recent topic I just answered might be helpful.

The problem was the XHR Cross Domain Policy, and a useful tip on how to get around it by using a technique called JSONP. The big downside is that JSONP does not support POST requests.

I know in the original post there is no mention of JavaScript, however JSON is usually used for JavaScript so that's why I jumped to that conclusion

How to hide a div with jQuery?

$('#myDiv').hide(); hide function is used to edit content and show function is used to show again.

For more please click on this link.

Find the most common element in a list

Borrowing from here, this can be used with Python 2.7:

from collections import Counter

def Most_Common(lst):
    data = Counter(lst)
    return data.most_common(1)[0][0]

Works around 4-6 times faster than Alex's solutions, and is 50 times faster than the one-liner proposed by newacct.

To retrieve the element that occurs first in the list in case of ties:

def most_common(lst):
    data = Counter(lst)
    return max(lst, key=data.get)

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

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

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

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

to install bundler that matches with your Gemfile.lock use:

gem install bundler -v "$(grep -A 1 "BUNDLED WITH" Gemfile.lock | tail -n 1)"

minimize app to system tray

I found this to accomplish the entire solution. The answer above fails to remove the window from the task bar.

private void ImportStatusForm_Resize(object sender, EventArgs e)
{
    if (this.WindowState == FormWindowState.Minimized)
    {
        notifyIcon.Visible = true;
        notifyIcon.ShowBalloonTip(3000);
        this.ShowInTaskbar = false;
    }
}

private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
{
    this.WindowState = FormWindowState.Normal;
    this.ShowInTaskbar = true;
    notifyIcon.Visible = false;
}

Also it is good to set the following properties of the notify icon control using the forms designer.

this.notifyIcon.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info; //Shows the info icon so the user doesn't think there is an error.
this.notifyIcon.BalloonTipText = "[Balloon Text when Minimized]";
this.notifyIcon.BalloonTipTitle = "[Balloon Title when Minimized]";
this.notifyIcon.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon.Icon"))); //The tray icon to use
this.notifyIcon.Text = "[Message shown when hovering over tray icon]";

Is there an alternative sleep function in C to milliseconds?

#include <stdio.h>
#include <stdlib.h>
int main () {

puts("Program Will Sleep For 2 Seconds");

system("sleep 2");      // works for linux systems


return 0;
}

CSS to select/style first word

Use the strong element, that is it's purpose:

<div id="content">
    <p><strong>First Word</strong> rest of paragraph.</p>
</div>

Then create a style for it in your style sheet.

#content p strong
{
    font-size: 14pt;
}

How to change text color of cmd with windows batch script every 1 second

Try this command:

@echo off
cls
:loop
echo RAINBOW
color 0
echo RAINBOW
color 1
echo RAINBOW
color 2
echo RAINBOW
color 3
echo RAINBOW
color 4
echo RAINBOW
color 5
echo RAINBOW
color 6
echo RAINBOW
color 8
echo RAINBOW
color 9
echo RAINBOW
color A
echo RAINBOW
color B
echo RAINBOW
color C
echo RAINBOW
color D
echo RAINBOW
color E
echo RAINBOW
goto loop

This should create color changing text go in a loop.
Edit: You can change the words rainbow to whatever you want.

How can I make a CSS glass/blur effect work for an overlay?

Here's a solution that works with fixed backgrounds, if you have a fixed background and you have some overlayed elements and you need blured backgrounds for them, this solution works:

Image we have this simple HTML:

<body> <!-- or any wrapper -->
   <div class="content">Some Texts</div>
</body>

A fixed background for <body> or the wrapper element:

body {
  background-image: url(http://placeimg.com/640/360/any);
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: fixed;
}

And here for example we have a overlayed element with a white transparent background:

.content {
  background-color: rgba(255, 255, 255, 0.3);
  position: relative;
}

Now we need to use the exact same background image of our wrapper for our overlay elements too, i use it as a :before psuedo-class:

.content:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  filter: blur(5px);
  background-image: url(http://placeimg.com/640/360/any);
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: fixed;
}

Since the fixed background works in a same way in both wrapper and overlayed elements, we have the background in exactly same scroll position of the overlayed element and we can simply blur it. Here's a working fiddle, tested in Firefox, Chrome, Opera and Edge: https://jsfiddle.net/0vL2rc4d/

NOTE: In firefox there's a bug that makes screen flicker when scrolling and there are fixed blurred backgrounds. if there's any fix, let me know

IF function with 3 conditions

You can simplify the 5 through 21 part:

=IF(E9>21,"Text1",IF(E9>4,"Text2","Text3"))

PDF Blob - Pop up window not showing content

problem is, it is not converted to proper format. Use function "printPreview(binaryPDFData)" to get print preview dialog of binary pdf data. you can comment script part if you don't want print dialog open.

printPreview = (data, type = 'application/pdf') => {
    let blob = null;
    blob = this.b64toBlob(data, type);
    const blobURL = URL.createObjectURL(blob);
    const theWindow = window.open(blobURL);
    const theDoc = theWindow.document;
    const theScript = document.createElement('script');
    function injectThis() {
        window.print();
    }
    theScript.innerHTML = `window.onload = ${injectThis.toString()};`;
    theDoc.body.appendChild(theScript);
};

b64toBlob = (content, contentType) => {
    contentType = contentType || '';
    const sliceSize = 512;
     // method which converts base64 to binary
    const byteCharacters = window.atob(content); 

    const byteArrays = [];
    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        const slice = byteCharacters.slice(offset, offset + sliceSize);
        const byteNumbers = new Array(slice.length);
        for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }
        const byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
    }
    const blob = new Blob(byteArrays, {
        type: contentType
    }); // statement which creates the blob
    return blob;
};

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

Inside ContentPlaceholder, put the placeholder control.For Example like this,

<asp:Content ID="header" ContentPlaceHolderID="head" runat="server">
       <asp:PlaceHolder ID="metatags" runat="server">
        </asp:PlaceHolder>
</asp:Content>

Code Behind:

HtmlMeta hm1 = new HtmlMeta();
hm1.Name = "Description";
hm1.Content = "Content here";
metatags.Controls.Add(hm1);

Passing array in GET for a REST call

This worked for me.

/users?ids[]=id1&ids[]=id2

How can I select checkboxes using the Selenium Java WebDriver?

You can use the following code:

List<WebElement> checkbox = driver.findElements(By.name("vehicle"));
((WebElement) checkbox.get(0)).click();

My HTML code was as follows:

<.input type="checkbox" name="vehicle" value="Bike">I have a bike<br/>
<.input type="checkbox" name="vehicle" value="Car">I have a car<br/>

"Initializing" variables in python?

The issue is in the line -

grade_1, grade_2, grade_3, average = 0.0

and

fName, lName, ID, converted_ID = ""

In python, if the left hand side of the assignment operator has multiple variables, python would try to iterate the right hand side that many times and assign each iterated value to each variable sequentially. The variables grade_1, grade_2, grade_3, average need three 0.0 values to assign to each variable.

You may need something like -

grade_1, grade_2, grade_3, average = [0.0 for _ in range(4)]
fName, lName, ID, converted_ID = ["" for _ in range(4)]

Resize Cross Domain Iframe Height

Minimum crossdomain set I've used for embedding fitted single iframe on a page.

On embedding page (containing iframe):

<iframe frameborder="0" id="sizetracker" src="http://www.hurtta.com/Services/SizeTracker/DE" width="100%"></iframe>
<script type="text/javascript">
  // Create browser compatible event handler.
  var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
  var eventer = window[eventMethod];
  var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
  // Listen for a message from the iframe.
  eventer(messageEvent, function(e) {
    if (isNaN(e.data)) return;

    // replace #sizetracker with what ever what ever iframe id you need
    document.getElementById('sizetracker').style.height = e.data + 'px';

  }, false);
</script>

On embedded page (iframe):

<script type="text/javascript">
function sendHeight()
{
    if(parent.postMessage)
    {
        // replace #wrapper with element that contains 
        // actual page content
        var height= document.getElementById('wrapper').offsetHeight;
        parent.postMessage(height, '*');
    }
}

// Create browser compatible event handler.
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listen for a message from the iframe.
eventer(messageEvent, function(e) {

    if (isNaN(e.data)) return;

    sendHeight();

}, 
false);
</script>

What is Java Servlet?

Servlet is a java class to respond a HTTP request and produce a HTTP response...... when we make a page with the use of HTML then it would be a static page so to make it dynamic we use SERVLET {in simple words one can understand} To make use of servlet is overcomed by JSP it uses the code and HTML tag both in itself..

How to redirect the output of DBMS_OUTPUT.PUT_LINE to a file?

DBMS_OUTPUT is not the best tool to debug, since most environments don't use it natively. If you want to capture the output of DBMS_OUTPUT however, you would simply use the DBMS_OUTPUT.get_line procedure.

Here is a small example:

SQL> create directory tmp as '/tmp/';

Directory created

SQL> CREATE OR REPLACE PROCEDURE write_log AS
  2     l_line VARCHAR2(255);
  3     l_done NUMBER;
  4     l_file utl_file.file_type;
  5  BEGIN
  6     l_file := utl_file.fopen('TMP', 'foo.log', 'A');
  7     LOOP
  8        EXIT WHEN l_done = 1;
  9        dbms_output.get_line(l_line, l_done);
 10        utl_file.put_line(l_file, l_line);
 11     END LOOP;
 12     utl_file.fflush(l_file);
 13     utl_file.fclose(l_file);
 14  END write_log;
 15  /

Procedure created

SQL> BEGIN
  2     dbms_output.enable(100000);
  3     -- write something to DBMS_OUTPUT
  4     dbms_output.put_line('this is a test');
  5     -- write the content of the buffer to a file
  6     write_log;
  7  END;
  8  /

PL/SQL procedure successfully completed

SQL> host cat /tmp/foo.log

this is a test

Binary numbers in Python

Binary, decimal, hexadecimal... the base only matters when reading or outputting numbers, adding binary numbers is just the same as adding decimal number : it is just a matter of representation.

How to remove gaps between subplots in matplotlib?

Another method is to use the pad keyword from plt.subplots_adjust(), which also accepts negative values:

import matplotlib.pyplot as plt

ax = [plt.subplot(2,2,i+1) for i in range(4)]

for a in ax:
    a.set_xticklabels([])
    a.set_yticklabels([])

plt.subplots_adjust(pad=-5.0)

Additionally, to remove the white at the outer fringe of all subplots (i.e. the canvas), always save with plt.savefig(fname, bbox_inches="tight").

Change the image source on rollover using jQuery

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>JQuery</title>
<script src="jquery.js" type="text/javascript"> </script>
<style type="text/css">
    #box{
        width: 68px;
        height: 27px;
        background: url(images/home1.gif);
        cursor: pointer;
    }
</style>

<script type="text/javascript">

$(function(){

    $('#box').hover( function(){
        $('#box').css('background', 'url(images/home2.gif)');

    });
    $('#box').mouseout( function(){
        $('#box').css('background', 'url(images/home1.gif)');

    });

});
</script>
</head>

<body>
<div id="box" onclick="location.href='index.php';"></div>
</body>
</html>

How can I view the contents of an ElasticSearch index?

I can recommend Elasticvue, which is modern, free and open source. It allows accessing your ES instance via browser add-ons quite easily (supports Firefox, Chrome, Edge). But there are also further ways.

Just make sure you set cors values in elasticsearch.yml appropiate.

How to get the first 2 letters of a string in Python?

t = "your string"

Play with the first N characters of a string with

def firstN(s, n=2):
    return s[:n]

which is by default equivalent to

t[:2]

How do I POST form data with UTF-8 encoding by using curl?

You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.

You should use this request:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod

#1071 - Specified key was too long; max key length is 767 bytes

We encountered this issue when trying to add a UNIQUE index to a VARCHAR(255) field using utf8mb4. While the problem is outlined well here already, I wanted to add some practical advice for how we figured this out and solved it.

When using utf8mb4, characters count as 4 bytes, whereas under utf8, they could as 3 bytes. InnoDB databases have a limit that indexes can only contain 767 bytes. So when using utf8, you can store 255 characters (767/3 = 255), but using utf8mb4, you can only store 191 characters (767/4 = 191).

You're absolutely able to add regular indexes for VARCHAR(255) fields using utf8mb4, but what happens is the index size is truncated at 191 characters automatically - like unique_key here:

Sequel Pro screenshot showing index truncated at 191 characters

This is fine, because regular indexes are just used to help MySQL search through your data more quickly. The whole field doesn't need to be indexed.

So, why does MySQL truncate the index automatically for regular indexes, but throw an explicit error when trying to do it for unique indexes? Well, for MySQL to be able to figure out if the value being inserted or updated already exists, it needs to actually index the whole value and not just part of it.

At the end of the day, if you want to have a unique index on a field, the entire contents of the field must fit into the index. For utf8mb4, this means reducing your VARCHAR field lengths to 191 characters or less. If you don't need utf8mb4 for that table or field, you can drop it back to utf8 and be able to keep your 255 length fields.

vertical divider between two columns in bootstrap

Assuming you have a column space, this is an option. Rebalance the columns depending on what you need.

<div class="col-1">
    <div class="col-6 vhr">
    </div>
</div>
.vhr{
  border-right: 1px solid #333;
  height:100%;
}

Javascript: The prettiest way to compare one value against multiple values

(foobar == foo || foobar == bar) otherwise if you are comparing expressions based only on a single integer, enumerated value, or String object you can use switch. See The switch Statement. You can also use the method suggested by André Alçada Padez. Ultimately what you select will need to depend on the details of what you are doing.

SQL Server converting varbinary to string

This works in both SQL 2005 and 2008:

declare @source varbinary(max);
set @source = 0x21232F297A57A5A743894A0E4A801FC3;
select cast('' as xml).value('xs:hexBinary(sql:variable("@source"))', 'varchar(max)');

CSS3 transition on click using pure CSS

Method #1: CSS :focus pseudo-class

As pure CSS solution, you could achieve sort of the effect by using a tabindex attribute for the image, and :focus pseudo-class as follows:

<img class="crossRotate" src="http://placehold.it/100" tabindex="1" />
.crossRotate {
    outline: 0;
    /* other styles... */
}

.crossRotate:focus {
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
}

WORKING DEMO.

Note: Using this approach, the image gets rotated onclick (focused), to negate the rotation, you'll need to click somewhere out of the image (blured).

Method #2: Hidden input & :checked pseudo-class

This is one of my favorite methods. In this approach, there's a hidden checkbox input and a <label> element which wraps the image.

Once you click on the image, the hidden input is checked because of using for attribute for the label.

Hence by using the :checked pseudo-class and adjacent sibling selector +, we could get the image to be rotated:

<input type="checkbox" id="hacky-input">

<label for="hacky-input">
  <img class="crossRotate" src="http://placehold.it/100">
</label>
#hacky-input {
  display: none; /* Hide the input */
}

#hacky-input:checked + label img.crossRotate {
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
}

WORKING DEMO #1.

WORKING DEMO #2 (Applying the rotate to the label gives a better experience).

Method #3: Toggling a class via JavaScript

If using JavaScript/jQuery is an option, you could toggle a .active class by .toggleClass() to trigger the rotation effect, as follows:

$('.crossRotate').on('click', function(){
    $(this).toggleClass('active');
});
.crossRotate.active {
    /* vendor-prefixes here... */
    transform: rotate(45deg);
}

WORKING DEMO.

RESTful API methods; HEAD & OPTIONS

OPTIONS method returns info about API (methods/content type)

HEAD method returns info about resource (version/length/type)

Server response

OPTIONS

HTTP/1.1 200 OK
Allow: GET,HEAD,POST,OPTIONS,TRACE
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:24:43 GMT
Content-Length: 0

HEAD

HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:12:29 GMT
ETag: "780602-4f6-4db31b2978ec0"
Last-Modified: Thu, 25 Apr 2013 16:13:23 GMT
Content-Length: 1270
  • OPTIONS Identifying which HTTP methods a resource supports, e.g. can we DELETE it or update it via a PUT?
  • HEAD Checking whether a resource has changed. This is useful when maintaining a cached version of a resource
  • HEAD Retrieving metadata about the resource, e.g. its media type or its size, before making a possibly costly retrieval
  • HEAD, OPTIONS Testing whether a resource exists and is accessible. For example, validating user-submitted links in an application

Here is nice and concise article about how HEAD and OPTIONS fit into RESTful architecture.

How can I remove 3 characters at the end of a string in php?

<?php echo substr($string, 0, strlen($string) - 3); ?>

Swift error : signal SIGABRT how to solve it

For me, This error was because i had a prepare segue step that wasn't applicable to the segue that was being done.

long story:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        let gosetup = segue.destination as! Update
        gosetup.wherefrom = updatestring

    }

This was being done to all segue when it was only for one. So i create a boolean and placed the gosetup inside it.

What's an object file in C?

An object file is the real output from the compilation phase. It's mostly machine code, but has info that allows a linker to see what symbols are in it as well as symbols it requires in order to work. (For reference, "symbols" are basically names of global objects, functions, etc.)

A linker takes all these object files and combines them to form one executable (assuming that it can, ie: that there aren't any duplicate or undefined symbols). A lot of compilers will do this for you (read: they run the linker on their own) if you don't tell them to "just compile" using command-line options. (-c is a common "just compile; don't link" option.)

Testing if value is a function

// This should be a function, because in certain JavaScript engines (V8, for
// example, try block kills many optimizations).
function isFunction(func) {
    // For some reason, function constructor doesn't accept anonymous functions.
    // Also, this check finds callable objects that aren't function (such as,
    // regular expressions in old WebKit versions), as according to EcmaScript
    // specification, any callable object should have typeof set to function.
    if (typeof func === 'function')
        return true

    // If the function isn't a string, it's probably good idea to return false,
    // as eval cannot process values that aren't strings.
    if (typeof func !== 'string')
        return false

    // So, the value is a string. Try creating a function, in order to detect
    // syntax error.
    try {
        // Create a function with string func, in order to detect whatever it's
        // an actual function. Unlike examples with eval, it should be actually
        // safe to use with any string (provided you don't call returned value).
        Function(func)
        return true
    }
    catch (e) {
        // While usually only SyntaxError could be thrown (unless somebody
        // modified definition of something used in this function, like
        // SyntaxError or Function, it's better to prepare for unexpected.
        if (!(e instanceof SyntaxError)) {
            throw e
        }

        return false
    }
}

Python Pandas Replacing Header with Top Row

new_header = df.iloc[0] #grab the first row for the header
df = df[1:] #take the data less the header row
df.columns = new_header #set the header row as the df header

Node.js fs.readdir recursive directory search

A library called Filehound is another option. It will recursively search a given directory (working directory by default). It supports various filters, callbacks, promises and sync searches.

For example, search the current working directory for all files (using callbacks):

const Filehound = require('filehound');

Filehound.create()
.find((err, files) => {
    if (err) {
        return console.error(`error: ${err}`);
    }
    console.log(files); // array of files
});

Or promises and specifying a specific directory:

const Filehound = require('filehound');

Filehound.create()
.paths("/tmp")
.find()
.each(console.log);

Consult the docs for further use cases and examples of usage: https://github.com/nspragg/filehound

Disclaimer: I'm the author.

splitting a number into the integer and decimal parts

This variant allows getting desired precision:

>>> a = 1234.5678
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e0)
(1234, 0.0)
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e1)
(1234, 0.5)
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e15)
(1234, 0.5678)

How to properly upgrade node using nvm

Node.JS to install a new version.

Step 1 : NVM Install

npm i -g nvm

Step 2 : NODE Newest version install

nvm install *.*.*(NodeVersion)

Step 3 : Selected Node Version

nvm use *.*.*(NodeVersion)

Finish

Psql list all tables

Connect to the database, then list the tables:

\c liferay
\dt

That's how I do it anyway.

You can combine those two commands onto a single line, if you prefer:

\c liferay \dt

Python, Unicode, and the Windows console

The cause of your problem is NOT the Win console not willing to accept Unicode (as it does this since I guess Win2k by default). It is the default system encoding. Try this code and see what it gives you:

import sys
sys.getdefaultencoding()

if it says ascii, there's your cause ;-) You have to create a file called sitecustomize.py and put it under python path (I put it under /usr/lib/python2.5/site-packages, but that is differen on Win - it is c:\python\lib\site-packages or something), with the following contents:

import sys
sys.setdefaultencoding('utf-8')

and perhaps you might want to specify the encoding in your files as well:

# -*- coding: UTF-8 -*-
import sys,time

Edit: more info can be found in excellent the Dive into Python book

How can I pass a parameter to a t-sql script?

Two options save vijay.sql

declare
begin
execute immediate 
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||to_char(sysdate,'YYYYMMDD')||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
       sel.tactical_select_executive_flag,
       sel.agent_name,
       res.DMS_RESIGN_CAMPAIGN_CODE,
       pclub.tactical_select_flag
FROM   spineowner.pop_wkly_refresh_20100201 wk,
       dms_bb_coverage_102009 bbc,
       dms_select_executive_group sel,
       DMS_RESIGN_CAMPAIGN_26052009 res,
       DMS_PRIORITY_CLUB pclub
WHERE  wk.mpn = bbc.mpn(+)
AND    wk.mpn = sel.mpn (+)
AND    wk.mpn = res.mpn (+)
AND    wk.mpn = pclub.mpn (+)'
end;
/

The above will generate table names automatically based on sysdate. If you still need to pass as variable, then save vijay.sql as

declare
begin
execute immediate 
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||&1||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
       sel.tactical_select_executive_flag,
       sel.agent_name,
       res.DMS_RESIGN_CAMPAIGN_CODE,
       pclub.tactical_select_flag
FROM   spineowner.pop_wkly_refresh_20100201 wk,
       dms_bb_coverage_102009 bbc,
       dms_select_executive_group sel,
       DMS_RESIGN_CAMPAIGN_26052009 res,
       DMS_PRIORITY_CLUB pclub
WHERE  wk.mpn = bbc.mpn(+)
AND    wk.mpn = sel.mpn (+)
AND    wk.mpn = res.mpn (+)
AND    wk.mpn = pclub.mpn (+)'
end;
/

and then run as sqlplus -s username/password @vijay.sql '20100101'

How do I check if a string is valid JSON in Python?

I would say parsing it is the only way you can really entirely tell. Exception will be raised by python's json.loads() function (almost certainly) if not the correct format. However, the the purposes of your example you can probably just check the first couple of non-whitespace characters...

I'm not familiar with the JSON that facebook sends back, but most JSON strings from web apps will start with a open square [ or curly { bracket. No images formats I know of start with those characters.

Conversely if you know what image formats might show up, you can check the start of the string for their signatures to identify images, and assume you have JSON if it's not an image.

Another simple hack to identify a graphic, rather than a text string, in the case you're looking for a graphic, is just to test for non-ASCII characters in the first couple of dozen characters of the string (assuming the JSON is ASCII).

How to modify list entries during for loop?

In short, to do modification on the list while iterating the same list.

list[:] = ["Modify the list" for each_element in list "Condition Check"]

example:

list[:] = [list.remove(each_element) for each_element in list if each_element in ["data1", "data2"]]

What are good ways to prevent SQL injection?

SQL injection should not be prevented by trying to validate your input; instead, that input should be properly escaped before being passed to the database.

How to escape input totally depends on what technology you are using to interface with the database. In most cases and unless you are writing bare SQL (which you should avoid as hard as you can) it will be taken care of automatically by the framework so you get bulletproof protection for free.

You should explore this question further after you have decided exactly what your interfacing technology will be.