Programs & Examples On #Onmousemove

The "onmousemove" event is a event that is triggered when the user moves the mouse pointer on an element.

javascript get x and y coordinates on mouse click

It sounds like your printMousePos function should:

  1. Get the X and Y coordinates of the mouse
  2. Add those values to the HTML

Currently, it does this:

  1. Creates (undefined) variables for the X and Y coordinates of the mouse
  2. Attaches a function to the "mousemove" event (which will set those variables to the mouse coordinates when triggered by a mouse move)
  3. Adds the current values of your variables to the HTML

See the problem? Your variables are never getting set, because as soon as you add your function to the "mousemove" event you print them.

It seems like you probably don't need that mousemove event at all; I would try something like this:

function printMousePos(e) {
    var cursorX = e.pageX;
    var cursorY = e.pageY;
    document.getElementById('test').innerHTML = "x: " + cursorX + ", y: " + cursorY;
}

Real mouse position in canvas

You need to get the mouse position relative to the canvas

To do that you need to know the X/Y position of the canvas on the page.

This is called the canvas’s “offset”, and here’s how to get the offset. (I’m using jQuery in order to simplify cross-browser compatibility, but if you want to use raw javascript a quick Google will get that too).

    var canvasOffset=$("#canvas").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;

Then in your mouse handler, you can get the mouse X/Y like this:

  function handleMouseDown(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
}

Here is an illustrating code and fiddle that shows how to successfully track mouse events on the canvas:

http://jsfiddle.net/m1erickson/WB7Zu/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var canvasOffset=$("#canvas").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;

    function handleMouseDown(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      $("#downlog").html("Down: "+ mouseX + " / " + mouseY);

      // Put your mousedown stuff here

    }

    function handleMouseUp(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      $("#uplog").html("Up: "+ mouseX + " / " + mouseY);

      // Put your mouseup stuff here
    }

    function handleMouseOut(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      $("#outlog").html("Out: "+ mouseX + " / " + mouseY);

      // Put your mouseOut stuff here
    }

    function handleMouseMove(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      $("#movelog").html("Move: "+ mouseX + " / " + mouseY);

      // Put your mousemove stuff here

    }

    $("#canvas").mousedown(function(e){handleMouseDown(e);});
    $("#canvas").mousemove(function(e){handleMouseMove(e);});
    $("#canvas").mouseup(function(e){handleMouseUp(e);});
    $("#canvas").mouseout(function(e){handleMouseOut(e);});

}); // end $(function(){});
</script>

</head>

<body>
    <p>Move, press and release the mouse</p>
    <p id="downlog">Down</p>
    <p id="movelog">Move</p>
    <p id="uplog">Up</p>
    <p id="outlog">Out</p>
    <canvas id="canvas" width=300 height=300></canvas>

</body>
</html>

How to linebreak an svg text within javascript?

I suppese you alredy managed to solve it, but if someone is looking for similar solution then this worked for me:

 g.append('svg:text')
  .attr('x', 0)
  .attr('y', 30)
  .attr('class', 'id')
  .append('svg:tspan')
  .attr('x', 0)
  .attr('dy', 5)
  .text(function(d) { return d.name; })
  .append('svg:tspan')
  .attr('x', 0)
  .attr('dy', 20)
  .text(function(d) { return d.sname; })
  .append('svg:tspan')
  .attr('x', 0)
  .attr('dy', 20)
  .text(function(d) { return d.idcode; })

There are 3 lines separated with linebreak.

Get pixel color from canvas, on mousemove

Merging various references found here in StackOverflow (including the article above) and in other sites, I did so using javascript and JQuery:

<html>
<body>
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script src="jquery.js"></script>
<script type="text/javascript">
    window.onload = function(){
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');
        var img = new Image();
        img.src = 'photo_apple.jpg';
        context.drawImage(img, 0, 0);
    };

    function findPos(obj){
    var current_left = 0, current_top = 0;
    if (obj.offsetParent){
        do{
            current_left += obj.offsetLeft;
            current_top += obj.offsetTop;
        }while(obj = obj.offsetParent);
        return {x: current_left, y: current_top};
    }
    return undefined;
    }

    function rgbToHex(r, g, b){
    if (r > 255 || g > 255 || b > 255)
        throw "Invalid color component";
    return ((r << 16) | (g << 8) | b).toString(16);
    }

$('#myCanvas').click(function(e){
    var position = findPos(this);
    var x = e.pageX - position.x;
    var y = e.pageY - position.y;
    var coordinate = "x=" + x + ", y=" + y;
    var canvas = this.getContext('2d');
    var p = canvas.getImageData(x, y, 1, 1).data;
    var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
    alert("HEX: " + hex);
});
</script>
<img src="photo_apple.jpg"/>
</body>
</html>

This is my complete solution. Here I only used canvas and one image, but if you need to use <map> over the image, it's possible too.

javascript createElement(), style problem

I found this page when I was trying to set the backgroundImage attribute of a div, but hadn't wrapped the backgroundImage value with url(). This worked fine:

for (var i=0; i<20; i++) {
  // add a wrapper around an image element
  var wrapper = document.createElement('div');
  wrapper.className = 'image-cell';

  // add the image element
  var img = document.createElement('div');
  img.className = 'image';
  img.style.backgroundImage = 'url(http://via.placeholder.com/350x150)';

  // add the image to its container; add both to the body
  wrapper.appendChild(img);
  document.body.appendChild(wrapper);
}

Define a global variable in a JavaScript function

Classic example:

window.foo = 'bar';

A modern, safe example following best practice by using an IIFE:

;(function (root) {
    'use strict'

    root.foo = 'bar';
)(this));

Nowadays, there's also the option of using the WebStorage API:

localStorage.foo = 42;

or

sessionStorage.bar = 21;

Performance-wise, I'm not sure whether it is noticeably slower than storing values in variables.

Widespread browser support as stated on Can I use....

HTML Canvas Full Screen

Well, I was looking to make my canvas fullscreen too, This is how i did it. I'll post the entire index.html since I am not a CSS expert yet : (basically just using position:fixed and width and height as 100% and top and left as 0% and i nested this CSS code for every tag. I also have min-height and min-width as 100%. When I tried it with a 1px border the border size was changing as I zoomed in and out but the canvas remained fullscreen.)

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">_x000D_
<head>_x000D_
<title>MOUSEOVER</title>_x000D_
<script "text/javascript" src="main.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
_x000D_
<body id="BODY_CONTAINER" style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">_x000D_
_x000D_
_x000D_
_x000D_
<div id="DIV_GUI_CONTAINER" style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">_x000D_
_x000D_
<canvas id="myCanvas"  style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">_x000D_
_x000D_
</canvas>_x000D_
_x000D_
</div>_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

EDIT: add this to the canvas element:

_x000D_
_x000D_
<canvas id="myCanvas" width="" height="" style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">_x000D_
_x000D_
</canvas>
_x000D_
_x000D_
_x000D_

add this to the javascript

canvas.width = window.screen.width;

canvas.height = window.screen.height;

I found this made the drawing a lot smoother than my original comment.

Thanks.

Displaying tooltip on mouse hover of a text

Use:

ToolTip tip = new ToolTip();
private void richTextBox1_MouseMove(object sender, MouseEventArgs e)
{
    Cursor a = System.Windows.Forms.Cursor.Current;
    if (a == Cursors.Hand)
    {
        Point p = richTextBox1.Location;
        tip.Show(
            GetWord(richTextBox1.Text,
                richTextBox1.GetCharIndexFromPosition(e.Location)),
            this,
            p.X + e.X,
            p.Y + e.Y + 32,
            1000);
    }
}

Use the GetWord function from my other answer to get the hovered word. Use timer logic to disable reshow the tooltip as in prev. example.

In this example right above, the tool tip shows the hovered word by checking the mouse pointer.

If this answer is still not what you are looking fo, please specify the condition that characterizes the word you want to use tooltip on. If you want it for bolded word, please tell me.

Change the image source on rollover using jQuery

If the solution you are looking for is for an animated button, then the best you can do to improve in performance is the combination of sprites and CSS. A sprite is a huge image that contains all the images from your site (header, logo, buttons, and all decorations you have). Each image you have uses an HTTP request, and the more HTTP requests the more time it will take to load.

.buttonClass {
    width: 25px;
    height: 25px;
    background: url(Sprite.gif) -40px -500px;
}
.buttonClass:hover {
    width: 25px;
    height: 25px;
    background: url(Sprite.gif) -40px -525px;
}

The 0px 0px coordinates will be the left upper corner from your sprites.

But if you are developing some photo album with Ajax or something like that, then JavaScript (or any framework) is the best.

Have fun!

Need help rounding to 2 decimal places

It is caused by a lack of precision with doubles / decimals (i.e. - the function will not always give the result you expect).

See the following link: MSDN on Math.Round

Here is the relevant quote:

Because of the loss of precision that can result from representing decimal values as floating-point numbers or performing arithmetic operations on floating-point values, in some cases the Round(Double, Int32, MidpointRounding) method may not appear to round midpoint values as specified by the mode parameter.This is illustrated in the following example, where 2.135 is rounded to 2.13 instead of 2.14.This occurs because internally the method multiplies value by 10digits, and the multiplication operation in this case suffers from a loss of precision.

Make XAMPP / Apache serve file outside of htdocs folder

If you're trying to get XAMPP to use a network drive as your document root you have to use UNC paths in httpd.conf. XAMPP will not recognize your mapped network drives.

For example the following won't work, DocumentRoot "X:/webroot"

But this will, DocumentRoot "//192.168.10.100/webroot" (note the forward slashes, not back slashes)

JSP : JSTL's <c:out> tag

Older versions of JSP did not support the second syntax.

How do I select the "last child" with a specific class name in CSS?

$('.class')[$(this).length - 1] 

or

$( "p" ).last().addClass( "selected" );

'names' attribute must be the same length as the vector

I want to explain the error with an example below:

> names(lenses)
[1] "X1..1..1..1..1..3"

names(lenses)=c("ID","Age","Sight","Astigmatism","Tear","Class") Error in names(lenses) = c("ID", "Age", "Sight", "Astigmatism", "Tear", : 'names' attribute [6] must be the same length as the vector [1]

The error happened because of mismatch in a number of attributes. I only have one but trying to add 6 names. In this case, the error happens. See below the correct one:::::>>>>

> names(lenses)=c("ID")
> names(lenses)

[1] "ID"

Now there was no error.

I hope this will help!

Positioning the colorbar

using padding pad

In order to move the colorbar relative to the subplot, one may use the pad argument to fig.colorbar.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

fig.colorbar(im, orientation="horizontal", pad=0.2)
plt.show()

enter image description here

using an axes divider

One can use an instance of make_axes_locatable to divide the axes and create a new axes which is perfectly aligned to the image plot. Again, the pad argument would allow to set the space between the two axes.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np; np.random.seed(1)

fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

divider = make_axes_locatable(ax)
cax = divider.new_vertical(size="5%", pad=0.7, pack_start=True)
fig.add_axes(cax)
fig.colorbar(im, cax=cax, orientation="horizontal")

plt.show()

enter image description here

using subplots

One can directly create two rows of subplots, one for the image and one for the colorbar. Then, setting the height_ratios as gridspec_kw={"height_ratios":[1, 0.05]} in the figure creation, makes one of the subplots much smaller in height than the other and this small subplot can host the colorbar.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

fig, (ax, cax) = plt.subplots(nrows=2,figsize=(4,4), 
                  gridspec_kw={"height_ratios":[1, 0.05]})
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

fig.colorbar(im, cax=cax, orientation="horizontal")

plt.show()

enter image description here

If/else else if in Jquery for a condition

If statement for images in jquery:
#html

<button id="chain">Chain</button>
<img src="bulb_on.jpg" alt="img" id="img"/>

#script
    <script>
        $(document).ready(function(){
            $("#chain").click(function(){
            if($("#img").attr('src')!='bulb_on.jpg'){
                $("#img").attr('src', 'bulb_on.jpg');
            }
            else
            {
                $("#img").attr('src', 'bulb_onn.jpg');
            }
            });
        });
    </script>

Create a new file in git bash

This is a very simple to create file in git bash at first write touch then file name with extension

for example

touch filename.extension

Change fill color on vector asset in Android Studio

Update: AppCompat support

Other answers suspecting if android:tint will work on only 21+ devices only, AppCompat(v23.2.0 and above) now provides a backward compatible handling of tint attribute.

So, the course of action would be to use AppCompatImageView and app:srcCompat(in AppCompat namespace) instead of android:src(Android namespace).

Here is an example(AndroidX: This is androidx.appcompat.widget.AppCompatImageView ;)):

<android.support.v7.widget.AppCompatImageView
        android:id="@+id/credits_material_icon"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"
        android:scaleType="fitCenter"
        android:tint="#ffd2ee"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:srcCompat="@drawable/ic_dollar_coin_stack" />

And don't forget to enable vector drawable support in gradle:

vectorDrawables.useSupportLibrary = true 

__init__ and arguments in Python

Every method needs to accept one argument: The instance itself (or the class if it is a static method).

Read more about classes in Python.

How can I avoid getting this MySQL error Incorrect column specifier for column COLUMN NAME?

You cannot auto increment the char values. It should be int or long(integers or floating points). Try with this,

CREATE TABLE discussion_topics (
    topic_id int(5) NOT NULL AUTO_INCREMENT,
    project_id char(36) NOT NULL,
    topic_subject VARCHAR(255) NOT NULL,
    topic_content TEXT default NULL,
    date_created DATETIME NOT NULL,
    date_last_post DATETIME NOT NULL,
    created_by_user_id char(36) NOT NULL,
    last_post_user_id char(36) NOT NULL,
    posts_count char(36) default NULL,
    PRIMARY KEY (`topic_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

Hope this helps

How to calculate the bounding box for a given lat/lng location?

It is very simple just go to panoramio website and then open World Map from panoramio website.Then go to specified location whichs latitude and longitude required.

Then you found latitude and longitude in address bar for example in this address.

http://www.panoramio.com/map#lt=32.739485&ln=70.491211&z=9&k=1&a=1&tab=1&pl=all

lt=32.739485 =>latitude ln=70.491211 =>longitude

this Panoramio JavaScript API widget create a bounding box around a lat/long pair and then returning all photos with in those bounds.

Another type of Panoramio JavaScript API widget in which you can also change background color with example and code is here.

It does not show in composing mood.It show after publishing.

<div dir="ltr" style="text-align: center;" trbidi="on">
<script src="https://ssl.panoramio.com/wapi/wapi.js?v=1&amp;hl=en"></script>
<div id="wapiblock" style="float: right; margin: 10px 15px"></div>
<script type="text/javascript">
var myRequest = {
  'tag': 'kahna',
  'rect': {'sw': {'lat': -30, 'lng': 10.5}, 'ne': {'lat': 50.5, 'lng': 30}}
};
  var myOptions = {
  'width': 300,
  'height': 200
};
var wapiblock = document.getElementById('wapiblock');
var photo_widget = new panoramio.PhotoWidget('wapiblock', myRequest, myOptions);
photo_widget.setPosition(0);
</script>
</div>

What is the difference between Collection and List in Java?

Collection is the root interface to the java Collections hierarchy. List is one sub interface which defines an ordered Collection, other sub interfaces are Queue which typically will store elements ready for processing (e.g. stack).

The following diagram demonstrates the relationship between the different java collection types:

java collections

How can I pass a list as a command-line argument with argparse?

I think the most elegant solution is to pass a lambda function to "type", as mentioned by Chepner. In addition to this, if you do not know beforehand what the delimiter of your list will be, you can also pass multiple delimiters to re.split:

# python3 test.py -l "abc xyz, 123"

import re
import argparse

parser = argparse.ArgumentParser(description='Process a list.')
parser.add_argument('-l', '--list',
                    type=lambda s: re.split(' |, ', s),
                    required=True,
                    help='comma or space delimited list of characters')

args = parser.parse_args()
print(args.list)


# Output: ['abc', 'xyz', '123']

Git: Find the most recent common ancestor of two branches

As noted in a prior answer, although git merge-base works,

$ git merge-base myfeature develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

If myfeature is the current branch, as is common, you can use --fork-point:

$ git merge-base --fork-point develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

This argument works only in sufficiently recent versions of git. Unfortunately it doesn't always work, however, and it is not clear why. Please refer to the limitations noted toward the end of this answer.


For full commit info, consider:

$ git log -1 $(git merge-base --fork-point develop) 

Open Sublime Text from Terminal in macOS

I'm on a mac and this worked for me:

open /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl

Is it possible to listen to a "style change" event?

you can try Jquery plugin , it trigger events when css is change and its easy to use

http://meetselva.github.io/#gist-section-attrchangeExtension
 $([selector]).attrchange({
  trackValues: true, 
  callback: function (e) {
    //console.log( '<p>Attribute <b>' + e.attributeName +'</b> changed from <b>' + e.oldValue +'</b> to <b>' + e.newValue +'</b></p>');
    //event.attributeName - Attribute Name
    //event.oldValue - Prev Value
    //event.newValue - New Value
  }
});

LEFT INNER JOIN vs. LEFT OUTER JOIN - Why does the OUTER take longer?

This is because the LEFT OUTER Join is doing more work than an INNER Join BEFORE sending the results back.

The Inner Join looks for all records where the ON statement is true (So when it creates a new table, it only puts in records that match the m.SubID = a.SubID). Then it compares those results to your WHERE statement (Your last modified time).

The Left Outer Join...Takes all of the records in your first table. If the ON statement is not true (m.SubID does not equal a.SubID), it simply NULLS the values in the second table's column for that recordset.

The reason you get the same number of results at the end is probably coincidence due to the WHERE clause that happens AFTER all of the copying of records.

Join (SQL) Wikipedia

C++ - Decimal to binary converting

Here is modern variant that can be used for ints of different sizes.

#include <type_traits>
#include <bitset>

template<typename T>
std::enable_if_t<std::is_integral_v<T>,std::string>
encode_binary(T i){
    return std::bitset<sizeof(T) * 8>(i).to_string();
}

User Authentication in ASP.NET Web API

I am working on a MVC5/Web API project and needed to be able to get authorization for the Web Api methods. When my index view is first loaded I make a call to the 'token' Web API method which I believe is created automatically.

The client side code (CoffeeScript) to get the token is:

getAuthenticationToken = (username, password) ->
    dataToSend = "username=" + username + "&password=" + password
    dataToSend += "&grant_type=password"
    $.post("/token", dataToSend).success saveAccessToken

If successful the following is called, which saves the authentication token locally:

saveAccessToken = (response) ->
    window.authenticationToken = response.access_token

Then if I need to make an Ajax call to a Web API method that has the [Authorize] tag I simply add the following header to my Ajax call:

{ "Authorization": "Bearer " + window.authenticationToken }

WiX tricks and tips

Modify the "Ready to install?" dialog (aka VerifyReadyDlg) to provide a summary of choices made.

It looks like this:
alt text http://i46.tinypic.com/s4th7t.jpg

Do this with a Javascript CustomAction:


Javascript code:

// http://msdn.microsoft.com/en-us/library/aa372516(VS.85).aspx
var MsiViewModify = 
    {
        Refresh          : 0,
        Insert           : 1,
        Update           : 2,
        Assign           : 3,
        Replace          : 4,
        Merge            : 5,
        Delete           : 6,
        InsertTemporary  : 7,   // cannot permanently modify the MSI during install
        Validate         : 8,
        ValidateNew      : 9,
        ValidateField    : 10,
        ValidateDelete   : 11
    };


// http://msdn.microsoft.com/en-us/library/sfw6660x(VS.85).aspx
var Buttons = 
    {
        OkOnly           : 0,
        OkCancel         : 1,
        AbortRetryIgnore : 2,
        YesNoCancel      : 3
    };

var Icons= 
    {
        Critical         : 16,
        Question         : 32,
        Exclamation      : 48,
        Information      : 64
    }

var MsgKind =
    {
        Error            : 0x01000000,
        Warning          : 0x02000000,
        User             : 0x03000000,
        Log              : 0x04000000
    };

// http://msdn.microsoft.com/en-us/library/aa371254(VS.85).aspx
var MsiActionStatus = 
    {
        None             : 0,
        Ok               : 1, // success
        Cancel           : 2,
        Abort            : 3,
        Retry            : 4, // aka suspend?
        Ignore           : 5  // skip remaining actions; this is not an error.
    };

function UpdateReadyDialog_CA(sitename)
{
    try 
    {
        // can retrieve properties from the install session like this:
        var selectedWebSiteId = Session.Property("MSI_PROPERTY_HERE");

        // can retrieve requested feature install state like this:
        var fInstallRequested   = Session.FeatureRequestState("F.FeatureName");

        var text1 = "This is line 1 of text in the VerifyReadyDlg";

        var text2 = "This is the second line of custom text";

        var controlView     = Session.Database.OpenView("SELECT * FROM Control");
        controlView.Execute();

        var rec             = Session.Installer.CreateRecord(12);
        rec.StringData(1)   = "VerifyReadyDlg";    // Dialog_
        rec.StringData(2)   = "CustomVerifyText1"; // Control - can be any name
        rec.StringData(3)   = "Text";              // Type
        rec.IntegerData(4)  = 25;                  // X
        rec.IntegerData(5)  = 60;                  // Y
        rec.IntegerData(6)  = 320;                 // Width
        rec.IntegerData(7)  = 85;                  // Height
        rec.IntegerData(8)  = 2;                   // Attributes
        rec.StringData(9)   = "";                  // Property
        rec.StringData(10)  = vText1;              // Text
        rec.StringData(11)  = "";                  // Control_Next
        rec.StringData(12)  = "";                  // Help
        controlView.Modify(MsiViewModify.InsertTemporary, rec);

        rec                 = Session.Installer.CreateRecord(12);
        rec.StringData(1)   = "VerifyReadyDlg";    // Dialog_
        rec.StringData(2)   = "CustomVerifyText2"; // Control - any unique name
        rec.StringData(3)   = "Text";              // Type
        rec.IntegerData(4)  = 25;                  // X
        rec.IntegerData(5)  = 160;                 // Y
        rec.IntegerData(6)  = 320;                 // Width
        rec.IntegerData(7)  = 65;                  // Height
        rec.IntegerData(8)  = 2;                   // Attributes
        rec.StringData(9)   = "";                  // Property
        rec.StringData(10)  = text2;               // Text
        rec.StringData(11)  = "";                  // Control_Next
        rec.StringData(12)  = "";                  // Help
        controlView.Modify(MsiViewModify.InsertTemporary, rec);

        controlView.Close();
    }
    catch (exc1)
    {
        Session.Property("CA_EXCEPTION") = exc1.message ;
        LogException("UpdatePropsWithSelectedWebSite", exc1);
        return MsiActionStatus.Abort;
    }
    return MsiActionStatus.Ok;
}


function LogException(loc, exc)
{
    var record = Session.Installer.CreateRecord(0);
    record.StringData(0) = "Exception {" + loc + "}: " + exc.number + " : " + exc.message;
    Session.Message(MsgKind.Error + Icons.Critical + Buttons.btnOkOnly, record);
}

Declare the Javascript CA:

<Fragment>
  <Binary Id="IisScript_CA" SourceFile="CustomActions.js" />

  <CustomAction Id="CA.UpdateReadyDialog"
              BinaryKey="IisScript_CA"
              JScriptCall="UpdateReadyDialog_CA"
              Execute="immediate"
              Return="check" />
</Fragment>

Attach the CA to a button. In this example, the CA is fired when Next is clicked from the CustomizeDlg:

<UI ...>
  <Publish Dialog="CustomizeDlg" Control="Next" Event="DoAction" 
           Value="CA.UpdateReadyDialog" Order="1"/>
</UI>

Related SO Question: How can I set, at runtime, the text to be displayed in VerifyReadyDlg?

Inserting a PDF file in LaTeX

Use the pdfpages package.

\usepackage{pdfpages}

To include all the pages in the PDF file:

\includepdf[pages=-]{myfile.pdf}

To include just the first page of a PDF:

\includepdf[pages={1}]{myfile.pdf}

Run texdoc pdfpages in a shell to see the complete manual for pdfpages.

syntax error: unexpected token <

This error can also arise from a JSON AJAX call to a PHP script that has an error in its code. Servers are often set up to return PHP error information formatted with html markup. This response is interpreted as invalid JSON, resulting in the "unexpected token <" AJAX error.

To view the PHP error using Chrome, go to the Network panel in the web inspector, click the PHP file listed on the left side, and click on the Response tab.

how to set the query timeout from SQL connection string

See:- ConnectionStrings content on this subject. There is no default command timeout property.

Pandas DataFrame: replace all values in a column, based on condition

for single condition, ie. ( 'employrate'] > 70 )

       country        employrate alcconsumption
0  Afghanistan  55.7000007629394            .03
1      Albania  51.4000015258789           7.29
2      Algeria              50.5            .69
3      Andorra                            10.17
4       Angola  75.6999969482422           5.57

use this:

df.loc[df['employrate'] > 70, 'employrate'] = 7

       country  employrate alcconsumption
0  Afghanistan   55.700001            .03
1      Albania   51.400002           7.29
2      Algeria   50.500000            .69
3      Andorra         nan          10.17
4       Angola    7.000000           5.57

therefore syntax here is:

df.loc[<mask>(here mask is generating the labels to index) , <optional column(s)> ]

For multiple conditions ie. (df['employrate'] <=55) & (df['employrate'] > 50)

use this:

df['employrate'] = np.where(
   (df['employrate'] <=55) & (df['employrate'] > 50) , 11, df['employrate']
   )

out[108]:
       country  employrate alcconsumption
0  Afghanistan   55.700001            .03
1      Albania   11.000000           7.29
2      Algeria   11.000000            .69
3      Andorra         nan          10.17
4       Angola   75.699997           5.57

therefore syntax here is:

 df['<column_name>'] = np.where((<filter 1> ) & (<filter 2>) , <new value>, df['column_name'])

Moving from JDK 1.7 to JDK 1.8 on Ubuntu

This is what I do on debian - I suspect it should work on ubuntu (amend the version as required + adapt the folder where you want to copy the JDK files as you wish, I'm using /opt/jdk):

wget --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u71-b15/jdk-8u71-linux-x64.tar.gz
sudo mkdir /opt/jdk
sudo tar -zxf jdk-8u71-linux-x64.tar.gz -C /opt/jdk/
rm jdk-8u71-linux-x64.tar.gz

Then update-alternatives:

sudo update-alternatives --install /usr/bin/java java /opt/jdk/jdk1.8.0_71/bin/java 1
sudo update-alternatives --install /usr/bin/javac javac /opt/jdk/jdk1.8.0_71/bin/javac 1

Select the number corresponding to the /opt/jdk/jdk1.8.0_71/bin/java when running the following commands:

sudo update-alternatives --config java
sudo update-alternatives --config javac

Finally, verify that the correct version is selected:

java -version
javac -version

How to make a checkbox checked with jQuery?

I think you should use prop(), if you are using jQuery 1.6 onwards.

To check it you should do:

$('#test').prop('checked', true);

to uncheck it:

$('#test').prop('checked', false);

How to customize listview using baseadapter

Create your own BaseAdapter class and use it as following.

 public class NotificationScreen extends Activity
{

@Override
protected void onCreate_Impl(Bundle savedInstanceState)
{
    setContentView(R.layout.notification_screen);

    ListView notificationList = (ListView) findViewById(R.id.notification_list);
    NotiFicationListAdapter notiFicationListAdapter = new NotiFicationListAdapter();
    notificationList.setAdapter(notiFicationListAdapter);

    homeButton = (Button) findViewById(R.id.home_button);

}

}

Make your own BaseAdapter class and its separate xml file.

public class NotiFicationListAdapter  extends BaseAdapter
{
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater=null;


public NotiFicationListAdapter(ArrayList data)
{
this.data=data;        
    inflater =(LayoutInflater)baseActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}



public int getCount() 
{
 return data.size();
}



public Object getItem(int position) 
{
 return position;
}



public long getItemId(int position) 
{
    return position;
}



public View getView(int position, View convertView, ViewGroup parent) 
{
View vi=convertView;
    if(convertView==null)

    vi = inflater.inflate(R.layout.notification_list_item, null);

    ImageView compleatImageView=(ImageView)vi.findViewById(R.id.complet_image);
    TextView name = (TextView)vi.findViewById(R.id.game_name); // name
    TextView email_id = (TextView)vi.findViewById(R.id.e_mail_id); // email ID
    TextView notification_message = (TextView)vi.findViewById(R.id.notification_message); // notification message



    compleatImageView.setBackgroundResource(R.id.address_book);
    name.setText(data.getIndex(position));
    email_id.setText(data.getIndex(position));
    notification_message.setTextdata.getIndex(position));

    return vi;
}

  }

BaseAdapter xml file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/inner_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_weight="4"
android:background="@drawable/list_view_frame"
android:gravity="center_vertical"
android:padding="5dp" >

<TextView
    android:id="@+id/game_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Game name"
    android:textColor="#FFFFFF"
    android:textSize="15dip"
    android:textStyle="bold"
    android:typeface="sans" />

<TextView
    android:id="@+id/e_mail_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/game_name"
    android:layout_marginTop="1dip"
    android:text="E-Mail Id"
    android:textColor="#FFFFFF"
    android:textSize="10dip" />

<TextView
    android:id="@+id/notification_message"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/game_name"
    android:layout_toRightOf="@id/e_mail_id"
    android:paddingLeft="5dp"
    android:text="Notification message"
    android:textColor="#FFFFFF"
    android:textSize="10dip" />



<ImageView
    android:id="@+id/complet_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_marginBottom="30dp"
    android:layout_marginRight="10dp"
    android:src="@drawable/complete_tag"
    android:visibility="invisible" />

</RelativeLayout>

Change it accordingly and use.

jQuery AJAX file upload PHP

Use pure js

_x000D_
_x000D_
async function saveFile() _x000D_
{_x000D_
    let formData = new FormData();           _x000D_
    formData.append("file", sortpicture.files[0]);_x000D_
    await fetch('/uploads', {method: "POST", body: formData});    _x000D_
    alert('works');_x000D_
}
_x000D_
<input id="sortpicture" type="file" name="sortpic" />_x000D_
<button id="upload" onclick="saveFile()">Upload</button>_x000D_
<br>Before click upload look on chrome>console>network (in this snipped we will see 404)
_x000D_
_x000D_
_x000D_

The filename is automatically included to request and server can read it, the 'content-type' is automatically set to 'multipart/form-data'. Here is more developed example with error handling and additional json sending

_x000D_
_x000D_
async function saveFile(inp) _x000D_
{_x000D_
    let user = { name:'john', age:34 };_x000D_
    let formData = new FormData();_x000D_
    let photo = inp.files[0];      _x000D_
         _x000D_
    formData.append("photo", photo);_x000D_
    formData.append("user", JSON.stringify(user));  _x000D_
    _x000D_
    try {_x000D_
       let r = await fetch('/upload/image', {method: "POST", body: formData}); _x000D_
       console.log('HTTP response code:',r.status); _x000D_
       alert('success');_x000D_
    } catch(e) {_x000D_
       console.log('Huston we have problem...:', e);_x000D_
    }_x000D_
    _x000D_
}
_x000D_
<input type="file" onchange="saveFile(this)" >_x000D_
<br><br>_x000D_
Before selecting the file Open chrome console > network tab to see the request details._x000D_
<br><br>_x000D_
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
_x000D_
_x000D_
_x000D_

Ship an application with a database

From what I've seen you should be be shipping a database that already has the tables setup and data. However if you want (and depending on the type of application you have) you can allow "upgrade database option". Then what you do is download the latest sqlite version, get the latest Insert/Create statements of a textfile hosted online, execute the statements and do a data transfer from the old db to the new one.

Different color for each bar in a bar chart; ChartJS

here is how I dealed: I pushed an array "colors", with same number of entries than number of datas. For this I added a function "getRandomColor" at the end of the script. Hope it helps...

for (var i in arr) {
    customers.push(arr[i].customer);
    nb_cases.push(arr[i].nb_cases);
    colors.push(getRandomColor());
}

window.onload = function() {
    var config = {
        type: 'pie',
        data: {
            labels: customers,
            datasets: [{
                label: "Nomber of cases by customers",
                data: nb_cases,
                fill: true,
                backgroundColor: colors 
            }]
        },
        options: {
            responsive: true,
            title: {
                display: true,
                text: "Cases by customers"
            },
        }
    };

    var ctx = document.getElementById("canvas").getContext("2d");
    window.myLine = new Chart(ctx, config);
};

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

What is the difference between properties and attributes in HTML?

The answers already explain how attributes and properties are handled differently, but I really would like to point out how totally insane this is. Even if it is to some extent the spec.

It is crazy, to have some of the attributes (e.g. id, class, foo, bar) to retain only one kind of value in the DOM, while some attributes (e.g. checked, selected) to retain two values; that is, the value "when it was loaded" and the value of the "dynamic state". (Isn't the DOM supposed to be to represent the state of the document to its full extent?)

It is absolutely essential, that two input fields, e.g. a text and a checkbox behave the very same way. If the text input field does not retain a separate "when it was loaded" value and the "current, dynamic" value, why does the checkbox? If the checkbox does have two values for the checked attribute, why does it not have two for its class and id attributes? If you expect to change the value of a text *input* field, and you expect the DOM (i.e. the "serialized representation") to change, and reflect this change, why on earth would you not expect the same from an input field of type checkbox on the checked attribute?

The differentiation, of "it is a boolean attribute" just does not make any sense to me, or is, at least not a sufficient reason for this.

How to reload .bash_profile from the command line?

Simply type source ~/.bash_profile

Alternatively, if you like saving keystrokes you can type . ~/.bash_profile

Log4j, configuring a Web App to use a relative path

I've finally done it in this way.

Added a ServletContextListener that does the following:

public void contextInitialized(ServletContextEvent event) {
    ServletContext context = event.getServletContext();
    System.setProperty("rootPath", context.getRealPath("/"));
}

Then in the log4j.properties file:

log4j.appender.file.File=${rootPath}WEB-INF/logs/MyLog.log

By doing it in this way Log4j will write into the right folder as long as you don't use it before the "rootPath" system property has been set. This means that you cannot use it from the ServletContextListener itself but you should be able to use it from anywhere else in the app.

It should work on every web container and OS as it's not dependent on a container specific system property and it's not affected by OS specific path issues. Tested with Tomcat and Orion web containers and on Windows and Linux and it works fine so far.

What do you think?

How to use ConfigurationManager

I found some answers, but I don't know if it is the right way.This is my solution for now. Fortunatelly it didn´t broke my design mode.

    `
    /// <summary>
    /// set config, if key is not in file, create
    /// </summary>
    /// <param name="key">Nome do parâmetro</param>
    /// <param name="value">Valor do parâmetro</param>
    public static void SetConfig(string key, string value)
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = configFile.AppSettings.Settings;
        if (settings[key] == null)
        {
            settings.Add(key, value);
        }
        else
        {
            settings[key].Value = value;
        }
        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
    }

    /// <summary>
    /// Get key value, if not found, return null
    /// </summary>
    /// <param name="key"></param>
    /// <returns>null if key is not found, else string with value</returns>
    public static string GetConfig(string key)
    {
        return ConfigurationManager.AppSettings[key];
    }`

How can I multiply all items in a list together with Python?

'''the only simple method to understand the logic use for loop'''

Lap=[2,5,7,7,9] x=1 for i in Lap: x=i*x print(x)

C++, copy set to vector

You need to use a back_inserter:

std::copy(input.begin(), input.end(), std::back_inserter(output));

std::copy doesn't add elements to the container into which you are inserting: it can't; it only has an iterator into the container. Because of this, if you pass an output iterator directly to std::copy, you must make sure it points to a range that is at least large enough to hold the input range.

std::back_inserter creates an output iterator that calls push_back on a container for each element, so each element is inserted into the container. Alternatively, you could have created a sufficient number of elements in the std::vector to hold the range being copied:

std::vector<double> output(input.size());
std::copy(input.begin(), input.end(), output.begin());

Or, you could use the std::vector range constructor:

std::vector<double> output(input.begin(), input.end()); 

Export HTML page to PDF on user click using JavaScript

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

change it to:

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#cmd').click(function () {
        var doc = new jsPDF();
        doc.fromHTML(
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){ doc.save('sample-file.pdf'); }
        );

    });  
});

and it will work.

PHP header redirect 301 - what are the implications?

Just a tip: using http_response_code is much easier to remember than writing the full header:

http_response_code(301);
header('Location: /option-a'); 
exit;

Renaming column names of a DataFrame in Spark Scala

For those of you interested in PySpark version (actually it's same in Scala - see comment below) :

    merchants_df_renamed = merchants_df.toDF(
        'merchant_id', 'category', 'subcategory', 'merchant')

    merchants_df_renamed.printSchema()

Result:

root
|-- merchant_id: integer (nullable = true)
|-- category: string (nullable = true)
|-- subcategory: string (nullable = true)
|-- merchant: string (nullable = true)

How to redirect in a servlet filter?

In Filter the response is of ServletResponse rather than HttpServletResponse. Hence do the cast to HttpServletResponse.

HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.sendRedirect("/login.jsp");

If using a context path:

httpResponse.sendRedirect(req.getContextPath() + "/login.jsp");

Also don't forget to call return; at the end.

UNION with WHERE clause

You need to look at the explain plans, but unless there is an INDEX or PARTITION on COL_A, you are looking at a FULL TABLE SCAN on both tables.

With that in mind, your first example is throwing out some of the data as it does the FULL TABLE SCAN. That result is being sorted by the UNION, then duplicate data is dropped. This gives you your result set.

In the second example, you are pulling the full contents of both tables. That result is likely to be larger. So the UNION is sorting more data, then dropping the duplicate stuff. Then the filter is being applied to give you the result set you are after.

As a general rule, the earlier you filter away data, the smaller the data set, and the faster you will get your results. As always, your milage may vary.

JPA or JDBC, how are they different?

JDBC is the predecessor of JPA.

JDBC is a bridge between the Java world and the databases world. In JDBC you need to expose all dirty details needed for CRUD operations, such as table names, column names, while in JPA (which is using JDBC underneath), you also specify those details of database metadata, but with the use of Java annotations.

So JPA creates update queries for you and manages the entities that you looked up or created/updated (it does more as well).

If you want to do JPA without a Java EE container, then Spring and its libraries may be used with the very same Java annotations.

How does data binding work in AngularJS?

AngularJS handle data-binding mechanism with the help of three powerful functions : $watch(),$digest()and $apply(). Most of the time AngularJS will call the $scope.$watch() and $scope.$digest(), but in some cases you may have to call these functions manually to update with new values.

$watch() :-

This function is used to observe changes in a variable on the $scope. It accepts three parameters: expression, listener and equality object, where listener and equality object are optional parameters.

$digest() -

This function iterates through all the watches in the $scope object, and its child $scope objects
(if it has any). When $digest() iterates over the watches, it checks if the value of the expression has changed. If the value has changed, AngularJS calls the listener with new value and old value. The $digest() function is called whenever AngularJS thinks it is necessary. For example, after a button click, or after an AJAX call. You may have some cases where AngularJS does not call the $digest() function for you. In that case you have to call it yourself.

$apply() -

Angular do auto-magically updates only those model changes which are inside AngularJS context. When you do change in any model outside of the Angular context (like browser DOM events, setTimeout, XHR or third party libraries), then you need to inform Angular of the changes by calling $apply() manually. When the $apply() function call finishes AngularJS calls $digest() internally, so all data bindings are updated.

How to debug .htaccess RewriteRule not working

Enter some junk value into your .htaccess e.g. foo bar, sakjnaskljdnas any keyword not recognized by htaccess and visit your URL. If it is working, you should get a

500 Internal Server Error

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request....

I suggest you to put it soon after RewriteEngine on.


Since you are on your machine. I presume you have access to apache .conf file.

open the .conf file, and look for a line similar to:

LoadModule rewrite_module modules/mod_rewrite.so

If it is commented(#), uncomment and restart apache.


To log rewrite

RewriteEngine On
RewriteLog "/path/to/rewrite.log"
RewriteLogLevel 9

Put the above 3 lines in your virtualhost. restart the httpd.

RewriteLogLevel 9 Using a high value for Level will slow down your Apache server dramatically! Use the rewriting logfile at a Level greater than 2 only for debugging! Level 9 will log almost every rewritelog detail.


UPDATE

Things have changed in Apache 2.4:

FROM Upgrading to 2.4 from 2.2

The RewriteLog and RewriteLogLevel directives have been removed. This functionality is now provided by configuring the appropriate level of logging for the mod_rewrite module using the LogLevel directive. See also the mod_rewrite logging section.

For more on LogLevel, refer LogLevel Directive

you can accomplish

RewriteLog "/path/to/rewrite.log"

in this manner now

LogLevel debug rewrite_module:debug

Insert the same fixed value into multiple rows

UPDATE `table` SET table_column='test';

NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

Add the all tiles jars like(tiles-jsp,tiles-servlet,tiles-template,tiles-extras.tiles-core ) to your server lib folder and your application build path then it work if you using apache tailes with spring mvc application

"git rebase origin" vs."git rebase origin/master"

You can make a new file under [.git\refs\remotes\origin] with name "HEAD" and put content "ref: refs/remotes/origin/master" to it. This should solve your problem.

It seems that clone from an empty repos will lead to this. Maybe the empty repos do not have HEAD because no commit object exist.

You can use the

git log --remotes --branches --oneline --decorate

to see the difference between each repository, while the "problem" one do not have "origin/HEAD"

Edit: Give a way using command line
You can also use git command line to do this, they have the same result

git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/master

Laravel Eloquent limit and offset

Maybe this

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

ImportError: No module named 'selenium'

Even though the egg file may be present, that does not necessarily mean that it is installed. Check out this previous answer for some hint:

How to install Selenium WebDriver on Mac OS

window.onload vs document.onload

The general idea is that window.onload fires when the document's window is ready for presentation and document.onload fires when the DOM tree (built from the markup code within the document) is completed.

Ideally, subscribing to DOM-tree events, allows offscreen-manipulations through Javascript, incurring almost no CPU load. Contrarily, window.onload can take a while to fire, when multiple external resources have yet to be requested, parsed and loaded.

?Test scenario:

To observe the difference and how your browser of choice implements the aforementioned event handlers, simply insert the following code within your document's - <body>- tag.

<script language="javascript">
window.tdiff = []; fred = function(a,b){return a-b;};
window.document.onload = function(e){ 
    console.log("document.onload", e, Date.now() ,window.tdiff,  
    (window.tdiff[0] = Date.now()) && window.tdiff.reduce(fred) ); 
}
window.onload = function(e){ 
    console.log("window.onload", e, Date.now() ,window.tdiff, 
    (window.tdiff[1] = Date.now()) && window.tdiff.reduce(fred) ); 
}
</script>

?Result:

Here is the resulting behavior, observable for Chrome v20 (and probably most current browsers).

  • No document.onload event.
  • onload fires twice when declared inside the <body>, once when declared inside the <head> (where the event then acts as document.onload ).
  • counting and acting dependent on the state of the counter allows to emulate both event behaviors.
  • Alternatively declare the window.onload event handler within the confines of the HTML-<head> element.

?Example Project:

The code above is taken from this project's codebase (index.html and keyboarder.js).


For a list of event handlers of the window object, please refer to the MDN documentation.

Is there a combination of "LIKE" and "IN" in SQL?

For Sql Server you can resort to Dynamic SQL.

Most of the time in such situations you have the parameter of IN clause based on some data from database.

The example below is a little "forced", but this can match various real cases found in legacy databases.

Suppose you have table Persons where person names are stored in a single field PersonName as FirstName + ' ' + LastName. You need to select all persons from a list of first names, stored in field NameToSelect in table NamesToSelect, plus some additional criteria (like filtered on gender, birth date, etc)

You can do it as follows

-- @gender is nchar(1), @birthDate is date 

declare 
  @sql nvarchar(MAX),
  @subWhere nvarchar(MAX)
  @params nvarchar(MAX)

-- prepare the where sub-clause to cover LIKE IN (...)
-- it will actually generate where clause PersonName Like 'param1%' or PersonName Like 'param2%' or ...   
set @subWhere = STUFF(
  (
    SELECT ' OR PersonName like ''' + [NameToSelect] + '%''' 
        FROM [NamesToSelect] t FOR XML PATH('')
  ), 1, 4, '')

-- create the dynamic SQL
set @sql ='select 
      PersonName
      ,Gender
      ,BirstDate    -- and other field here         
  from [Persons]
  where 
    Gender = @gender
    AND BirthDate = @birthDate
    AND (' + @subWhere + ')'

set @params = ' @gender nchar(1),
  @birthDate Date'     

EXECUTE sp_executesql @sql, @params,    
  @gender,  
  @birthDate

Best practices for API versioning?

I agree that versioning the resource representation better follows the REST approach...but, one big problem with custom MIME types (or MIME types that append a version parameter) is the poor support to write to Accept and Content-Type headers in HTML and JavaScript.

For example, it is not possible IMO to POST with the following headers in HTML5 forms, in order to create a resource:

Accept: application/vnd.company.myapp-v3+json
Content-Type: application/vnd.company.myapp-v3+json 

This is because the HTML5 enctype attribute is an enumeration, therefore anything other than the usual application/x-www-formurlencoded, multipart/form-data and text/plain are invalid.

...nor am I sure it is supported across all browsers in HTML4 (which has a more lax encytpe attribute, but would be a browser implementation issue as to whether the MIME type was forwarded)

Because of this I now feel the most appropriate way to version is via the URI, but I accept that it is not the 'correct' way.

JPA: difference between @JoinColumn and @PrimaryKeyJoinColumn?

I normally differentiate these two via this diagram:

Use PrimaryKeyJoinColumn

enter image description here

Use JoinColumn

enter image description here

How can I export a GridView.DataSource to a datatable or dataset?

Personally I would go with:

DataTable tbl = Gridview1.DataSource as DataTable;

This would allow you to test for null as this results in either DataTable object or null. Casting it as a DataTable using (DataTable)Gridview1.DataSource would cause a crashing error in case the DataSource is actually a DataSet or even some kind of collection.

Supporting Documentation: MSDN Documentation on "as"

Remove characters before character "."

string input = "America.USA"
string output = input.Substring(input.IndexOf('.') + 1);

How to show all rows by default in JQuery DataTable

Use:

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

The option you should use is iDisplayLength:

$('#adminProducts').dataTable({
  'iDisplayLength': 100
});

$('#table').DataTable({
   "lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});

It will Load by default all entries.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

If you want to load by default 25 not all do this.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
});

How to round the corners of a button

Swift 4 Update

I also tried many options still i wasn't able to get my UIButton round cornered. I added the corner radius code inside the viewDidLayoutSubviews() Solved My issue.

func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        anyButton.layer.cornerRadius = anyButton.frame.height / 2
    }

Also we can adjust the cornerRadius as follows

func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        anyButton.layer.cornerRadius = 10 //Any suitable number as you prefer can be applied 
    }

ADB not recognising Nexus 4 under Windows 7

For me, it was Nexus 4 and Windows 7. I reinstalled the drivers, changed to PTP - basically went through everything.

Clicking the tab that said MainActivity.java rather than activity_main.xml in Eclipse fixed it for me.

When creating a service with sc.exe how to pass in context parameters?

This command works:

sc create startSvn binPath= "\"C:\Subversion\bin\svnserve.exe\" --service -r \"C:\SVN_Repository\"" displayname= "MyServer" depend= tcpip start= auto

How to tell if node.js is installed or not

Open the command prompt in Windows or terminal in Linux and Mac.Type

node -v

If node is install it will show its version.For eg.,

v6.9.5

Else download it from nodejs.org

Asp.net MVC ModelState.Clear

Well lots of us seem to have been bitten by this, and although the reason this happens makes sense I needed a way to ensure that the value on my Model was shown, and not ModelState.

Some have suggested ModelState.Remove(string key), but it's not obvious what key should be, especially for nested models. Here are a couple methods I came up with to assist with this.

The RemoveStateFor method will take a ModelStateDictionary, a Model, and an expression for the desired property, and remove it. HiddenForModel can be used in your View to create a hidden input field using only the value from the Model, by first removing its ModelState entry. (This could easily be expanded for the other helper extension methods).

/// <summary>
/// Returns a hidden input field for the specified property. The corresponding value will first be removed from
/// the ModelState to ensure that the current Model value is shown.
/// </summary>
public static MvcHtmlString HiddenForModel<TModel, TProperty>(this HtmlHelper<TModel> helper,
    Expression<Func<TModel, TProperty>> expression)
{
    RemoveStateFor(helper.ViewData.ModelState, helper.ViewData.Model, expression);
    return helper.HiddenFor(expression);
}

/// <summary>
/// Removes the ModelState entry corresponding to the specified property on the model. Call this when changing
/// Model values on the server after a postback, to prevent ModelState entries from taking precedence.
/// </summary>
public static void RemoveStateFor<TModel, TProperty>(this ModelStateDictionary modelState, TModel model,
    Expression<Func<TModel, TProperty>> expression)
{
    var key = ExpressionHelper.GetExpressionText(expression);

    modelState.Remove(key);
}

Call from a controller like this:

ModelState.RemoveStateFor(model, m => m.MySubProperty.MySubValue);

or from a view like this:

@Html.HiddenForModel(m => m.MySubProperty.MySubValue)

It uses System.Web.Mvc.ExpressionHelper to get the name of the ModelState property.

How to get an Instagram Access Token

Almost all of the replies that people have posted so far only cover how to handle access tokens on the front end, following Instagram's client-side "implicit authentication" procedure. This method is less secure and unrecommended according to Instagram's API docs.

Assuming you are using a server, the Instagram docs sort of fail in providing a clear answer about exchanging a code for a token, as they only give an example of a cURL request. Essentially you have to make a POST request to their server with the provided code and all of your app's information, and they will return a user object including user information and the token.

I don't know what language you are writing in, but I solved this in Node.js with the request npm module which you can find here.

I parsed through the url and used this information to send the post request

var code = req.url.split('code=')[1];

request.post(
  { form: { client_id: configAuth.instagramAuth.clientID,
            client_secret: configAuth.instagramAuth.clientSecret,
            grant_type: 'authorization_code',
            redirect_uri: configAuth.instagramAuth.callbackURL,
            code: code
          },
    url: 'https://api.instagram.com/oauth/access_token'
  },
  function (err, response, body) {
    if (err) {
      console.log("error in Post", err)
    }else{
      console.log(JSON.parse(body))
    }
  }
);

Of course replace the configAuth stuff with your own information. You probably aren't using Node.js, but hopefully this solution will help you translate your own solution into whatever language you are using it in.

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

You probably use this in your project:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

in which case you'll have to also add:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

and the magic happens :)

PS: that's because Spring will use by default web-MVC instead of web-flux when both are available

Unable to resolve host "<insert URL here>" No address associated with hostname

Are you able to reach that url from within the built-in browser?

If not, it means that your network setup is not correct. If you are in the emulator, you may have a look at the networking section of the docs.

If you are on OS/X, the emulator is using "the first" interface, en0 even if you are on wireless (en1), as en0 without a cable is still marked as up. You can issue ifconfig en0 down and restart the emulator. I think I have read about similar behavior on Windows.

If you are on Wifi/3G, call your network provider for the correct DNS settings.

android View not attached to window manager

when you declare activity in the manifest you need android:configChanges="orientation"

example:

<activity android:theme="@android:style/Theme.Light.NoTitleBar" android:configChanges="orientation"  android:label="traducción" android:name=".PantallaTraductorAppActivity"></activity>

Concatenating null strings in Java

This is behavior specified in the Java API's String.valueOf(Object) method. When you do concatenation, valueOf is used to get the String representation. There is a special case if the Object is null, in which case the string "null" is used.

public static String valueOf(Object obj)

Returns the string representation of the Object argument.

Parameters: obj - an Object.

Returns:

if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

Visual Studio: ContextSwitchDeadlock

In Visual Studio 2017 Spanish version.

"Depurar" -> "Ventanas" -> "Configuración de Excepciones"

and search "ContextSwitchDeadlock". Then, uncheck it. Or shortcut

Ctrl+D,E

Best.

Running Node.js in apache?

You can always do something shell-scripty like:

#!/usr/bin/node

var header = "Content-type: text/plain\n";
var hi = "Hello World from nodetest!";
console.log(header);
console.log(hi);

exit;

Angular 2: How to write a for loop, not a foreach loop

You could dynamically generate an array of however time you wanted to render <li>Something</li>, and then do ngFor over that collection. Also you could take use of index of current element too.

Markup

<ul>
   <li *ngFor="let item of createRange(5); let currentElementIndex=index+1">
      {{currentElementIndex}} Something
   </li>
</ul>

Code

createRange(number){
  var items: number[] = [];
  for(var i = 1; i <= number; i++){
     items.push(i);
  }
  return items;
}

Demo Here

Under the hood angular de-sugared this *ngFor syntax to ng-template version.

<ul>
    <ng-template ngFor let-item [ngForOf]="createRange(5)" let-currentElementIndex="(index + 1)" [ngForTrackBy]="trackByFn">
      {{currentElementIndex}} Something
    </ng-template>
</ul>

Temporarily disable all foreign key constraints

Disable all table constraints

ALTER TABLE TableName NOCHECK CONSTRAINT ConstraintName

-- Enable all table constraints

ALTER TABLE TableName CHECK CONSTRAINT ConstraintName

Difference between PACKETS and FRAMES

Consider TCP over ATM. ATM uses 48 byte frames, but clearly TCP packets can be bigger than that. A frame is the chunk of data sent as a unit over the data link (Ethernet, ATM). A packet is the chunk of data sent as a unit over the layer above it (IP). If the data link is made specifically for IP, as Ethernet and WiFi are, these will be the same size and packets will correspond to frames.

How to prevent user from typing in text field without disabling the field?

Markup

<asp:TextBox ID="txtDateOfBirth" runat="server" onkeydown="javascript:preventInput(event);" onpaste="return false;"
                                TabIndex="1">

Script

function preventInput(evnt) {
//Checked In IE9,Chrome,FireFox
if (evnt.which != 9) evnt.preventDefault();}

Status bar and navigation bar appear over my view's bounds in iOS 7

The simplest trick is to open the NIB file and do these two simple steps:

  1. Just toggle that and set it to the one you prefer:

Enter image description here

  1. Select those UIView's/UIIMageView's/... that you want to be moved down. In my case only the logo was overlapped an I've set the delta to +15; (OR -15 if you chose iOS 7 in step 1)

Enter image description here

And the result:

Before After

How to use the PRINT statement to track execution as stored procedure is running?

SQL Server returns messages after a batch of statements has been executed. Normally, you'd use SQL GO to indicate the end of a batch and to retrieve the results:

PRINT '1'
GO

WAITFOR DELAY '00:00:05'

PRINT '2'
GO

WAITFOR DELAY '00:00:05'

PRINT '3'
GO

In this case, however, the print statement you want returned immediately is in the middle of a loop, so the print statements cannot be in their own batch. The only command I know of that will return in the middle of a batch is RAISERROR (...) WITH NOWAIT, which gbn has provided as an answer as I type this.

How to remove symbols from a string with Python?

I often just open the console and look for the solution in the objects methods. Quite often it's already there:

>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello   s'

Short answer: Use string.replace().

JavaScript data grid for millions of rows

dojox.grid.DataGrid offers a JS abstraction for data so you can hook it up to various backends with provided dojo.data stores or write your own. You'll obviously need one that supports random access for this many records. DataGrid also provides full accessibility.

Edit so here's a link to Matthew Russell's article that should provide the example you need, viewing millions of records with dojox.grid. Note that it uses the old version of the grid, but the concepts are the same, there were just some incompatible API improvements.

Oh, and it's totally free open source.

Scp command syntax for copying a folder from local machine to a remote server

scp -r C:/site user@server_ip:path

path is the place, where site will be copied into the remote server


EDIT: As I said in my comment, try pscp, as you want to use scp using PuTTY.

The other option is WinSCP

Remove object from a list of objects in python

In python there are no arrays, lists are used instead. There are various ways to delete an object from a list:

my_list = [1,2,4,6,7]

del my_list[1] # Removes index 1 from the list
print my_list # [1,4,6,7]
my_list.remove(4) # Removes the integer 4 from the list, not the index 4
print my_list # [1,6,7]
my_list.pop(2) # Removes index 2 from the list

In your case the appropriate method to use is pop, because it takes the index to be removed:

x = object()
y = object()
array = [x, y]
array.pop(0)
# Using the del statement
del array[0]

Javascript / Chrome - How to copy an object from the webkit inspector as code

Right click on data which you want to store

  • Firstly, Right click on data which you want to store -> select "Store as global variable" And the new temp variable appear like bellow: (temp3 variable): New temp variable appear in console
  • Second use command copy(temp_variable_name) like picture: enter image description here After that, you can paste data to anywhere you want. hope useful/

get enum name from enum value

Say we have:

public enum MyEnum {
  Test1, Test2, Test3
}

To get the name of a enum variable use name():

MyEnum e = MyEnum.Test1;
String name = e.name(); // Returns "Test1"

To get the enum from a (string) name, use valueOf():

String name = "Test1";
MyEnum e = Enum.valueOf(MyEnum.class, name);

If you require integer values to match enum fields, extend the enum class:

public enum MyEnum {
  Test1(1), Test2(2), Test3(3);

  public final int value;

  MyEnum(final int value) {
     this.value = value;
  }
}

Now you can use:

MyEnum e = MyEnum.Test1;
int value = e.value; // = 1

And lookup the enum using the integer value:

MyEnum getValue(int value) {
  for(MyEnum e: MyEunm.values()) {
    if(e.value == value) {
      return e;
    }
  }
  return null;// not found
}

What is a "thread" (really)?

A thread is a set of (CPU)instructions which can be executed.

But in order to better understand the thread we have to have some knowledge about how the CPU and RAM works.

A computer follows instructions and manipulates data. RAM is the place where those instructions and data on which the CPU will operate on, are saved. Within the CPU some memory cells called registers exist. Those registers contain numbers on which the CPU performs simple mathematical operations. An example can be the following: “Add the number in register #3 to the number in register #1.”.

The collection of all operations a CPU can do is called instruction set. Each operation in the instruction set is assigned a number, so computer code is essentially a sequence of numbers representing CPU operations. These operations are stored as numbers in the RAM.

The CPU works in a never-ending loop, always fetching and executing an instruction from memory. At the core of this cycle is the PC register, or Program Counter. It's a special register that stores the memory address of the next instruction to be executed.

The CPU will:  

  1. Fetch the instruction at the memory address given by the PC,
  2. Increment the PC by 1,
  3. Execute the instruction,
  4. Go back to step 1.

The CPU can be instructed to write a new value to the PC, causing the execution to branch, or "jump" to somewhere else in the memory. And this branching can be conditional. For instance, a CPU instruction could say: "set PC to address #200 if register #1 equals zero". This allows computers to execute stuff like this:

if  x = 0
    compute_this()
else
    compute_that()

Resources taken from Computer Science Distilled were used.

Convert NVARCHAR to DATETIME in SQL Server 2008

As your data is nvarchar there is no guarantee it will convert to datetime (as it may hold invalid date/time information) - so a way to handle this is to use ISDATE which I would use within a cross apply. (Cross apply results are reusable hence making is easier for the output formats.)

|                     YOUR_DT |             SQL2008 |
|-----------------------------|---------------------|
|         2013-08-29 13:55:48 | 29-08-2013 13:55:48 |
|    2013-08-29 13:55:48 blah |              (null) |
| 2013-08-29 13:55:48 rubbish |              (null) |

SELECT
  [Your_Dt]
, convert(varchar, ca1.dt_converted ,105) + ' ' + convert(varchar, ca1.dt_converted ,8) AS sql2008
FROM your_table
CROSS apply ( SELECT CASE WHEN isdate([Your_Dt]) = 1
                        THEN convert(datetime,[Your_Dt])
                        ELSE NULL
                     END
            ) AS ca1 (dt_converted)
;

Notes:

You could also introduce left([Your_Dt],19) to only get a string like '2013-08-29 13:55:48' from '2013-08-29 13:55:48 rubbish'

For that specific output I think you will need 2 sql 2008 date styles (105 & 8) sql2012 added for comparison

declare @your_dt as datetime2
set @your_dt = '2013-08-29 13:55:48'

select
  FORMAT(@your_dt, 'dd-MM-yyyy H:m:s') as sql2012
, convert(varchar, @your_dt ,105) + ' ' + convert(varchar, @your_dt ,8) as sql2008

|             SQL2012 |             SQL2008 |
|---------------------|---------------------|
| 29-08-2013 13:55:48 | 29-08-2013 13:55:48 | 

select dept names who have more than 2 employees whose salary is greater than 1000

SELECT DEPTNAME
FROM(SELECT D.DEPTNAME,COUNT(EMPID) AS TOTEMP
     FROM DEPT AS D,EMPLOYEE AS E
     WHERE D.DEPTID=E.DEPTID AND SALARY>1000
     GROUP BY D.DEPTID
     )
WHERE TOTEMP>2;

PHP 5.4 Call-time pass-by-reference - Easy fix available?

You should be denoting the call by reference in the function definition, not the actual call. Since PHP started showing the deprecation errors in version 5.3, I would say it would be a good idea to rewrite the code.

From the documentation:

There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);.

For example, instead of using:

// Wrong way!
myFunc(&$arg);               # Deprecated pass-by-reference argument
function myFunc($arg) { }

Use:

// Right way!
myFunc($var);                # pass-by-value argument
function myFunc(&$arg) { }

How to install "make" in ubuntu?

I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.

To answer the question in the header: To install make in ubuntu you have to install build-essentials

sudo apt-get install build-essential

How to match letters only using java regex, matches method?

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.*;

/* Write an application that prompts the user for a String that contains at least
 * five letters and at least five digits. Continuously re-prompt the user until a
 * valid String is entered. Display a message indicating whether the user was
 * successful or did not enter enough digits, letters, or both.
 */
public class FiveLettersAndDigits {

  private static String readIn() { // read input from stdin
    StringBuilder sb = new StringBuilder();
    int c = 0;
    try { // do not use try-with-resources. We don't want to close the stdin stream
      BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
      while ((c = reader.read()) != 0) { // read all characters until null
        // We don't want new lines, although we must consume them.
        if (c != 13 && c != 10) {
          sb.append((char) c);
        } else {
          break; // break on new line (or else the loop won't terminate)
        }
      }
      // reader.readLine(); // get the trailing new line
    } catch (IOException ex) {
      System.err.println("Failed to read user input!");
      ex.printStackTrace(System.err);
    }

    return sb.toString().trim();
  }

  /**
   * Check the given input against a pattern
   *
   * @return the number of matches
   */
  private static int getitemCount(String input, String pattern) {
    int count = 0;

    try {
      Pattern p = Pattern.compile(pattern);
      Matcher m = p.matcher(input);
      while (m.find()) { // count the number of times the pattern matches
        count++;
      }
    } catch (PatternSyntaxException ex) {
      System.err.println("Failed to test input String \"" + input + "\" for matches to pattern \"" + pattern + "\"!");
      ex.printStackTrace(System.err);
    }

    return count;
  }

  private static String reprompt() {
    System.out.print("Entered input is invalid! Please enter five letters and five digits in any order: ");

    String in = readIn();

    return in;
  }

  public static void main(String[] args) {
    int letters = 0, digits = 0;
    String in = null;
    System.out.print("Please enter five letters and five digits in any order: ");
    in = readIn();
    while (letters < 5 || digits < 5) { // will keep occuring until the user enters sufficient input
      if (null != in && in.length() > 9) { // must be at least 10 chars long in order to contain both
        // count the letters and numbers. If there are enough, this loop won't happen again.
        letters = getitemCount(in, "[A-Za-z]");
        digits = getitemCount(in, "[0-9]");

        if (letters < 5 || digits < 5) {
          in = reprompt(); // reset in case we need to go around again.
        }
      } else {
        in = reprompt();
      }
    }
  }

}

How do I declare class-level properties in Objective-C?

Properties have values only in objects, not classes.

If you need to store something for all objects of a class, you have to use a global variable. You can hide it by declaring it static in the implementation file.

You may also consider using specific relations between your objects: you attribute a role of master to a specific object of your class and link others objects to this master. The master will hold the dictionary as a simple property. I think of a tree like the one used for the view hierarchy in Cocoa applications.

Another option is to create an object of a dedicated class that is composed of both your 'class' dictionary and a set of all the objects related to this dictionary. This is something like NSAutoreleasePool in Cocoa.

How do I pass variables and data from PHP to JavaScript?

There are actually several approaches to do this. Some require more overhead than others, and some are considered better than others.

In no particular order:

  1. Use AJAX to get the data you need from the server.
  2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.
  3. Echo the data directly to JavaScript.

In this post, we'll examine each of the above methods, and see the pros and cons of each, as well as how to implement them.

1. Use AJAX to get the data you need from the server

This method is considered the best, because your server side and client side scripts are completely separate.

Pros

  • Better separation between layers - If tomorrow you stop using PHP, and want to move to a servlet, a REST API, or some other service, you don't have to change much of the JavaScript code.
  • More readable - JavaScript is JavaScript, PHP is PHP. Without mixing the two, you get more readable code on both languages.
  • Allows for asynchronous data transfer - Getting the information from PHP might be time/resources expensive. Sometimes you just don't want to wait for the information, load the page, and have the information reach whenever.
  • Data is not directly found on the markup - This means that your markup is kept clean of any additional data, and only JavaScript sees it.

Cons

  • Latency - AJAX creates an HTTP request, and HTTP requests are carried over network and have network latencies.
  • State - Data fetched via a separate HTTP request won't include any information from the HTTP request that fetched the HTML document. You may need this information (e.g., if the HTML document is generated in response to a form submission) and, if you do, will have to transfer it across somehow. If you have ruled out embedding the data in the page (which you have if you are using this technique) then that limits you to cookies/sessions which may be subject to race conditions.

Implementation Example

With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:

get-data.php

/* Do some operation here, like talk to the database, the file-session
 * The world beyond, limbo, the city of shimmers, and Canada.
 *
 * AJAX generally uses strings, but you can output JSON, HTML and XML as well.
 * It all depends on the Content-type header that you send with your AJAX
 * request. */

echo json_encode(42); // In the end, you need to echo the result.
                      // All data should be json_encode()d.

                      // You can json_encode() any value in PHP, arrays, strings,
                      //even objects.

index.php (or whatever the actual page is named like)

<!-- snip -->
<script>
    function reqListener () {
      console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest(); // New request object
    oReq.onload = function() {
        // This is where you handle what to do with the response.
        // The actual data is found on this.responseText
        alert(this.responseText); // Will alert: 42
    };
    oReq.open("get", "get-data.php", true);
    //                               ^ Don't block the rest of the execution.
    //                                 Don't wait until the request finishes to
    //                                 continue.
    oReq.send();
</script>
<!-- snip -->

The above combination of the two files will alert 42 when the file finishes loading.

Some more reading material

2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM

This method is less preferable to AJAX, but it still has its advantages. It's still relatively separated between PHP and JavaScript in a sense that there is no PHP directly in the JavaScript.

Pros

  • Fast - DOM operations are often quick, and you can store and access a lot of data relatively quickly.

Cons

  • Potentially Unsemantic Markup - Usually, what happens is that you use some sort of <input type=hidden> to store the information, because it's easier to get the information out of inputNode.value, but doing so means that you have a meaningless element in your HTML. HTML has the <meta> element for data about the document, and HTML 5 introduces data-* attributes for data specifically for reading with JavaScript that can be associated with particular elements.
  • Dirties up the Source - Data that PHP generates is outputted directly to the HTML source, meaning that you get a bigger and less focused HTML source.
  • Harder to get structured data - Structured data will have to be valid HTML, otherwise you'll have to escape and convert strings yourself.
  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.

Implementation Example

With this, the idea is to create some sort of element which will not be displayed to the user, but is visible to JavaScript.

index.php

<!-- snip -->
<div id="dom-target" style="display: none;">
    <?php
        $output = "42"; // Again, do some operation, get the output.
        echo htmlspecialchars($output); /* You have to escape because the result
                                           will not be valid HTML otherwise. */
    ?>
</div>
<script>
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
</script>
<!-- snip -->

3. Echo the data directly to JavaScript

This is probably the easiest to understand.

Pros

  • Very easily implemented - It takes very little to implement this, and understand.
  • Does not dirty source - Variables are outputted directly to JavaScript, so the DOM is not affected.

Cons

  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.

Implementation Example

Implementation is relatively straightforward:

<!-- snip -->
<script>
    var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; // Don't forget the extra semicolon!
</script>
<!-- snip -->

Good luck!

How do you use a variable in a regular expression?

String.prototype.replaceAll = function(a, b) {
    return this.replace(new RegExp(a.replace(/([.?*+^$[\]\\(){}|-])/ig, "\\$1"), 'ig'), b)
}

Test it like:

var whatever = 'Some [b]random[/b] text in a [b]sentence.[/b]'

console.log(whatever.replaceAll("[", "<").replaceAll("]", ">"))

GROUP BY without aggregate function

Given this data:

Col1  Col2  Col3
 A     X     1
 A     Y     2
 A     Y     3
 B     X     0
 B     Y     3
 B     Z     1

This query:

SELECT Col1, Col2, Col3 FROM data GROUP BY Col1, Col2, Col3

Would result in exactly the same table.

However, this query:

SELECT Col1, Col2 FROM data GROUP BY Col1, Col2

Would result in:

Col1  Col2
 A     X  
 A     Y  
 B     X  
 B     Y  
 B     Z  

Now, a query:

SELECT Col1, Col2, Col3 FROM data GROUP BY Col1, Col2

Would create a problem: the line with A, Y is the result of grouping the two lines

 A     Y     2
 A     Y     3

So, which value should be in Col3, '2' or '3'?

Normally you would use a GROUP BY to calculate e.g. a sum:

SELECT Col1, Col2, SUM(Col3) FROM data GROUP BY Col1, Col2

So in the line, we had a problem with we now get (2+3) = 5.

Grouping by all your columns in your select is effectively the same as using DISTINCT, and it is preferable to use the DISTINCT keyword word readability in this case.

So instead of

SELECT Col1, Col2, Col3 FROM data GROUP BY Col1, Col2, Col3

use

SELECT DISTINCT Col1, Col2, Col3 FROM data

Goal Seek Macro with Goal as a Formula

I think your issue is that Range("H18") doesn't contain a formula. Also, you could make your code more efficient by eliminating x. Instead, change your code to

Range("H18").GoalSeek Goal:=Range("H32").Value, ChangingCell:=Range("G18")

NGINX: upstream timed out (110: Connection timed out) while reading response header from upstream

Hopefully it helps someone: I ran into this error and the cause was wrong permission on the log folder for phpfpm, after changing it so phpfpm could write to it, everything was fine.

Assign pandas dataframe column dtypes

facing similar problem to you. In my case I have 1000's of files from cisco logs that I need to parse manually.

In order to be flexible with fields and types I have successfully tested using StringIO + read_cvs which indeed does accept a dict for the dtype specification.

I usually get each of the files ( 5k-20k lines) into a buffer and create the dtype dictionaries dynamically.

Eventually I concatenate ( with categorical... thanks to 0.19) these dataframes into a large data frame that I dump into hdf5.

Something along these lines

import pandas as pd
import io 

output = io.StringIO()
output.write('A,1,20,31\n')
output.write('B,2,21,32\n')
output.write('C,3,22,33\n')
output.write('D,4,23,34\n')

output.seek(0)


df=pd.read_csv(output, header=None,
        names=["A","B","C","D"],
        dtype={"A":"category","B":"float32","C":"int32","D":"float64"},
        sep=","
       )

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 4 columns):
A    5 non-null category
B    5 non-null float32
C    5 non-null int32
D    5 non-null float64
dtypes: category(1), float32(1), float64(1), int32(1)
memory usage: 205.0 bytes
None

Not very pythonic.... but does the job

Hope it helps.

JC

Preserve Line Breaks From TextArea When Writing To MySQL

why make is sooooo hard people when it can be soooo easy :)

//here is the pull from the form
$your_form_text = $_POST['your_form_text'];


//line 1 fixes the line breaks - line 2 the slashes
$your_form_text = nl2br($your_form_text);
$your_form_text = stripslashes($your_form_text);

//email away
$message = "Comments: $your_form_text";
mail("[email protected]", "Website Form Submission", $message, $headers);

you will obviously need headers and likely have more fields, but this is your textarea take care of

Query an XDocument for elements by name at any depth

I am using XPathSelectElements extension method which works in the same way to XmlDocument.SelectNodes method:

using System;
using System.Xml.Linq;
using System.Xml.XPath; // for XPathSelectElements

namespace testconsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            XDocument xdoc = XDocument.Parse(
                @"<root>
                    <child>
                        <name>john</name>
                    </child>
                    <child>
                        <name>fred</name>
                    </child>
                    <child>
                        <name>mark</name>
                    </child>
                 </root>");

            foreach (var childElem in xdoc.XPathSelectElements("//child"))
            {
                string childName = childElem.Element("name").Value;
                Console.WriteLine(childName);
            }
        }
    }
}

How do I check whether an array contains a string in TypeScript?

Also note that "in" keyword does not work on arrays. It works on objects only.

propName in myObject

Array inclusion test is

myArray.includes('three');

Center Div inside another (100% width) div

.outerdiv {
    margin-left: auto;
    margin-right: auto;
    display: table;
}

Doesn't work in internet explorer 7... but who cares ?

Remove pandas rows with duplicate indices

This adds the index as a dataframe column, drops duplicates on that, then removes the new column:

df = df.reset_index().drop_duplicates(subset='index', keep='last').set_index('index').sort_index()

Note that the use of .sort_index() above at the end is as needed and is optional.

How do I get the command-line for an Eclipse run configuration?

I found a solution on Stack Overflow for Java program run configurations which also works for JUnit run configurations.

You can get the full command executed by your configuration on the Debug tab, or more specifically the Debug view.

  1. Run your application
  2. Go to your Debug perspective
  3. There should be an entry in there (in the Debug View) for the app you've just executed
  4. Right-click the node which references java.exe or javaw.exe and select Properties In the dialog that pops up you'll see the Command Line which includes all jars, parameters, etc

Unsupported Media Type in postman

You need to set the content-type in postman as JSON (application/json).

Go to the body inside your POST request, there you will find the raw option.

Right next to it, there will be a drop down, select JSON (application.json).

How to create composite primary key in SQL Server 2008

To create a composite unique key on table

ALTER TABLE [TableName] ADD UNIQUE ([Column1], [Column2], [column3]);

How to pass payload via JSON file for curl?

curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.

How to delete empty folders using windows command prompt?

Adding to corroded answer from the same referenced page is a PowerShell version http://blogs.msdn.com/b/oldnewthing/archive/2008/04/17/8399914.aspx#8408736

Get-ChildItem -Recurse . | where { $_.PSISContainer -and @( $_ | Get-ChildItem ).Count -eq 0 } | Remove-Item

or, more tersely,

gci -R . | where { $_.PSISContainer -and @( $_ | gci ).Count -eq 0 } | ri

credit goes to the posting author

Cannot read property 'map' of undefined

First of all, set more safe initial data:

getInitialState : function() {
    return {data: {comments:[]}};
},

And ensure your ajax data.

It should work if you follow above two instructions like Demo.

Updated: you can just wrap the .map block with conditional statement.

if (this.props.data) {
  var commentNodes = this.props.data.map(function (comment){
      return (
        <div>
          <h1>{comment.author}</h1>
        </div>
      );
  });
}

How to avoid page refresh after button click event in asp.net

html

 "input type ="text" id="txtnothing" runat ="server" "

javacript

var txt = document.getElementById("txtnothing");
        txt.value =  Date.now();

code

 If Not (Session("txtnothing") Is Nothing OrElse String.IsNullOrEmpty(Session("txtnothing"))) Then
            If Session("txtnothing") = txtnothing.Value Then
                lblMsg.Text = "Please try again not a valid request"
                Exit Sub
            End If
        End If
        Session("txtnothing") = txtnothing.Value

Target class controller does not exist - Laravel 8

For solution just uncomment line 29:

**protected $namespace = 'App\\Http\\Controllers';**

in 'app\Providers\RouteServiceProvider.php' file.

just uncomment line 29

How to replace a substring of a string

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

from javadoc.

How do I make calls to a REST API using C#?

My suggestion would be to use RestSharp. You can make calls to REST services and have them cast into POCO objects with very little boilerplate code to actually have to parse through the response. This will not solve your particular error, but it answers your overall question of how to make calls to REST services. Having to change your code to use it should pay off in the ease of use and robustness moving forward. That is just my two cents though.

Example:

namespace RestSharpThingy
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Reflection;

    using RestSharp;

    public static class Program
    {
        public static void Main()
        {
            Uri baseUrl = new Uri("https://httpbin.org/");
            IRestClient client = new RestClient(baseUrl);
            IRestRequest request = new RestRequest("get", Method.GET) { Credentials = new NetworkCredential("testUser", "P455w0rd") };

            request.AddHeader("Authorization", "Bearer qaPmk9Vw8o7r7UOiX-3b-8Z_6r3w0Iu2pecwJ3x7CngjPp2fN3c61Q_5VU3y0rc-vPpkTKuaOI2eRs3bMyA5ucKKzY1thMFoM0wjnReEYeMGyq3JfZ-OIko1if3NmIj79ZSpNotLL2734ts2jGBjw8-uUgKet7jQAaq-qf5aIDwzUo0bnGosEj_UkFxiJKXPPlF2L4iNJSlBqRYrhw08RK1SzB4tf18Airb80WVy1Kewx2NGq5zCC-SCzvJW-mlOtjIDBAQ5intqaRkwRaSyjJ_MagxJF_CLc4BNUYC3hC2ejQDoTE6HYMWMcg0mbyWghMFpOw3gqyfAGjr6LPJcIly__aJ5__iyt-BTkOnMpDAZLTjzx4qDHMPWeND-TlzKWXjVb5yMv5Q6Jg6UmETWbuxyTdvGTJFzanUg1HWzPr7gSs6GLEv9VDTMiC8a5sNcGyLcHBIJo8mErrZrIssHvbT8ZUPWtyJaujKvdgazqsrad9CO3iRsZWQJ3lpvdQwucCsyjoRVoj_mXYhz3JK3wfOjLff16Gy1NLbj4gmOhBBRb8rJnUXnP7rBHs00FAk59BIpKLIPIyMgYBApDCut8V55AgXtGs4MgFFiJKbuaKxq8cdMYEVBTzDJ-S1IR5d6eiTGusD5aFlUkAs9NV_nFw");
            request.AddParameter("clientId", 123);

            IRestResponse<RootObject> response = client.Execute<RootObject>(request);

            if (response.IsSuccessful)
            {
                response.Data.Write();
            }
            else
            {
                Console.WriteLine(response.ErrorMessage);
            }

            Console.WriteLine();

            string path = Assembly.GetExecutingAssembly().Location;
            string name = Path.GetFileName(path);

            request = new RestRequest("post", Method.POST);
            request.AddFile(name, File.ReadAllBytes(path), name, "application/octet-stream");
            response = client.Execute<RootObject>(request);
            if (response.IsSuccessful)
            {
                response.Data.Write();
            }
            else
            {
                Console.WriteLine(response.ErrorMessage);
            }

            Console.ReadLine();
        }

        private static void Write(this RootObject rootObject)
        {
            Console.WriteLine("clientId: " + rootObject.args.clientId);
            Console.WriteLine("Accept: " + rootObject.headers.Accept);
            Console.WriteLine("AcceptEncoding: " + rootObject.headers.AcceptEncoding);
            Console.WriteLine("AcceptLanguage: " + rootObject.headers.AcceptLanguage);
            Console.WriteLine("Authorization: " + rootObject.headers.Authorization);
            Console.WriteLine("Connection: " + rootObject.headers.Connection);
            Console.WriteLine("Dnt: " + rootObject.headers.Dnt);
            Console.WriteLine("Host: " + rootObject.headers.Host);
            Console.WriteLine("Origin: " + rootObject.headers.Origin);
            Console.WriteLine("Referer: " + rootObject.headers.Referer);
            Console.WriteLine("UserAgent: " + rootObject.headers.UserAgent);
            Console.WriteLine("origin: " + rootObject.origin);
            Console.WriteLine("url: " + rootObject.url);
            Console.WriteLine("data: " + rootObject.data);
            Console.WriteLine("files: ");
            foreach (KeyValuePair<string, string> kvp in rootObject.files ?? Enumerable.Empty<KeyValuePair<string, string>>())
            {
                Console.WriteLine("\t" + kvp.Key + ": " + kvp.Value);
            }
        }
    }

    public class Args
    {
        public string clientId { get; set; }
    }

    public class Headers
    {
        public string Accept { get; set; }

        public string AcceptEncoding { get; set; }

        public string AcceptLanguage { get; set; }

        public string Authorization { get; set; }

        public string Connection { get; set; }

        public string Dnt { get; set; }

        public string Host { get; set; }

        public string Origin { get; set; }

        public string Referer { get; set; }

        public string UserAgent { get; set; }
    }

    public class RootObject
    {
        public Args args { get; set; }

        public Headers headers { get; set; }

        public string origin { get; set; }

        public string url { get; set; }

        public string data { get; set; }

        public Dictionary<string, string> files { get; set; }
    }
}

How to use absolute path in twig functions

From Symfony2 documentation: Absolute URLs for assets were introduced in Symfony 2.5.

If you need absolute URLs for assets, you can set the third argument (or the absolute argument) to true:

Example:

<img src="{{ asset('images/logo.png', absolute=true) }}" alt="Symfony!" />

How to create my json string by using C#?

No real need for the JSON.NET package. You could use JavaScriptSerializer. The Serialize method will turn a managed type instance into a JSON string.

var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(instanceOfThing);

how to set the default value to the drop down list control?

Assuming that the DropDownList control in the other table also contains DepartmentName and DepartmentID:

lstDepartment.ClearSelection();

foreach (var item in lstDepartment.Items) 
{
  if (item.Value == otherDropDownList.SelectedValue)
  {
    item.Selected = true;
  }
}

Java NIO FileChannel versus FileOutputstream performance / usefulness

My experience with larger files sizes has been that java.nio is faster than java.io. Solidly faster. Like in the >250% range. That said, I am eliminating obvious bottlenecks, which I suggest your micro-benchmark might suffer from. Potential areas for investigating:

The buffer size. The algorithm you basically have is

  • copy from disk to buffer
  • copy from buffer to disk

My own experience has been that this buffer size is ripe for tuning. I've settled on 4KB for one part of my application, 256KB for another. I suspect your code is suffering with such a large buffer. Run some benchmarks with buffers of 1KB, 2KB, 4KB, 8KB, 16KB, 32KB and 64KB to prove it to yourself.

Don't perform java benchmarks that read and write to the same disk.

If you do, then you are really benchmarking the disk, and not Java. I would also suggest that if your CPU is not busy, then you are probably experiencing some other bottleneck.

Don't use a buffer if you don't need to.

Why copy to memory if your target is another disk or a NIC? With larger files, the latency incured is non-trivial.

Like other have said, use FileChannel.transferTo() or FileChannel.transferFrom(). The key advantage here is that the JVM uses the OS's access to DMA (Direct Memory Access), if present. (This is implementation dependent, but modern Sun and IBM versions on general purpose CPUs are good to go.) What happens is the data goes straight to/from disc, to the bus, and then to the destination... bypassing any circuit through RAM or the CPU.

The web app I spent my days and night working on is very IO heavy. I've done micro benchmarks and real-world benchmarks too. And the results are up on my blog, have a look-see:

Use production data and environments

Micro-benchmarks are prone to distortion. If you can, make the effort to gather data from exactly what you plan to do, with the load you expect, on the hardware you expect.

My benchmarks are solid and reliable because they took place on a production system, a beefy system, a system under load, gathered in logs. Not my notebook's 7200 RPM 2.5" SATA drive while I watched intensely as the JVM work my hard disc.

What are you running on? It matters.

Django - limiting query results

Actually I think the LIMIT 10 would be issued to the database so slicing would not occur in Python but in the database.

See limiting-querysets for more information.

How to set session timeout dynamically in Java web applications?

As another anwsers told, you can change in a Session Listener. But you can change it directly in your servlet, for example.

getRequest().getSession().setMaxInactiveInterval(123);

How do I float a div to the center?

Simple solution:

<style>
.center {
    margin: auto;

}
</style>

<div class="center">
    <p> somthing goes here </p>
</div>

Try Online

Why is list initialization (using curly braces) better than the alternatives?

Basically copying and pasting from Bjarne Stroustrup's "The C++ Programming Language 4th Edition":

List initialization does not allow narrowing (§iso.8.5.4). That is:

  • An integer cannot be converted to another integer that cannot hold its value. For example, char to int is allowed, but not int to char.
  • A floating-point value cannot be converted to another floating-point type that cannot hold its value. For example, float to double is allowed, but not double to float.
  • A floating-point value cannot be converted to an integer type.
  • An integer value cannot be converted to a floating-point type.

Example:

void fun(double val, int val2) {

    int x2 = val;    // if val == 7.9, x2 becomes 7 (bad)

    char c2 = val2;  // if val2 == 1025, c2 becomes 1 (bad)

    int x3 {val};    // error: possible truncation (good)

    char c3 {val2};  // error: possible narrowing (good)

    char c4 {24};    // OK: 24 can be represented exactly as a char (good)

    char c5 {264};   // error (assuming 8-bit chars): 264 cannot be 
                     // represented as a char (good)

    int x4 {2.0};    // error: no double to int value conversion (good)

}

The only situation where = is preferred over {} is when using auto keyword to get the type determined by the initializer.

Example:

auto z1 {99};   // z1 is an int
auto z2 = {99}; // z2 is std::initializer_list<int>
auto z3 = 99;   // z3 is an int

Conclusion

Prefer {} initialization over alternatives unless you have a strong reason not to.

Why am I not getting a java.util.ConcurrentModificationException in this example?

The forward/iterator method does not work when removing items. You can remove the element without error, but you will get a runtime error when you try to access removed items. You can't use the iterator because as pushy shows it will cause a ConcurrentModificationException, so use a regular for loop instead, but step backwards through it.

List<Integer> integerList;
integerList = new ArrayList<Integer>();
integerList.add(1);
integerList.add(2);
integerList.add(3);

int size= integerList.size();

//Item to remove
Integer remove = Integer.valueOf(3);

A solution:

Traverse the array in reverse order if you are going to remove a list element. Simply by going backwards through the list you avoid visiting an item that has been removed, which removes the exception.

//To remove items from the list, start from the end and go backwards through the arrayList
//This way if we remove one from the beginning as we go through, then we will avoid getting a runtime error
//for java.lang.IndexOutOfBoundsException or java.util.ConcurrentModificationException as when we used the iterator
for (int i=size-1; i> -1; i--) {
    if (integerList.get(i).equals(remove) ) {
        integerList.remove(i);
    }
}

fatal: early EOF fatal: index-pack failed

If you're on Windows, you may want to check git clone fails with "index-pack" failed?.

Basically, after running your git.exe daemon ... command, select some text from that console window. Retry pulling/cloning, it might just work now!

See this answer for more info.

SQL - Rounding off to 2 decimal places

I find the STR function the cleanest means of accomplishing this.

SELECT STR(ceiling(123.415432875), 6, 2)

How to make a JFrame button open another JFrame class in Netbeans?

new SecondForm().setVisible(true);

You can either use setVisible(false) or dispose() method to disappear current form.

Authentication failed for https://xxx.visualstudio.com/DefaultCollection/_git/project

I had a same issue recently (visual studio 2017 & Windows 10), and solved it using the following method:

Control Panel --> Credential Manager --> Manage Windows Credentials --> Choose the entry of the git repository, and Edit the user and password.

Done.

Explanation of JSONB introduced by PostgreSQL

As far as I can tell,

  • hstore as it currently exists (in Postgresql 9.3) does not allow for nesting other objects and arrays as the values of its key/value pairs. however a future hstore patch will allow for nesting. this patch will not be in the 9.4 release and may not be included any time soon.

  • json as it currently exists does allow for nesting, but is text-based, and does not allow for indexing, thus it is "slow"

  • jsonb that will be released with 9.4 will have the current nesting capabilities of json, as well as the GIN/GIST indexing of hstore, so it will be fast

People working on postgresql 9.4 seem to be saying that the new, fast jsonb type will appeal to people who would have chosen to use a noSQL data store like MongoDB, but can now combine a relational database with query-able unstructured data under one roof

http://www.databasesoup.com/2014/02/why-hstore2jsonb-is-most-important.html

Benchmarks of postgresql 9.4 jsonb seem to be on par with or in some cases faster than MongoDB

http://texture.io/alphabetum/postgresql-incl-hstore-vs-mongodb

How should I import data from CSV into a Postgres table using pgAdmin 3?

assuming you have a SQL table called mydata - you can load data from a csv file as follows:

COPY MYDATA FROM '<PATH>/MYDATA.CSV' CSV HEADER;

For more details refer to: http://www.postgresql.org/docs/9.2/static/sql-copy.html

Looping through a hash, or using an array in PowerShell

I prefer this variant on the enumerator method with a pipeline, because you don't have to refer to the hash table in the foreach (tested in PowerShell 5):

$hash = @{
    'a' = 3
    'b' = 2
    'c' = 1
}
$hash.getEnumerator() | foreach {
    Write-Host ("Key = " + $_.key + " and Value = " + $_.value);
}

Output:

Key = c and Value = 1
Key = b and Value = 2
Key = a and Value = 3

Now, this has not been deliberately sorted on value, the enumerator simply returns the objects in reverse order.

But since this is a pipeline, I now can sort the objects received from the enumerator on value:

$hash.getEnumerator() | sort-object -Property value -Desc | foreach {
  Write-Host ("Key = " + $_.key + " and Value = " + $_.value);
}

Output:

Key = a and Value = 3
Key = b and Value = 2
Key = c and Value = 1

Counting null and non-null values in a single query

As i understood your query, You just run this script and get Total Null,Total NotNull rows,

select count(*) - count(a) as 'Null', count(a) as 'Not Null' from us;

Reading binary file and looping over each byte

To read a file — one byte at a time (ignoring the buffering) — you could use the two-argument iter(callable, sentinel) built-in function:

with open(filename, 'rb') as file:
    for byte in iter(lambda: file.read(1), b''):
        # Do stuff with byte

It calls file.read(1) until it returns nothing b'' (empty bytestring). The memory doesn't grow unlimited for large files. You could pass buffering=0 to open(), to disable the buffering — it guarantees that only one byte is read per iteration (slow).

with-statement closes the file automatically — including the case when the code underneath raises an exception.

Despite the presence of internal buffering by default, it is still inefficient to process one byte at a time. For example, here's the blackhole.py utility that eats everything it is given:

#!/usr/bin/env python3
"""Discard all input. `cat > /dev/null` analog."""
import sys
from functools import partial
from collections import deque

chunksize = int(sys.argv[1]) if len(sys.argv) > 1 else (1 << 15)
deque(iter(partial(sys.stdin.detach().read, chunksize), b''), maxlen=0)

Example:

$ dd if=/dev/zero bs=1M count=1000 | python3 blackhole.py

It processes ~1.5 GB/s when chunksize == 32768 on my machine and only ~7.5 MB/s when chunksize == 1. That is, it is 200 times slower to read one byte at a time. Take it into account if you can rewrite your processing to use more than one byte at a time and if you need performance.

mmap allows you to treat a file as a bytearray and a file object simultaneously. It can serve as an alternative to loading the whole file in memory if you need access both interfaces. In particular, you can iterate one byte at a time over a memory-mapped file just using a plain for-loop:

from mmap import ACCESS_READ, mmap

with open(filename, 'rb', 0) as f, mmap(f.fileno(), 0, access=ACCESS_READ) as s:
    for byte in s: # length is equal to the current file size
        # Do stuff with byte

mmap supports the slice notation. For example, mm[i:i+len] returns len bytes from the file starting at position i. The context manager protocol is not supported before Python 3.2; you need to call mm.close() explicitly in this case. Iterating over each byte using mmap consumes more memory than file.read(1), but mmap is an order of magnitude faster.

Want to move a particular div to right

This will do the job:

_x000D_
_x000D_
<div style="position:absolute; right:0;">Hello world</div>
_x000D_
_x000D_
_x000D_

Set Matplotlib colorbar size to match graph

This combination (and values near to these) seems to "magically" work for me to keep the colorbar scaled to the plot, no matter what size the display.

plt.colorbar(im,fraction=0.046, pad=0.04)

It also does not require sharing the axis which can get the plot out of square.

In log4j, does checking isDebugEnabled before logging improve performance?

Since Log4j version 2.4 (orslf4j-api 2.0.0-alpha1) it's much better to use fluent API (or Java 8 lambda support for lazy logging), supporting Supplier<?> for log message argument, that can be given by lambda:

log.debug("Debug message with expensive data : {}", 
           () -> doExpensiveCalculation());

OR with slf4j API:

log.atDebug()
            .addArgument(() -> doExpensiveCalculation())
            .log("Debug message with expensive data : {}");

Finding child element of parent pure javascript

Just adding another idea you could use a child selector to get immediate children

document.querySelectorAll(".parent > .child1");

should return all the immediate children with class .child1

Converting an int to std::string

boost::lexical_cast<std::string>(yourint) from boost/lexical_cast.hpp

Work's for everything with std::ostream support, but is not as fast as, for example, itoa

It even appears to be faster than stringstream or scanf:

How to disable an input box using angular.js

You need to use ng-disabled directive

<input data-ng-model="userInf.username" 
       class="span12 editEmail" 
       type="text" 
       placeholder="[email protected]" 
       pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" 
       required 
       ng-disabled="<expression to disable>" />

Sorting arrays in javascript by object key value

This worked for me

var files=data.Contents;
          files = files.sort(function(a,b){
        return a.LastModified - b. LastModified;
      });

OR use Lodash to sort the array

files = _.orderBy(files,'LastModified','asc');

Create a Cumulative Sum Column in MySQL

Sample query

SET @runtot:=0;
SELECT
   q1.d,
   q1.c,
   (@runtot := @runtot + q1.c) AS rt
FROM
   (SELECT
       DAYOFYEAR(date) AS d,
       COUNT(*) AS c
    FROM  orders
    WHERE  hasPaid > 0
    GROUP  BY d
    ORDER  BY d) AS q1

New Array from Index Range Swift

Array functional way:

   array.enumerated().filter { $0.offset < limit }.map { $0.element }

ranged:

 array.enumerated().filter { $0.offset >= minLimit && $0.offset < maxLimit }.map { $0.element }

The advantage of this method is such implementation is safe.

How do I count occurrence of duplicate items in array

this code will return duplicate value in same array

$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
foreach($arr as $key=>$item){
  if(array_count_values($arr)[$item] > 1){
     echo "Found Matched value : ".$item." <br />";
  }
}

How to load a xib file in a UIView

I created a sample project on github to load a UIView from a .xib file inside another .xib file. Or you can do it programmatically.

This is good for little widgets you want to reuse on different UIViewController objects.

  1. New Approach: https://github.com/PaulSolt/CustomUIView
  2. Original Approach: https://github.com/PaulSolt/CompositeXib

Load a Custom UIView from .xib file

Where are $_SESSION variables stored?

I am using Ubuntu and my sessions are stored in /var/lib/php5.

How to commit changes to a new branch

If I understand right, you've made a commit to changed_branch and you want to copy that commit to other_branch? Easy:

git checkout other_branch
git cherry-pick changed_branch

Sublime Text 2 multiple line edit

Use multiple cursors and column selection.

In your case you just need to place the cursors at the beginning of each column containing the "words".

Linux and Windows

  • Click & drag to select column(s): Shift + RightMouseBtn
  • Add other column(s) to selection by click & drag: Ctrl + Shift + RightMouseBtn
  • Subtract column(s) from the selection: Alt + Shift + RightMouseBtn
  • Add individual cursors: Ctrl + LeftMouseBtn
  • Remove individual cursors: Alt + LeftMouseBtn

Mac

  • Click & drag to select column(s): Option? + LeftMouseBtn
  • Add other column(s) to selection by click & drag: Option? + LeftMouseBtn
  • Subtract column(s) from the selection: Cmd? + Option? + shift + LeftMouseBtn
  • Add individual cursors: Cmd? + LeftMouseBtn
  • Remove individual cursors: Cmd? + Option? + shift + LeftMouseBtn

Then edit as needed. In your case, type 0, x.

You could also navigate as needed to the end or beginning of the words, select the words and surround with quotes or parenthesis, and so on.


References:

Benefits of using the conditional ?: (ternary) operator

A really cool usage is:

x = foo ? 1 :
    bar ? 2 :
    baz ? 3 :
          4;

background-image: url("images/plaid.jpg") no-repeat; wont show up

Try this:

body
{ 
    background:url("images/plaid.jpg") no-repeat fixed center;
}

jsfiddle example: http://jsfiddle.net/Q9Zfa/

Enable & Disable a Div and its elements in Javascript

The following selects all descendant elements and disables them:

$("#dcacl").find("*").prop("disabled", true);

But it only really makes sense to disable certain element types: inputs, buttons, etc., so you want a more specific selector:

$("#dcac1").find(":input").prop("disabled",true);
// noting that ":input" gives you the equivalent of
$("#dcac1").find("input,select,textarea,button").prop("disabled",true);

To re-enable you just set "disabled" to false.

I want to Disable them at loading the page and then by a click i can enable them

OK, so put the above code in a document ready handler, and setup an appropriate click handler:

$(document).ready(function() {
    var $dcac1kids = $("#dcac1").find(":input");
    $dcac1kids.prop("disabled",true);

    // not sure what you want to click on to re-enable
    $("selector for whatever you want to click").one("click",function() {
       $dcac1kids.prop("disabled",false);
    }
}

I've cached the results of the selector on the assumption that you're not adding more elements to the div between the page load and the click. And I've attached the click handler with .one() since you haven't specified a requirement to re-disable the elements so presumably the event only needs to be handled once. Of course you can change the .one() to .click() if appropriate.

Get just the filename from a path in a Bash script

basename and dirname solutions are more convenient. Those are alternative commands:

FILE_PATH="/opt/datastores/sda2/test.old.img"
echo "$FILE_PATH" | sed "s/.*\///"

This returns test.old.img like basename.

This is salt filename without extension:

echo "$FILE_PATH" | sed -r "s/.+\/(.+)\..+/\1/"

It returns test.old.

And following statement gives the full path like dirname command.

echo "$FILE_PATH" | sed -r "s/(.+)\/.+/\1/"

It returns /opt/datastores/sda2

Error: TypeError: $(...).dialog is not a function

Change jQueryUI to version 1.11.4 and make sure jQuery is not added twice.

How to perform a real time search and filter on a HTML table

Thank you @dfsq for the very helpful code!

I've made some adjustments and maybe some others like them too. I ensured that you can search for multiple words, without having a strict match.

Example rows:

  • Apples and Pears
  • Apples and Bananas
  • Apples and Oranges
  • ...

You could search for 'ap pe' and it would recognise the first row
You could search for 'banana apple' and it would recognise the second row

Demo: http://jsfiddle.net/JeroenSormani/xhpkfwgd/1/

var $rows = $('#table tr');
$('#search').keyup(function() {
  var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase().split(' ');

  $rows.hide().filter(function() {
    var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
    var matchesSearch = true;
    $(val).each(function(index, value) {
      matchesSearch = (!matchesSearch) ? false : ~text.indexOf(value);
    });
    return matchesSearch;
  }).show();
});

How to use the gecko executable with Selenium

Recently Selenium has launched Selenium 3 and if you are trying to use Firefox latest version then you have to use GeckoDriver:

System.setProperty("webdriver.gecko.driver","G:\\Selenium\\Firefox driver\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();

You can check full documentation from here

HTML image not showing in Gmail

HTTP or HTTPS should be full address

background-image: url(http://fulladdress.com/ca/1/product_assets/T/C/X/M/K/NMTCXMK_mu.jpg)

var mailOptions = {
  from: '[email protected]',
  to: emails,
  subject: 'i super another ma node mailer cool test',
  text: 'That was easy!',
  html: '<a href="//google.com"><div style="background-image: url(http://fulladdress.com/ca/1/product_assets/T/C/X/M/K/NMTCXMK_mu.jpg);width:500px;height:500px">ascfas</div></a>'
};

How to break lines at a specific character in Notepad++?

I have no idea how it can work automatically, but you can copy "], " together with new line and then use replace function.

MySQL: When is Flush Privileges in MySQL really needed?

2 points in addition to all other good answers:

1:

what are the Grant Tables?

from dev.mysql.com

The MySQL system database includes several grant tables that contain information about user accounts and the privileges held by them.

clari?cation: in MySQL, there are some inbuilt databases , one of them is "mysql" , all the tables on "mysql" database have been called as grant tables

2:

note that if you perform:

UPDATE a_grant_table SET password=PASSWORD('1234') WHERE test_col = 'test_val';

and refresh phpMyAdmin , you'll realize that your password has been changed on that table but even now if you perform:

mysql -u someuser -p

your access will be denied by your new password until you perform :

FLUSH PRIVILEGES;

Compile throws a "User-defined type not defined" error but does not go to the offending line of code

Possible solution, you are trying to work with Powerpoint via Excel VBA and you didn't activate Powerpoint Object Library first.

To do this, in the VBA editor top menu select Tools, References, then scroll down to click the library called Microsoft Powerpoint xx.x Object Library. Office 2007 is library 12, each Office version has a different library. FYI, I've experienced some odd errors and file corruption when I activate the 2007 library but someone tries to open and run this macro using Excel 2003. The old version of Excel doesn't recognize the newer library, which seems to cause problems.

Convert date formats in bash

Just with bash:

convert_date () {
    local months=( JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC )
    local i
    for (( i=0; i<11; i++ )); do
        [[ $2 = ${months[$i]} ]] && break
    done
    printf "%4d%02d%02d\n" $3 $(( i+1 )) $1
}

And invoke it like this

d=$( convert_date 27 JUN 2011 )

Or if the "old" date string is stored in a variable

d_old="27 JUN 2011"
d=$( convert_date $d_old )  # not quoted

Spark specify multiple column conditions for dataframe join

One thing you can do is to use raw SQL:

case class Bar(x1: Int, y1: Int, z1: Int, v1: String)
case class Foo(x2: Int, y2: Int, z2: Int, v2: String)

val bar = sqlContext.createDataFrame(sc.parallelize(
    Bar(1, 1, 2, "bar") :: Bar(2, 3, 2, "bar") ::
    Bar(3, 1, 2, "bar") :: Nil))

val foo = sqlContext.createDataFrame(sc.parallelize(
    Foo(1, 1, 2, "foo") :: Foo(2, 1, 2, "foo") ::
    Foo(3, 1, 2, "foo") :: Foo(4, 4, 4, "foo") :: Nil))

foo.registerTempTable("foo")
bar.registerTempTable("bar")

sqlContext.sql(
    "SELECT * FROM foo LEFT JOIN bar ON x1 = x2 AND y1 = y2 AND z1 = z2")

How to set .net Framework 4.5 version in IIS 7 application pool

There is no 4.5 application pool. You can use any 4.5 application in 4.0 app pool. The .NET 4.5 is "just" an in-place-update not a major new version.

Plugin org.apache.maven.plugins:maven-compiler-plugin or one of its dependencies could not be resolved

I was getting this problem when using IBM RSA 9.6.1 when building a brand new development machine. The problem for me ended up being because of HTTPS on the Global Maven repository. My solution was to create a Maven settings.xml that forced it to use HTTP.

The key to me was that the central repository was empty when I exploded it under Maven Repositories -- > Global Repositories

Using the following settings file worked for me:

<settings>
  <activeProfiles>
    <!--make the profile active all the time -->
    <activeProfile>insecurecentral</activeProfile>
  </activeProfiles>
  <profiles>
    <profile>
      <id>insecurecentral</id>
      <!--Override the repository (and pluginRepository) "central" from the Maven Super POM -->
      <repositories>
        <repository>
          <id>central</id>
          <url>http://repo.maven.apache.org/maven2</url>
          <releases>
            <enabled>true</enabled>
          </releases>
        </repository>
      </repositories>
      <pluginRepositories>
        <pluginRepository>
          <id>central</id>
          <url>http://repo.maven.apache.org/maven2</url>
          <releases>
            <enabled>true</enabled>
          </releases>
        </pluginRepository>
      </pluginRepositories>
    </profile>
  </profiles>
</settings>

I got the idea from this stackoverflow question.

PHP - Insert date into mysql

try CAST function in MySQL:

mysql_query("INSERT INTO data_table (title, date_of_event)
VALUES('". $_POST['post_title'] ."',
CAST('". $date ."' AS DATE))") or die(mysql_error()); 

Fix height of a table row in HTML Table

my css

TR.gray-t {background:#949494;}
h3{
    padding-top:3px;
    font:bold 12px/2px Arial;
}

my html

<TR class='gray-t'>
<TD colspan='3'><h3>KAJANG</h3>

I decrease the 2nd size in font.

padding-top is used to fix the size in IE7.

RegEx to match stuff between parentheses

var getMatchingGroups = function(s) {
  var r=/\((.*?)\)/g, a=[], m;
  while (m = r.exec(s)) {
    a.push(m[1]);
  }
  return a;
};

getMatchingGroups("something/([0-9])/([a-z])"); // => ["[0-9]", "[a-z]"]

Python Pandas counting and summing specific conditions

You didn't mention the fancy indexing capabilities of dataframes, e.g.:

>>> df = pd.DataFrame({"class":[1,1,1,2,2], "value":[1,2,3,4,5]})
>>> df[df["class"]==1].sum()
class    3
value    6
dtype: int64
>>> df[df["class"]==1].sum()["value"]
6
>>> df[df["class"]==1].count()["value"]
3

You could replace df["class"]==1by another condition.

npx command not found

Remove NodeJs and npm in your system and reinstall it by following commands

Uninlstallation

sudo apt remove nodejs
sudo apt remove npm

Fresh Installation

sudo apt install nodejs
sudo apt install npm

Configuration optional, in some cases users may face permission errors.

  1. user defined directory where npm will install packages

    mkdir ~/.npm-global

  2. configure npm

    npm config set prefix '~/.npm-global'

  3. add directory to path

    echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.profile

  4. refresh path for the current session

    source ~/.profile

  5. cross-check npm and node modules installed successfully in our system

    node -v
    npm -v

Installation of npx

sudo npm i -g npx
npx -v

Well-done we are ready to go... now you can easily use npx anywhere in your system.

Disable form auto submit on button click

Buttons like <button>Click to do something</button> are submit buttons.

Set type="button" to change that. type="submit" is the default (as specified by the HTML recommendation).

Why is the Java main method static?

As the execution start of a program from main() and and java is purely object oriented program where the object is declared inside main() that means main() is called before object creation so if main() would non static then to call it there would be needed a object because static means no need of object..........

sed edit file in place

You didn't specify what shell you are using, but with zsh you could use the =( ) construct to achieve this. Something along the lines of:

cp =(sed ... file; sync) file

=( ) is similar to >( ) but creates a temporary file which is automatically deleted when cp terminates.

ORA-06508: PL/SQL: could not find program unit being called

Based on previous answers. I resolved my issue by removing global variable at package level to procedure, since there was no impact in my case.

Original script was

create or replace PACKAGE BODY APPLICATION_VALIDATION AS 

V_ERROR_NAME varchar2(200) := '';

PROCEDURE  APP_ERROR_X47_VALIDATION (   PROCESS_ID IN VARCHAR2 ) AS BEGIN
     ------ rules for validation... END APP_ERROR_X47_VALIDATION ;

/* Some more code
*/

END APPLICATION_VALIDATION; /

Rewritten the same without global variable V_ERROR_NAME and moved to procedure under package level as

Modified Code

create or replace PACKAGE BODY APPLICATION_VALIDATION AS

PROCEDURE  APP_ERROR_X47_VALIDATION (   PROCESS_ID IN VARCHAR2 ) AS

**V_ERROR_NAME varchar2(200) := '';** 

BEGIN
     ------ rules for validation... END APP_ERROR_X47_VALIDATION ;

/* Some more code
*/

END APPLICATION_VALIDATION; /

When do items in HTML5 local storage expire?

If someone using jStorage Plugin of jQuery the it can be add expiry with setTTL function if jStorage plugin

$.jStorage.set('myLocalVar', "some value");
$.jStorage.setTTL("myLocalVar", 24*60*60*1000); // 24 Hr.

How to mount a single file in a volume

TL;DR/Notice:

If you experience a directory being created in place of the file you are trying to mount, you have probably failed to supply a valid and absolute path. This is a common mistake with a silent and confusing failure mode.

File volumes are done this way in docker (absolute path example (can use env variables), and you need to mention the file name) :

    volumes:
      - /src/docker/myapp/upload:/var/www/html/upload
      - /src/docker/myapp/upload/config.php:/var/www/html/config.php

You can also do:

    volumes:
      - ${PWD}/upload:/var/www/html/upload
      - ${PWD}/upload/config.php:/var/www/html/config.php

If you fire the docker-compose from /src/docker/myapp folder

Removing Spaces from a String in C?

I came across a variation to this question where you need to reduce multiply spaces into one space "represent" the spaces.

This is my solution:

char str[] = "Put Your string Here.....";

int copyFrom = 0, copyTo = 0;

printf("Start String %s\n", str);

while (str[copyTo] != 0) {
    if (str[copyFrom] == ' ') {
        str[copyTo] = str[copyFrom];
        copyFrom++;
        copyTo++;

        while ((str[copyFrom] == ' ') && (str[copyFrom] !='\0')) {
            copyFrom++;
        }
    }

    str[copyTo] = str[copyFrom];

    if (str[copyTo] != '\0') {
        copyFrom++;
        copyTo++;
    }
}

printf("Final String %s\n", str);

Hope it helps :-)

What is C# analog of C++ std::pair?

I created a C# implementation of Tuples, which solves the problem generically for between two and five values - here's the blog post, which contains a link to the source.

How do you get current active/default Environment profile programmatically in Spring?

To tweak a bit in order to handle the case where the variable is not set you could use a default value:

@Value("${spring.profiles.active:unknown}")
private String activeProfile;

This way if spring.profiles.active is set, it will take it else it will take the default value unknown.

So no exception will be triggered. And no need to force add something like @ActiveProfiles("test") in your test to make it pass.

How do I verify that a string only contains letters, numbers, underscores and dashes?

Regular expression can be very flexible.

import re;
re.fullmatch("^[\w-]+$", target_string) # fullmatch looks also workable for python 3.4

\w: Only [a-zA-Z0-9_]

So you need to add - char for justify hyphen char.

+: Match one or more repetitions of the preceding char. I guess you don't accept blank input. But if you do, change to * .

^: Matches the start of the string.

$: Matches the end of the string.

You need these two special characters since you need to avoid the following case. The unwanted chars like & here might appear between the matched pattern.

&&&PATTERN&&PATTERN

Implements vs extends: When to use? What's the difference?

extends is for extending a class.

implements is for implementing an interface

The difference between an interface and a regular class is that in an interface you can not implement any of the declared methods. Only the class that "implements" the interface can implement the methods. The C++ equivalent of an interface would be an abstract class (not EXACTLY the same but pretty much).

Also java doesn't support multiple inheritance for classes. This is solved by using multiple interfaces.

 public interface ExampleInterface {
    public void doAction();
    public String doThis(int number);
 }

 public class sub implements ExampleInterface {
     public void doAction() {
       //specify what must happen
     }

     public String doThis(int number) {
       //specfiy what must happen
     }
 }

now extending a class

 public class SuperClass {
    public int getNb() {
         //specify what must happen
        return 1;
     }

     public int getNb2() {
         //specify what must happen
        return 2;
     }
 }

 public class SubClass extends SuperClass {
      //you can override the implementation
      @Override
      public int getNb2() {
        return 3;
     }
 }

in this case

  Subclass s = new SubClass();
  s.getNb(); //returns 1
  s.getNb2(); //returns 3

  SuperClass sup = new SuperClass();
  sup.getNb(); //returns 1
  sup.getNb2(); //returns 2

Also, note that an @Override tag is not required for implementing an interface, as there is nothing in the original interface methods to be overridden

I suggest you do some more research on dynamic binding, polymorphism and in general inheritance in Object-oriented programming

DataTables: Cannot read property 'length' of undefined

It can happen when your view property name and name inside column section of data table is not matching . Make sure that property name and column data name are matching

How do I enable TODO/FIXME/XXX task tags in Eclipse?

All those settings are necessary to choose which tags you are interested in, but in order to display these tags in a list, you also need to select the right Eclipse perspective. I finally discovered that the "Markers" tab containing the "Task" list is only available under the "Java EE" perspective... Hope this helps! :-)

Task vs Thread differences

Usually you hear Task is a higher level concept than thread... and that's what this phrase means:

  1. You can't use Abort/ThreadAbortedException, you should support cancel event in your "business code" periodically testing token.IsCancellationRequested flag (also avoid long or timeoutless connections e.g. to db, otherwise you will never get a chance to test this flag). By the similar reason Thread.Sleep(delay) call should be replaced with Task.Delay(delay, token) call (passing token inside to have possibility to interrupt delay).

  2. There are no thread's Suspend and Resume methods functionality with tasks. Instance of task can't be reused either.

  3. But you get two new tools:

    a) continuations

    // continuation with ContinueWhenAll - execute the delegate, when ALL
    // tasks[] had been finished; other option is ContinueWhenAny
    
    Task.Factory.ContinueWhenAll( 
       tasks,
       () => {
           int answer = tasks[0].Result + tasks[1].Result;
           Console.WriteLine("The answer is {0}", answer);
       }
    );
    

    b) nested/child tasks

    //StartNew - starts task immediately, parent ends whith child
    var parent = Task.Factory.StartNew
    (() => {
              var child = Task.Factory.StartNew(() =>
             {
             //...
             });
          },  
          TaskCreationOptions.AttachedToParent
    );
    
  4. So system thread is completely hidden from task, but still task's code is executed in the concrete system thread. System threads are resources for tasks and ofcourse there is still thread pool under the hood of task's parallel execution. There can be different strategies how thread get new tasks to execute. Another shared resource TaskScheduler cares about it. Some problems that TaskScheduler solves 1) prefer to execute task and its conitnuation in the same thread minimizing switching cost - aka inline execution) 2) prefer execute tasks in an order they were started - aka PreferFairness 3) more effective distribution of tasks between inactive threads depending on "prior knowledge of tasks activity" - aka Work Stealing. Important: in general "async" is not same as "parallel". Playing with TaskScheduler options you can setup async tasks be executed in one thread synchronously. To express parallel code execution higher abstractions (than Tasks) could be used: Parallel.ForEach, PLINQ, Dataflow.

  5. Tasks are integrated with C# async/await features aka Promise Model, e.g there requestButton.Clicked += async (o, e) => ProcessResponce(await client.RequestAsync(e.ResourceName)); the execution of client.RequestAsync will not block UI thread. Important: under the hood Clicked delegate call is absolutely regular (all threading is done by compiler).

That is enough to make a choice. If you need to support Cancel functionality of calling legacy API that tends to hang (e.g. timeoutless connection) and for this case supports Thread.Abort(), or if you are creating multithread background calculations and want to optimize switching between threads using Suspend/Resume, that means to manage parallel execution manually - stay with Thread. Otherwise go to Tasks because of they will give you easy manipulate on groups of them, are integrated into the language and make developers more productive - Task Parallel Library (TPL) .

React-router: How to manually invoke Link?

again this is JS :) this still works ....

var linkToClick = document.getElementById('something');
linkToClick.click();

<Link id="something" to={/somewhaere}> the link </Link>

How to check for an undefined or null variable in JavaScript?

here's another way using the Array includes() method:

[undefined, null].includes(value)

How to filter Android logcat by application?

to filter the logs on command line use the below script

adb logcat com.yourpackage:v

how to count the total number of lines in a text file using python

You can use sum() with a generator expression here. The generator expression will be [1, 1, ...] up to the length of the file. Then we call sum() to add them all together, to get the total count.

with open('text.txt') as myfile:
    count = sum(1 for line in myfile)

It seems by what you have tried that you don't want to include empty lines. You can then do:

with open('text.txt') as myfile:
    count = sum(1 for line in myfile if line.rstrip('\n'))

Simple jQuery, PHP and JSONP example?

Use this ..

    $str = rawurldecode($_SERVER['REQUEST_URI']);
    $arr = explode("{",$str);
    $arr1 = explode("}", $arr[1]);
    $jsS = '{'.$arr1[0].'}';
    $data = json_decode($jsS,true);

Now ..

use $data['elemname'] to access the values.

send jsonp request with JSON Object.

Request format :

$.ajax({
    method : 'POST',
    url : 'xxx.com',
    data : JSONDataObj, //Use JSON.stringfy before sending data
    dataType: 'jsonp',
    contentType: 'application/json; charset=utf-8',
    success : function(response){
      console.log(response);
    }
}) 

Is there an equivalent of 'which' on the Windows command line?

If you have PowerShell installed (which I recommend), you can use the following command as a rough equivalent (substitute programName for your executable's name):

($Env:Path).Split(";") | Get-ChildItem -filter programName*

More is here: My Manwich! PowerShell Which

How to get the path of current worksheet in VBA?

Always nice to have:

Dim myPath As String     
Dim folderPath As String 

folderPath = Application.ActiveWorkbook.Path    
myPath = Application.ActiveWorkbook.FullName

e.printStackTrace equivalent in python

import traceback
traceback.print_exc()

When doing this inside an except ...: block it will automatically use the current exception. See http://docs.python.org/library/traceback.html for more information.

How to add icon inside EditText view in Android ?

use android:drawbleStart propery on EditText

    <EditText
        ...     
        android:drawableStart="@drawable/my_icon" />

Is there a better way to iterate over two lists, getting one element from each list for each iteration?

Iterating through elements of two lists simultaneously is known as zipping, and python provides a built in function for it, which is documented here.

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zipped)
>>> x == list(x2) and y == list(y2)
True

[Example is taken from pydocs]

In your case, it will be simply:

for (lat, lon) in zip(latitudes, longitudes):
    ... process lat and lon

Return JSON with error status code MVC

A simple way to send a error to Json is control Http Status Code of response object and set a custom error message.

Controller

public JsonResult Create(MyObject myObject) 
{
  //AllFine
  return Json(new { IsCreated = True, Content = ViewGenerator(myObject));

  //Use input may be wrong but nothing crashed
  return Json(new { IsCreated = False, Content = ViewGenerator(myObject));  

  //Error
  Response.StatusCode = (int)HttpStatusCode.InternalServerError;
  return Json(new { IsCreated = false, ErrorMessage = 'My error message');
}

JS

$.ajax({
     type: "POST",
     dataType: "json",
     url: "MyController/Create",
     data: JSON.stringify(myObject),
     success: function (result) {
       if(result.IsCreated)
     {
    //... ALL FINE
     }
     else
     {
    //... Use input may be wrong but nothing crashed
     }
   },
    error: function (error) {
            alert("Error:" + erro.responseJSON.ErrorMessage ); //Error
        }
  });

C# - What does the Assert() method do? Is it still useful?

Assert can help you give separate messaging behavior between testing and release. For example,

Debug.Assert(x > 2)

will only trigger a break if you are running a "debug" build, not a release build. There's a full example of this behavior here

How to check if datetime happens to be Saturday or Sunday in SQL Server 2008

ok i figure out :

DECLARE @dayName VARCHAR(9), @weekenda VARCHAR(9), @free INT
SET @weekenda =DATENAME(dw,GETDATE())

IF (@weekenda='Saturday' OR @weekenda='Sunday')
SET @free=1
ELSE
SET @free=0

than i use : .......... OR free=1

How can I remove a button or make it invisible in Android?

To completely remove a button from its parent layout:

((ViewGroup)button.getParent()).removeView(button);

How to enable CORS in AngularJs

Answered by myself.

CORS angular js + restEasy on POST

Well finally I came to this workaround: The reason it worked with IE is because IE sends directly a POST instead of first a preflight request to ask for permission. But I still don't know why the filter wasn't able to manage an OPTIONS request and sends by default headers that aren't described in the filter (seems like an override for that only case ... maybe a restEasy thing ...)

So I created an OPTIONS path in my rest service that rewrites the reponse and includes the headers in the response using response header

I'm still looking for the clean way to do it if anybody faced this before.

cURL not working (Error #77) for SSL connections on CentOS for non-root users

If you recently reached here as I did when searching for the same error in vain you may find it to be an update to NSS causing failure on CentOS. Test by running yum update and see if you get errors, curl also creates this error. Solution is simple enough just install NSS manually.

Read on...

If you're like me it threw up an error similar to this:

curl: (77) Problem with the SSL CA cert (path? access rights?)

This took some time to solve but found that it wasn't the CA cert because by recreating them and checking all the configuration I had ruled it out. It could have been libcurl so I went in search of updates.

As mentioned I recreated CA certs. You can do this also but it may be a waste of time. http://wiki.centos.org/HowTos/Https

The next step (probably should of been my first) was to check that everything was up-to-date by simply running yum.

$ yum update
$ yum upgrade

This gave me an affirmative answer that there was a bigger problem at play: Downloading Packages: error: rpmts_HdrFromFdno: Header V3 RSA/SHA1 Signature, key ID c105b9de: BAD Problem opening package nss-softokn-freebl-3.14.3–19.el6_6.x86_64.rpm I started reading about Certificate Verification with NSS and how this new update may be related to my problems. So yum is broken. This is because nss-softokn-* needs nss-softokn-freebl-* need each other to function. The problem is they don't check each others version for compatibility and in some cases it ends up breaking yum. Lets go fix things:

$ wget http://mirrors.linode.com/centos/6.6/updates/x86_64/Packages/nsssoftokn-freebl-3.14.3-19.el6_6.x86_64.rpm
$ rpm -Uvh nss-softokn-freebl-3.14.3–19.el6_6.x86_64.rpm
$ yum update

You should of course download from your nearest mirror and check for the correct version / OS etc. We basically download and install the update from the rpm to fix yum. As @grumpysysadmin pointed out you can shorten the commands down. @cwgtex contributed that you should install the upgrade using the RPM command making the process even simplier.

To fix things with wordpress you need to restart your http server.

$ service httpd restart

Try again and success!

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

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

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

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

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

The code that really worked for me was:

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

How to Use Order By for Multiple Columns in Laravel 4?

You can do as @rmobis has specified in his answer, [Adding something more into it]

Using order by twice:

MyTable::orderBy('coloumn1', 'DESC')
    ->orderBy('coloumn2', 'ASC')
    ->get();

and the second way to do it is,

Using raw order by:

MyTable::orderByRaw("coloumn1 DESC, coloumn2 ASC");
    ->get();

Both will produce same query as follow,

SELECT * FROM `my_tables` ORDER BY `coloumn1` DESC, `coloumn2` ASC

As @rmobis specified in comment of first answer you can pass like an array to order by column like this,

$myTable->orders = array(
    array('column' => 'coloumn1', 'direction' => 'desc'), 
    array('column' => 'coloumn2', 'direction' => 'asc')
);

one more way to do it is iterate in loop,

$query = DB::table('my_tables');

foreach ($request->get('order_by_columns') as $column => $direction) {
    $query->orderBy($column, $direction);
}

$results = $query->get();

Hope it helps :)

user authentication libraries for node.js?

sweet-auth

A lightweight, zero-configuration user authentication module. It doesn't need a sperate database.

https://www.npmjs.com/package/sweet-auth

It's simple as:

app.get('/private-page', (req, res) => {

    if (req.user.isAuthorized) {
        // user is logged in! send the requested page
        // you can access req.user.email
    }
    else {
        // user not logged in. redirect to login page
    }
})

How can I format a list to print each element on a separate line in python?

Use str.join:

In [27]: mylist = ['10', '12', '14']

In [28]: print '\n'.join(mylist)
10
12
14

What is a difference between unsigned int and signed int in C?

Here is the very nice link which explains the storage of signed and unsigned INT in C -

http://answers.yahoo.com/question/index?qid=20090516032239AAzcX1O

Taken from this above article -

"process called two's complement is used to transform positive numbers into negative numbers. The side effect of this is that the most significant bit is used to tell the computer if the number is positive or negative. If the most significant bit is a 1, then the number is negative. If it's 0, the number is positive."

How to display raw html code in PRE or something like it but without escaping it

xmp is the way to go, i.e.:

<xmp>
  # your code...
</xmp>

Start an Activity with a parameter

Put an int which is your id into the new Intent.

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
Bundle b = new Bundle();
b.putInt("key", 1); //Your id
intent.putExtras(b); //Put your id to your next Intent
startActivity(intent);
finish();

Then grab the id in your new Activity:

Bundle b = getIntent().getExtras();
int value = -1; // or other values
if(b != null)
    value = b.getInt("key");