Programs & Examples On #Accessibility

Accessibility seeks to make an application or website usable by everyone, including people with disabilities such as visual, auditory, ambulatory, or cognitive impairment.

HTML img tag: title attribute vs. alt attribute?

I'd go for both. Title will show a nice tooltip in all browsers and alt will give a description when browsing in a browser with no images.

That said, I'd love to see some stats of how many "surfers" out there going to a "store" to browse merchandise actually have images turned off or are using a browser that doesn't support images. I think the days where 90% of the population is using a 28k modem to connect to the InterWeb is looooong over.

'Missing contentDescription attribute on image' in XML

It is giving you the warning because the image description is not defined.

We can resolve this warning by adding this code below in Strings.xml and activity_main.xml

Add this line below in Strings.xml

<string name="imgDescription">Background Picture</string>
you image will be like that:
<ImageView
        android:id="@+id/imageView2"
        android:lay`enter code hereout_width="0dp"
        android:layout_height="wrap_content"
        android:contentDescription="@string/imgDescription"
        app:layout_editor_absoluteX="0dp"
        app:layout_editor_absoluteY="0dp"
        app:srcCompat="@drawable/background1"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="0dp" />

Also add this line in activity_main.xml

android:contentDescription="@string/imgDescription"

Strings.xml

<resources>
    <string name="app_name">Saini_Browser</string>
    <string name="SainiBrowser">textView2</string>
    <string name="imgDescription">BackGround Picture</string>
</resources>

How to find good looking font color if background color is known?

Similar to @Aaron Digulla's suggestion except that I would suggest a graphics design tool, select the base color, in your case the background color, then adjust the Hue, Saturation and Value. Using this you can create color swatches very easily. Paint.Net is free and I use it all the time for this and also the pay-for-tools will also do this.

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

input type="submit" Vs button tag are they interchangeable?

<button> is newer than <input type="submit">, is more semantic, easy to stylize and support HTML inside of it.

How can you program if you're blind?

I'm blind, and have been programming for about 13 years on Windows, Mac, Linux and DOS, in languages from C/C++, Python, Java, C# and various smaller languages along the way. Though the original question was around configuring the environment, I think it's best answered by looking at how a blind person would use a computer.

Some people use a talking environment, such as T. V. Raman and the Emacspeak environment mentioned in other answers. The more common solution by far is to have a screen reader which runs in the background monitoring OS activity and alerting the user via synthetic speech or a physical braille display (generally showing somewhere from 20 to 80 characters at a time). This then means a blind person can use any accessible application.

So, I personally use Visual Studio 2008 these days, and run it with very few modifications. I turn off certain features like displaying errors as I type since I find this distracting. Prior to joining Microsoft all my development was done in a standard text editor like Notepad, so once again no customisations.

It is possible to configure a screen reader to announce indentation. I personally don't use this, since Visual Studio takes care of this, and C# uses braces. But this would be very important in a language like Python where whitespace matters. Finally, Emacspeak does make use of different voices/pitches to indicate different parts of syntax (keywords, comments, identifiers, etc).

Get a Windows Forms control by name in C#

string name = "the_name_you_know";

Control ctn = this.Controls[name];

ctn.Text = "Example...";

What would be the best method to code heading/title for <ul> or <ol>, Like we have <caption> in <table>?

Would the use of <caption> be allowed?

<ul>
  <caption> Title of List </caption>
  <li> Item 1 </li>
  <li> Item 2 </li>
</ul>

What is the shortcut in IntelliJ IDEA to find method / functions?

CTRL + F12 brings up the File Structure navigation menu, which lets you search for members of the currently open file.

How to change JFrame icon

Just add the following code:

setIconImage(new ImageIcon(PathOfFile).getImage());

Adding headers when using httpClient.GetAsync

You can add whatever headers you need to the HttpClient.

Here is a nice tutorial about it.

This doesn't just reference to POST-requests, you can also use it for GET-requests.

Change CSS class properties with jQuery

You can't change CSS properties directly with jQuery. But you can achieve the same effect in at least two ways.

Dynamically Load CSS from a File

function updateStyleSheet(filename) {
    newstylesheet = "style_" + filename + ".css";

    if ($("#dynamic_css").length == 0) {
        $("head").append("<link>")
        css = $("head").children(":last");

        css.attr({
          id: "dynamic_css",
          rel:  "stylesheet",
          type: "text/css",
          href: newstylesheet
        });
    } else {
        $("#dynamic_css").attr("href",newstylesheet);
    }
}

The example above is copied from:

Dynamically Add a Style Element

$("head").append('<style type="text/css"></style>');
var newStyleElement = $("head").children(':last');
newStyleElement.html('.red{background:green;}');

The example code is copied from this JSFiddle fiddle originally referenced by Alvaro in their comment.

Is <img> element block level or inline level?

For almost all purposes think of them as an inline element with a width set. Basically you are free to dictate how you would like images to display using CSS. I generally set a few image classes like so:

img.center {display:block;margin:0 auto;}

img.left {float:left;margin-right:10px;}

img.right  {float:right;margin-left:10px;}

img.border  {border:1px solid #333;}

How to Return partial view of another controller by controller?

The control searches for a view in the following order:

  • First in shared folder
  • Then in the folder matching the current controller (in your case it's Views/DEF)

As you do not have xxx.cshtml in those locations, it returns a "view not found" error.

Solution: You can use the complete path of your view:

Like

 PartialView("~/views/ABC/XXX.cshtml", zyxmodel);

How to send parameters from a notification-click to an activity?

Please use as PendingIntent while showing notification than it will be resolved.

PendingIntent intent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

Add PendingIntent.FLAG_UPDATE_CURRENT as last field.

Get current AUTO_INCREMENT value for any table

I was looking for the same and ended up by creating a static method inside a Helper class (in my case I named it App\Helpers\Database).

The method

/**
 * Method to get the autoincrement value from a database table
 *
 * @access public
 *
 * @param string $database The database name or configuration in the .env file
 * @param string $table    The table name
 *
 * @return mixed
 */
public static function getAutoIncrementValue($database, $table)
{
    $database ?? env('DB_DATABASE');

    return \DB::select("
        SELECT AUTO_INCREMENT 
        FROM information_schema.TABLES 
        WHERE TABLE_SCHEMA = '" . env('DB_DATABASE') . "' 
        AND TABLE_NAME = '" . $table . "'"
    )[0]->AUTO_INCREMENT;
}

To call the method and get the MySql AUTO_INCREMENT just use the following:

$auto_increment = \App\Helpers\Database::getAutoIncrementValue(env('DB_DATABASE'), 'your_table_name');

Hope it helps.

How to change the plot line color from blue to black?

The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-" for a red line, or by explicitely stating the color argument.

import matplotlib.pyplot as plt

plt.plot([1,2,3], [2,3,1], "r-") # red line
plt.plot([1,2,3], [5,5,3], color="blue") # blue line

plt.show()

See also the plot command's documentation.

In case you already have a line with a certain color, you can change that with the lines2D.set_color() method.

line, = plt.plot([1,2,3], [4,5,3], color="blue")
line.set_color("black")


Setting the color of a line in a pandas plot is also best done at the point of creating the plot:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({ "x" : [1,2,3,5], "y" : [3,5,2,6]})
df.plot("x", "y", color="r") #plot red line

plt.show()

If you want to change this color later on, you can do so by

plt.gca().get_lines()[0].set_color("black")

This will get you the first (possibly the only) line of the current active axes.
In case you have more axes in the plot, you could loop through them

for ax in plt.gcf().axes:
    ax.get_lines()[0].set_color("black")

and if you have more lines you can loop over them as well.

Play an audio file using jQuery when a button is clicked

Which approach?

You can play audio with <audio> tag or <object> or <embed>. Lazy loading(load when you need it) the sound is the best approach if its size is small. You can create the audio element dynamically, when its loaded you can start it with .play() and pause it with .pause().

Things we used

We will use canplay event to detect our file is ready to be played.

There is no .stop() function for audio elements. We can only pause them. And when we want to start from the beginning of the audio file we change its .currentTime. We will use this line in our example audioElement.currentTime = 0;. To achieve .stop() function we first pause the file then reset its time.

We may want to know the length of the audio file and the current playing time. We already learnt .currentTimeabove, to learn its length we use .duration.

Example Guide

  1. When document is ready we created an audio element dynamically
  2. We set its source with the audio we want to play.
  3. We used 'ended' event to start file again.

When the currentTime is equal to its duration audio file will stop playing. Whenever you use play(), it will start from the beginning.

  1. We used timeupdate event to update current time whenever audio .currentTime changes.
  2. We used canplay event to update information when file is ready to be played.
  3. We created buttons to play, pause, restart.

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    var audioElement = document.createElement('audio');_x000D_
    audioElement.setAttribute('src', 'http://www.soundjay.com/misc/sounds/bell-ringing-01.mp3');_x000D_
    _x000D_
    audioElement.addEventListener('ended', function() {_x000D_
        this.play();_x000D_
    }, false);_x000D_
    _x000D_
    audioElement.addEventListener("canplay",function(){_x000D_
        $("#length").text("Duration:" + audioElement.duration + " seconds");_x000D_
        $("#source").text("Source:" + audioElement.src);_x000D_
        $("#status").text("Status: Ready to play").css("color","green");_x000D_
    });_x000D_
    _x000D_
    audioElement.addEventListener("timeupdate",function(){_x000D_
        $("#currentTime").text("Current second:" + audioElement.currentTime);_x000D_
    });_x000D_
    _x000D_
    $('#play').click(function() {_x000D_
        audioElement.play();_x000D_
        $("#status").text("Status: Playing");_x000D_
    });_x000D_
    _x000D_
    $('#pause').click(function() {_x000D_
        audioElement.pause();_x000D_
        $("#status").text("Status: Paused");_x000D_
    });_x000D_
    _x000D_
    $('#restart').click(function() {_x000D_
        audioElement.currentTime = 0;_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<body>_x000D_
    <h2>Sound Information</h2>_x000D_
    <div id="length">Duration:</div>_x000D_
    <div id="source">Source:</div>_x000D_
    <div id="status" style="color:red;">Status: Loading</div>_x000D_
    <hr>_x000D_
    <h2>Control Buttons</h2>_x000D_
    <button id="play">Play</button>_x000D_
    <button id="pause">Pause</button>_x000D_
    <button id="restart">Restart</button>_x000D_
    <hr>_x000D_
    <h2>Playing Information</h2>_x000D_
    <div id="currentTime">0</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to trigger jQuery change event in code

Use That :

$(selector).trigger("change");

OR

$('#id').trigger("click");

OR

$('.class').trigger(event);

Trigger can be any event that javascript support.. Hope it's easy to understandable to all of You.

How do I skip an iteration of a `foreach` loop?

You can use the continue statement.

For example:

foreach(int number in numbers)
{
    if(number < 0)
    {
        continue;
    }
}

Text vertical alignment in WPF TextBlock

You can see my blog post. You can set custom height of Textblock from codebehind. For setting custom height you need to set it inside in a border or stackpanel

http://ciintelligence.blogspot.com/2011/02/wpf-textblock-vertical-alignment-with.html

How do I express "if value is not empty" in the VBA language?

Alexphi's suggestion is good. You can also hard code this by first creating a variable as a Variant and then assigning it to Empty. Then do an if/then with to possibly fill it. If it gets filled, it's not empty, if it doesn't, it remains empty. You check this then with IsEmpty.

Sub TestforEmpty()

    Dim dt As Variant
    dt = Empty

    Dim today As Date
    today = Date
    If today = Date Then
        dt = today
    End If

    If IsEmpty(dt) Then
        MsgBox "It not is today"
    Else
        MsgBox "It is today"
    End If

End Sub

How to render a DateTime object in a Twig template

It depends on the format you want the date to be shown as.

Static date format

If you want to display a static format, which is the same for all locales (for instance ISO 8601 for an Atom feed), you should use Twig's date filter:

{{ game.gameDate|date('Y-m-d\\TH:i:sP') }}

Which will allways return a datetime in the following format:

2014-05-02T08:55:41Z

The format strings accepted by the date filter are the same as you would use for PHP's date() function. (the only difference is that, as far as I know, you can't use the predefined constants which can be used in the PHP date() function)

Localized dates (and times)

However, since you want to render it in the browser, you'll likely want to show it in a human-readable format, localised for the user's language and location. Instead of doing the localization yourself, you can use the Intl Extension for this (which makes use of PHP's IntlDateFormatter). It provides a filter localizeddate which will output the date and time using a localized format.

localizeddate( date_format, time_format [, locale ] )

Arguments for localizeddate:

  • date_format: One of the format strings (see below)
  • time_format: One of the format strings (see below)
  • locale: (optional) Use this to override the configured locale. Leave this argument out to use the default locale, which can be configured in Symfony's configuration.

(there are more, see the docs for the complete list of possible arguments)

For date_format and time_format you can use one of the following strings:

  • 'none' if you don't want to include this element
  • 'short' for the most abbreviated style (12/13/52 or 3:30pm in an English locale)
  • 'medium' for the medium style (Jan 12, 1952 in an English locale)
  • 'long' for the long style (January 12, 1952 or 3:30:32pm in an English locale)
  • 'full' for the completely specified style (Tuesday, April 12, 1952 AD or 3:30:42pm PST in an English locale)

Example

So, for instance, if you want to display the date in a format equivalent to February 6, 2014 at 10:52 AM, use the following line in your Twig template:

{{ game.gameDate|localizeddate('long', 'short') }}

However, if you use a different locale, the result will be localized for that locale:

  • 6 februari 2014 10:52 for the nl locale;
  • 6 février 2014 10:52 for the fr locale;
  • 6. Februar 2014 10:52 for the de locale; etc.

As you can see, localizeddate does not only translate the month names but also uses the local notations. The English notation puts the date after the month, where Dutch, French and German notations put it before the month. English and German month names start with an uppercase letter, whereas Dutch and French month names are lowercase. And German dates have a dot appended.

Installation / setting the locale

Installation instructions for the Intl extension can be found in this seperate answer.

jQuery - Follow the cursor with a DIV

This works for me. Has a nice delayed action going on.

var $mouseX = 0, $mouseY = 0;
var $xp = 0, $yp =0;

$(document).mousemove(function(e){
    $mouseX = e.pageX;
    $mouseY = e.pageY;    
});

var $loop = setInterval(function(){
// change 12 to alter damping higher is slower
$xp += (($mouseX - $xp)/12);
$yp += (($mouseY - $yp)/12);
$("#moving_div").css({left:$xp +'px', top:$yp +'px'});  
}, 30);

Nice and simples

Switching users inside Docker image to a non-root user

You should not use su in a dockerfile, however you should use the USER instruction in the Dockerfile.

At each stage of the Dockerfile build, a new container is created so any change you make to the user will not persist on the next build stage.

For example:

RUN whoami
RUN su test
RUN whoami

This would never say the user would be test as a new container is spawned on the 2nd whoami. The output would be root on both (unless of course you run USER beforehand).

If however you do:

RUN whoami
USER test
RUN whoami

You should see root then test.

Alternatively you can run a command as a different user with sudo with something like

sudo -u test whoami

But it seems better to use the official supported instruction.

Get the element with the highest occurrence in an array

Here is another ES6 way of doing it with O(n) complexity

const result = Object.entries(
    ['pear', 'apple', 'orange', 'apple'].reduce((previous, current) => {
        if (previous[current] === undefined) previous[current] = 1;
        else previous[current]++;
        return previous;
    }, {})).reduce((previous, current) => (current[1] >= previous[1] ? current : previous))[0];
console.log("Max value : " + result);

Add st, nd, rd and th (ordinal) suffix to a number

Here is another option.

_x000D_
_x000D_
function getOrdinalSuffix(day) {_x000D_
        _x000D_
    if(/^[2-3]?1$/.test(day)){_x000D_
     return 'st';_x000D_
    } else if(/^[2-3]?2$/.test(day)){_x000D_
     return 'nd';_x000D_
    } else if(/^[2-3]?3$/.test(day)){_x000D_
     return 'rd';_x000D_
    } else {_x000D_
     return 'th';_x000D_
    }_x000D_
        _x000D_
}_x000D_
    _x000D_
console.log(getOrdinalSuffix('1'));_x000D_
console.log(getOrdinalSuffix('13'));_x000D_
console.log(getOrdinalSuffix('22'));_x000D_
console.log(getOrdinalSuffix('33'));
_x000D_
_x000D_
_x000D_

Notice the exception for the teens? Teens are so akward!

Edit: Forgot about 11th and 12th

Writing a VLOOKUP function in vba

        Public Function VLOOKUP1(ByVal lookup_value As String, ByVal table_array As Range, ByVal col_index_num As Integer) As String
        Dim i As Long

        For i = 1 To table_array.Rows.Count
            If lookup_value = table_array.Cells(table_array.Row + i - 1, 1) Then
                VLOOKUP1 = table_array.Cells(table_array.Row + i - 1, col_index_num)
                Exit For
            End If
        Next i

        End Function

Modifying a file inside a jar

You can use Vim:

vim my.jar

Vim is able to edit compressed text files, given you have unzip in your environment.

How to pass credentials to the Send-MailMessage command for sending emails

I found this blog site: Adam Kahtava
I also found this question: send-mail-via-gmail-with-powershell-v2s-send-mailmessage
The problem is, neither of them addressed both your needs (Attachment with a password), so I did some combination of the two and came up with this:

$EmailTo = "[email protected]"
$EmailFrom = "[email protected]"
$Subject = "Test" 
$Body = "Test Body" 
$SMTPServer = "smtp.gmail.com" 
$filenameAndPath = "C:\CDF.pdf"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("username", "password"); 
$SMTPClient.Send($SMTPMessage)

Since I love to make functions for things, and I need all the practice I can get, I went ahead and wrote this:

Function Send-EMail {
    Param (
        [Parameter(`
            Mandatory=$true)]
        [String]$EmailTo,
        [Parameter(`
            Mandatory=$true)]
        [String]$Subject,
        [Parameter(`
            Mandatory=$true)]
        [String]$Body,
        [Parameter(`
            Mandatory=$true)]
        [String]$EmailFrom="[email protected]",  #This gives a default value to the $EmailFrom command
        [Parameter(`
            mandatory=$false)]
        [String]$attachment,
        [Parameter(`
            mandatory=$true)]
        [String]$Password
    )

        $SMTPServer = "smtp.gmail.com" 
        $SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
        if ($attachment -ne $null) {
            $SMTPattachment = New-Object System.Net.Mail.Attachment($attachment)
            $SMTPMessage.Attachments.Add($SMTPattachment)
        }
        $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
        $SMTPClient.EnableSsl = $true 
        $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom.Split("@")[0], $Password); 
        $SMTPClient.Send($SMTPMessage)
        Remove-Variable -Name SMTPClient
        Remove-Variable -Name Password

} #End Function Send-EMail

To call it, just use this command:

Send-EMail -EmailTo "[email protected]" -Body "Test Body" -Subject "Test Subject" -attachment "C:\cdf.pdf" -password "Passowrd"

I know it's not secure putting the password in plainly like that. I'll see if I can come up with something more secure and update later, but at least this should get you what you need to get started. Have a great week!

Edit: Added $EmailFrom based on JuanPablo's comment

Edit: SMTP was spelled STMP in the attachments.

How to style the <option> with only CSS?

I've played around with select items before and without overriding the functionality with JavaScript, I don't think it's possible in Chrome. Whether you use a plugin or write your own code, CSS only is a no go for Chrome/Safari and as you said, Firefox is better at dealing with it.

How to write the code for the back button?

In my application,above javascript function didnt work,because i had many procrosses inside one page.so following code worked for me hope it helps you guys.

  function redirection()
        {
           <?php $send=$_SERVER['HTTP_REFERER'];?> 
            var redirect_to="<?php echo $send;?>";             
            window.location = redirect_to;

        }

how to remove the first two columns in a file using shell (awk, sed, whatever)

You can do it with cut:

cut -d " " -f 3- input_filename > output_filename

Explanation:

  • cut: invoke the cut command
  • -d " ": use a single space as the delimiter (cut uses TAB by default)
  • -f: specify fields to keep
  • 3-: all the fields starting with field 3
  • input_filename: use this file as the input
  • > output_filename: write the output to this file.

Alternatively, you can do it with awk:

awk '{$1=""; $2=""; sub("  ", " "); print}' input_filename > output_filename

Explanation:

  • awk: invoke the awk command
  • $1=""; $2="";: set field 1 and 2 to the empty string
  • sub(...);: clean up the output fields because fields 1 & 2 will still be delimited by " "
  • print: print the modified line
  • input_filename > output_filename: same as above.

How can I add a variable to console.log?

It depends on what you want.

console.log("story "+name+" story") will concatenate the strings together and print that. For me, I use this because it is easier to see what is going on.

Using console.log("story",name,"story") is similar to concatenation however, it seems to run something like this:

 var text = ["story", name, "story"];
 console.log(text.join(" "));

This is pushing all of the items in the array together, separated by a space: .join(" ")

In laymans terms, what does 'static' mean in Java?

In very laymen terms the class is a mold and the object is the copy made with that mold. Static belong to the mold and can be accessed directly without making any copies, hence the example above

New og:image size for Facebook share?

According to facebooks best practices it is like this (2016)

Image Sizes

Use images that are at least 1200 x 630 pixels for the best display on high resolution devices. At the minimum, you should use images that are 600 x 315 pixels to display link page posts with larger images. Images can be up to 8MB in size. enter image description here

Small Images

If your image is smaller than 600 x 315 px, it will still display in the link page post, but the size will be much smaller. enter image description here

We've also redesigned link page posts so that the aspect ratio for images is the same across desktop and mobile News Feed. Try to keep your images as close to 1.91:1 aspect ratio as possible to display the full image in News Feed without any cropping.

Minimum Image Size

The minimum image size is 200 x 200 pixels. If you try to use an image smaller than this you will see an error in the Sharing Debugger.

Game Apps Images

There are two different image sizes to use for game apps:

Open Graph Stories Images appear in a square format. Image ratios for these apps should be 600 x 600 px. Non-open Graph Stories Images appear in a rectangular format. You should use a 1.91:1 image ratio, such as 600 x 314 px.

What is the correct way to check for string equality in JavaScript?

what led me to this question is the padding and white-spaces

check my case

 if (title === "LastName")
      doSomething();

and title was " LastName"

enter image description here

so maybe you have to use trim function like this

var title = $(this).text().trim();

SQlite - Android - Foreign key syntax

As you can see in the error description your table contains the columns (_id, tast_title, notes, reminder_date_time) and you are trying to add a foreign key from a column "taskCat" but it does not exist in your table!

Setting and getting localStorage with jQuery

You said you are attempting to get the text from a div and store it on local storage.

Please Note: Text and Html are different. In the question you mentioned text. html() will return Html content like <a>example</a>. if you want to get Text content then you have to use text() instead of html() then the result will be example instead of <a>example<a>. Anyway, I am using your terminology let it be Text.

Step 1: get the text from div.

what you did is not get the text from div but set the text to a div.

$('#test').html("Test"); 

is actually setting text to div and the output will be a jQuery object. That is why it sets it as [object Object].

To get the text you have to write like this
$('#test').html();

This will return a string not an object so the result will be Test in your case.

Step 2: set it to local storage.

Your approach is correct and you can write it as

localStorage.key=value

But the preferred approach is

localStorage.setItem(key,value); to set

localStorage.getItem(key); to get.

key and value must be strings.

so in your context code will become

$('#test').html("Test");
localStorage.content = $('#test').html();
$('#test').html(localStorage.content);

But I don't find any meaning in your code. Because you want to get the text from div and store it on local storage. And again you are reading the same from local storage and set to div. just like a=10; b=a; a=b;

If you are facing any other problems please update your question accordingly.

iPad/iPhone hover problem causes the user to double click a link

I had the following problems with the existing solutions, and found something that seems to solve all of them. This assumes you're aiming for something cross browser, cross device, and don't want device sniffing.

The problems this solves

Using just touchstart or touchend:

  • Causes the event to fire when people are trying to scroll past the content and just happened to have their finger over this element when they starting swiping - triggering the action unexpectedly.
  • May cause the event to fire on longpress, similar to right click on desktop. For example, if your click event goes to URL X, and the user longpresses to open X in a new tab, the user will be confused to find X open in both tabs. On some browsers (e.g. iPhone) it may even prevent the long press menu from appearing.

Triggering mouseover events on touchstart and mouseout on touchmove has less serious consequences, but does interfere with the usual browser behaviour, for example:

  • A long press would trigger a mouseover that never ends.
  • Many Android browsers treat the location of the finger on touchstart like a mouseover, which is mouseouted on the next touchstart. One way to see mouseover content in Android is therefore to touch the area of interest and wiggle your finger, scrolling the page slightly. Treating touchmove as mouseout breaks this.

The solution

In theory, you could just add a flag with touchmove, but iPhones trigger touchmove even if there's no movement. In theory, you could just compare the touchstart and touchend event pageX and pageY but on iPhones, there's no touchend pageX or pageY.

So unfortunately to cover all bases it does end up a little more complicated.

$el.on('touchstart', function(e){
    $el.data('tstartE', e);
    if(event.originalEvent.targetTouches){
        // store values, not reference, since touch obj will change
        var touch = e.originalEvent.targetTouches[0];
        $el.data('tstartT',{ clientX: touch.clientX, clientY: touch.clientY } );
    }
});
$el.on('touchmove', function(e){
    if(event.originalEvent.targetTouches){
        $el.data('tstartM', event.originalEvent.targetTouches[0]);
    }
});

$el.on('click touchend', function(e){
    var oldE = $el.data('tstartE');
    if( oldE && oldE.timeStamp + 1000 < e.timeStamp ) {
        $el.data('tstartE',false);
        return;
    }
    if( $el.data('iosTouchM') && $el.data('tstartT') ){
        var start = $el.data('tstartT'), end = $el.data('tstartM');
        if( start.clientX != end.clientX || start.clientY != end.clientY ){
            $el.data('tstartT', false);
            $el.data('tstartM', false);
            $el.data('tstartE',false);
            return;
        }
    }
    $el.data('tstartE',false);

In theory, there are ways to get the exact time used for a longpress instead of just using 1000 as an approximation, but in practice it's not that simple and it's best to use a reasonable proxy.

Google Play Services Library update and missing symbol @integer/google_play_services_version

The problem for me was that the library project and the project using play services were in different directories. So just:

  • 1.Add the files to the same workspace then remove the library.
  • 2.Restart eclipse
  • 3.Add the library project again
  • 4.Clear

How to include JavaScript file or library in Chrome console?

var el = document.createElement("script"),
loaded = false;
el.onload = el.onreadystatechange = function () {
  if ((el.readyState && el.readyState !== "complete" && el.readyState !== "loaded") || loaded) {
    return false;
  }
  el.onload = el.onreadystatechange = null;
  loaded = true;
  // done!
};
el.async = true;
el.src = path;
var hhead = document.getElementsByTagName('head')[0];
hhead.insertBefore(el, hhead.firstChild);

DB2 Timestamp select statement

@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000

If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:

...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'

or

...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06' 
   AND usagetime < '2012-09-03 08:03:07'

How do you get the magnitude of a vector in Numpy?

Yet another alternative is to use the einsum function in numpy for either arrays:

In [1]: import numpy as np

In [2]: a = np.arange(1200.0).reshape((-1,3))

In [3]: %timeit [np.linalg.norm(x) for x in a]
100 loops, best of 3: 3.86 ms per loop

In [4]: %timeit np.sqrt((a*a).sum(axis=1))
100000 loops, best of 3: 15.6 µs per loop

In [5]: %timeit np.sqrt(np.einsum('ij,ij->i',a,a))
100000 loops, best of 3: 8.71 µs per loop

or vectors:

In [5]: a = np.arange(100000)

In [6]: %timeit np.sqrt(a.dot(a))
10000 loops, best of 3: 80.8 µs per loop

In [7]: %timeit np.sqrt(np.einsum('i,i', a, a))
10000 loops, best of 3: 60.6 µs per loop

There does, however, seem to be some overhead associated with calling it that may make it slower with small inputs:

In [2]: a = np.arange(100)

In [3]: %timeit np.sqrt(a.dot(a))
100000 loops, best of 3: 3.73 µs per loop

In [4]: %timeit np.sqrt(np.einsum('i,i', a, a))
100000 loops, best of 3: 4.68 µs per loop

Escape text for HTML

For those in the future looking for a simple way to do this in Razor pages, use the following:

In .cshtml:

@Html.Raw(Html.Encode("<span>blah<span>"))

In .cshtml.cs:

string rawHtml = Html.Raw(Html.Encode("<span>blah<span>"));

How to format date with hours, minutes and seconds when using jQuery UI Datepicker?

I added this code

<input class="form-control input-small hasDatepicker" id="datepicker6" name="expire_date" type="text" value="2018-03-17 00:00:00">

<script src="/assets/js/datepicker/bootstrap-datepicker.js"></script>
<script>
        $(document).ready(function() {
            $("#datepicker6").datepicker({
                isRTL: true,
                dateFormat: "yy/mm/dd 23:59:59",
                changeMonth: true,
                changeYear: true

            });
        });
</script>

python: how to get information about a function?

You can use pydoc.

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

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

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

For more information python -m pydoc

Searching for Text within Oracle Stored Procedures

If you use UPPER(text), the like '%lah%' will always return zero results. Use '%LAH%'.

Reading tab-delimited file with Pandas - works on Windows, but not on Mac

Another option would be to add engine='python' to the command pandas.read_csv(filename, sep='\t', engine='python')

"Please try running this command again as Root/Administrator" error when trying to install LESS

I also got the problem. This is what I did:

  1. Uninstalled nodeJs from Control Panel > Uninstall a program
  2. There are 2 folders in users//appData/roaming --> npm folder and npm-cache folder. Delete both of these.

Now, go to nodeJS site, and install again. Select 2nd option in installation option (ie npm package). Install it. You problem must be solved by now.

WebApi's {"message":"an error has occurred"} on IIS7, not in IIS Express

In case this helps anyone:

I had a similar issue, and following Nates instructions I added:

<system.web>
     <customErrors mode="Off"/>
 </system.web>

This showed me more information about the error:

"ExceptionMessage": "Unable to load the specified metadata resource.", "ExceptionType": "System.Data.Entity.Core.MetadataException", "StackTrace": " at System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderCompositeResource.LoadResources(...

This is when I remembered that I had moved the edmx file to a different location and had forgotten to change the connectionstrings node in the config (connectionsstrings node was placed in a seperate file using "configSource", but that's another story).

Is there a jQuery unfocus method?

I like the following approach as it works for all situations:

$(':focus').blur();

how to get last insert id after insert query in codeigniter active record

Try this

function add_post($post_data){
   $this->db->insert('posts', $post_data);
   $insert_id = $this->db->insert_id();

   return  $insert_id;
}

In case of multiple inserts you could use

$this->db->trans_start();
$this->db->trans_complete();

C# testing to see if a string is an integer?

It is possible to try this as well:

    var ix=Convert.ToInt32(x);
    if (x==ix) //if this condition is met, then x is integer
    {
        //your code here
    }

php hide ALL errors

Per the PHP documentation, put this at the top of your php scripts:

<?php error_reporting(0); ?>

http://php.net/manual/en/function.error-reporting.php

If you do hide your errors, which you should in a live environment, make sure that you are logging any errors somewhere. How to log errors and warnings into a file? Otherwise, things will go wrong and you will have no idea why.

matching query does not exist Error in Django

I also had this problem. It was caused by the development server not deleting the django session after a debug abort in Aptana, with subsequent database deletion. (Meaning the id of a non-existent database record was still present in the session the next time the development server started)

To resolve this during development, I used

request.session.flush()

Bootstrap: How do I identify the Bootstrap version?

That comment looks like it is a custom version of Bootstrap v2.3.3, here is the default header in the .css, notice the last comment line:

/*!
 * Bootstrap v2.3.2
 *
 * Copyright 2013 Twitter, Inc
 * Licensed under the Apache License v2.0
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Designed and built with all the love in the world by @mdo and @fat.
 */

What are you trying to accomplish? If it's customization then you have a set of files to work with though that seems like a bad idea. Otherwise, I would suggest going with the full build of v4.1.x since that is the current release.

Gradients in Internet Explorer 9

The best cross-browser solution is

background: #fff;
background: -moz-linear-gradient(#fff, #000);
background: -webkit-linear-gradient(#fff, #000);
background: -o-linear-gradient(#fff, #000);
background: -ms-linear-gradient(#fff, #000);/*For IE10*/
background: linear-gradient(#fff, #000);
filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#ffffff', endColorstr='#000000');/*For IE7-8-9*/ 
height: 1%;/*For IE7*/ 

Unique random string generation

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

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

Guid.NewGuid().ToString("n");

How to set host_key_checking=false in ansible inventory file?

I could not use:

ansible_ssh_common_args='-o StrictHostKeyChecking=no'

in inventory file. It seems ansible does not consider this option in my case (ansible 2.0.1.0 from pip in ubuntu 14.04)

I decided to use:

server ansible_host=192.168.1.1 ansible_ssh_common_args= '-o UserKnownHostsFile=/dev/null'

It helped me.

Also you could set this variable in group instead for each host:

[servers_group:vars]
ansible_ssh_common_args='-o UserKnownHostsFile=/dev/null'

Detect Safari browser

I don't know why the OP wanted to detect Safari, but in the rare case you need browser sniffing nowadays it's problably more important to detect the render engine than the name of the browser. For example on iOS all browsers use the Safari/Webkit engine, so it's pointless to get "chrome" or "firefox" as browser name if the underlying renderer is in fact Safari/Webkit. I haven't tested this code with old browsers but it works with everything fairly recent on Android, iOS, OS X, Windows and Linux.

<script>
    let browserName = "";

    if(navigator.vendor.match(/google/i)) {
        browserName = 'chrome/blink';
    }
    else if(navigator.vendor.match(/apple/i)) {
        browserName = 'safari/webkit';
    }
    else if(navigator.userAgent.match(/firefox\//i)) {
        browserName = 'firefox/gecko';
    }
    else if(navigator.userAgent.match(/edge\//i)) {
        browserName = 'edge/edgehtml';
    }
    else if(navigator.userAgent.match(/trident\//i)) {
        browserName = 'ie/trident';
    }
    else
    {
        browserName = navigator.userAgent + "\n" + navigator.vendor;
    }
    alert(browserName);
</script>

To clarify:

  • All browsers under iOS will be reported as "safari/webkit"
  • All browsers under Android but Firefox will be reported as "chrome/blink"
  • Chrome, Opera, Blisk, Vivaldi etc. will all be reported as "chrome/blink" under Windows, OS X or Linux

window.onload vs $(document).ready()

Document.ready (a jQuery event) will fire when all the elements are in place, and they can be referenced in the JavaScript code, but the content is not necessarily loaded. Document.ready executes when the HTML document is loaded.

$(document).ready(function() {

    // Code to be executed
    alert("Document is ready");
});

The window.load however will wait for the page to be fully loaded. This includes inner frames, images, etc.

$(window).load(function() {

    //Fires when the page is loaded completely
    alert("window is loaded");
});

How can I subset rows in a data frame in R based on a vector of values?

This will give you what you want:

eg2011cleaned <- eg2011[!eg2011$ID %in% bg2011missingFromBeg, ]

The error in your second attempt is because you forgot the ,

In general, for convenience, the specification object[index] subsets columns for a 2d object. If you want to subset rows and keep all columns you have to use the specification object[index_rows, index_columns], while index_cols can be left blank, which will use all columns by default.

However, you still need to include the , to indicate that you want to get a subset of rows instead of a subset of columns.

what is Ljava.lang.String;@

Ljava.lang.String;@ is returned where you used string arrays as strings. Employee.getSelectCancel() does not seem to return a String[]

Bootstrap push div content to new line

If your your list is dynamically generated with unknown number and your target is to always have last div in a new line set last div class to "col-xl-12" and remove other classes so it will always take a full row.

This is a copy of your code corrected so that last div always occupy a full row (I although removed unnecessary classes).

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="grid">_x000D_
  <div class="row">_x000D_
    <div class="col-sm-3">Under me should be a DIV</div>_x000D_
    <div class="col-md-6 col-sm-5">Under me should be a DIV</div>_x000D_
    <div class="col-xl-12">I am the last DIV and I always take a full row for my self!!</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Can not find module “@angular-devkit/build-angular”

Another issue could be with your dev-dependencies. Please check if they have been installed properly (check if they are availabe in the node_modules folder)

If not then a quick fix would be:

npm i --only=dev

Or check how your npm settings are regarding prod:

npm config get production

In case they are set to true - change them to false:

npm config set -g production false

and setup a new angular project.

Found that hint here: https://github.com/angular/angular-cli/issues/10661 (ken107 and lichunbin814)

Hope that helps.

Create a temporary table in a SELECT statement without a separate CREATE TABLE

In addition to psparrow's answer if you need to add an index to your temporary table do:

CREATE TEMPORARY TABLE IF NOT EXISTS 
  temp_table ( INDEX(col_2) ) 
ENGINE=MyISAM 
AS (
  SELECT col_1, coll_2, coll_3
  FROM mytable
)

It also works with PRIMARY KEY

Unbound classpath container in Eclipse

Given the FAQ, sharing a project file seems have to have advantages and is even recommended practice for Java projects (personally, I would not do that).

Maybe some of the following work for you:

  1. Edit the project's properties (right-click project, Properties, Java Build Path, Libraries, Remove and Add Library.
  2. Import the project's files without the "project file"
  3. Install JDK1.5 from http://java.sun.com/javase/downloads/index_jdk5.jsp and see whether you can fix paths

internet explorer 10 - how to apply grayscale filter?

Use this jQuery plugin https://gianlucaguarini.github.io/jQuery.BlackAndWhite/

That seems to be the only one cross-browser solution. Plus it has a nice fade in and fade out effect.

$('.bwWrapper').BlackAndWhite({
    hoverEffect : true, // default true
    // set the path to BnWWorker.js for a superfast implementation
    webworkerPath : false,
    // to invert the hover effect
    invertHoverEffect: false,
    // this option works only on the modern browsers ( on IE lower than 9 it remains always 1)
    intensity:1,
    speed: { //this property could also be just speed: value for both fadeIn and fadeOut
        fadeIn: 200, // 200ms for fadeIn animations
        fadeOut: 800 // 800ms for fadeOut animations
    },
    onImageReady:function(img) {
        // this callback gets executed anytime an image is converted
    }
});

DataTrigger where value is NOT null?

You can use a converter or create new property in your ViewModel like that:

public bool CanDoIt
{
    get
    {
        return !string.IsNullOrEmpty(SomeField);
    }
}

and use it:

<DataTrigger Binding="{Binding SomeField}" Value="{Binding CanDoIt}">

Passing Variable through JavaScript from one html page to another page

Your best option here, is to use the Query String to 'send' the value.

how to get query string value using javascript

  • So page 1 redirects to page2.html?someValue=ABC
  • Page 2 can then read the query string and specifically the key 'someValue'

If this is anything more than a learning exercise you may want to consider the security implications of this though.

Global variables wont help you here as once the page is re-loaded they are destroyed.

SQL Server IIF vs CASE

IIF is the same as CASE WHEN <Condition> THEN <true part> ELSE <false part> END. The query plan will be the same. It is, perhaps, "syntactical sugar" as initially implemented.

CASE is portable across all SQL platforms whereas IIF is SQL SERVER 2012+ specific.

Failed to connect to mailserver at "localhost" port 25

First of all, you aren't forced to use an SMTP on your localhost, if you change that localhost entry into the DNS name of the MTA from your ISP provider (who will let you relay mail) it will work right away, so no messing about with your own email service. Just try to use your providers SMTP servers, it will work right away.

Apache - MySQL Service detected with wrong path. / Ports already in use

  • Ok it's very easy actually to solve this...most of you who are presented with this problem probably don't even realize you don't have the full software yet installed :) I tried looking online with little success except some1 mentioned you need to look for those services running already. Forexample problem with filezilla you look in task manager for filezilla and you stop the process then you click the X in the xampp control pannel to install filezilla and then click run and it should start the service normally showing you a green lite with a check mark.

  • Same goes for mysql issues.

  • As for the apache problem, it usualy is a problem with the port being overtaken by skype or some other program, but you can find info how to solve that on the net easily :)

Android Studio does not show layout preview

Switch from Blank Activity and use Empty Activity. Change your theme to for example Holo.Light.NoActionBar.

Unlike Blank, Empty is more stripped down thus you may need to add some stuff yourself. Such as add the 2 Override methods onCreateOptionsMenu and onOptionsItemSelected yourself if you need to manipulate controls on the ActionBar and such. Otherwise, no other significant difference.

Getting and removing the first character of a string

Another alternative is to use capturing sub-expressions with the regular expression functions regmatches and regexec.

# the original example
x <- 'hello stackoverflow'

# grab the substrings
myStrings <- regmatches(x, regexec('(^.)(.*)', x))

This returns the entire string, the first character, and the "popped" result in a list of length 1.

myStrings
[[1]]
[1] "hello stackoverflow" "h"                   "ello stackoverflow" 

which is equivalent to list(c(x, substr(x, 1, 1), substr(x, 2, nchar(x)))). That is, it contains the super set of the desired elements as well as the full string.


Adding sapply will allow this method to work for a character vector of length > 1.

# a slightly more interesting example
xx <- c('hello stackoverflow', 'right back', 'at yah')

# grab the substrings
myStrings <- regmatches(x, regexec('(^.)(.*)', xx))

This returns a list with the matched full string as the first element and the matching subexpressions captured by () as the following elements. So in the regular expression '(^.)(.*)', (^.) matches the first character and (.*) matches the remaining characters.

myStrings
[[1]]
[1] "hello stackoverflow" "h"                   "ello stackoverflow" 

[[2]]
[1] "right back" "r"          "ight back" 

[[3]]
[1] "at yah" "a"      "t yah" 

Now, we can use the trusty sapply + [ method to pull out the desired substrings.

myFirstStrings <- sapply(myStrings, "[", 2)
myFirstStrings
[1] "h" "r" "a"
mySecondStrings <- sapply(myStrings, "[", 3)
mySecondStrings
[1] "ello stackoverflow" "ight back"          "t yah"

NodeJS / Express: what is "app.use"?

app.use is woks as middleware for app request. syntax

app.use('pass request format',function which contain request response onject)

example

app.use('/',funtion(req,res){
 console.log(all request pass through it);
// here u can check your authentication and other activities.
})

also you can use it in case of routing your request.

app.use('/', roting_object);

recursively use scp but excluding some folders

Although scp supports recursive directory copying with the -r option, it does not support filtering of the files. There are several ways to accomplish your task, but I would probably rely on find, xargs, tar, and ssh instead of scp.

find . -type d -wholename '*bench*/image' \
| xargs tar cf - \
| ssh user@remote tar xf - -C /my/dir

The rsync solution can be made to work, but you are missing some arguments. rsync also needs the r switch to recurse into subdirectories. Also, if you want the same security of scp, you need to do the transfer under ssh. Something like:

rsync -avr -e "ssh -l user" --exclude 'fl_*' ./bench* remote:/my/dir

Check if a class is derived from a generic class

(Reposted due to a massive rewrite)

JaredPar's code answer is fantastic, but I have a tip that would make it unnecessary if your generic types are not based on value type parameters. I was hung up on why the "is" operator would not work, so I have also documented the results of my experimentation for future reference. Please enhance this answer to further enhance its clarity.

TIP:

If you make certain that your GenericClass implementation inherits from an abstract non-generic base class such as GenericClassBase, you could ask the same question without any trouble at all like this:

typeof(Test).IsSubclassOf(typeof(GenericClassBase))

IsSubclassOf()

My testing indicates that IsSubclassOf() does not work on parameterless generic types such as

typeof(GenericClass<>)

whereas it will work with

typeof(GenericClass<SomeType>)

Therefore the following code will work for any derivation of GenericClass<>, assuming you are willing to test based on SomeType:

typeof(Test).IsSubclassOf(typeof(GenericClass<SomeType>))

The only time I can imagine that you would want to test by GenericClass<> is in a plug-in framework scenario.


Thoughts on the "is" operator

At design-time C# does not allow the use of parameterless generics because they are essentially not a complete CLR type at that point. Therefore, you must declare generic variables with parameters, and that is why the "is" operator is so powerful for working with objects. Incidentally, the "is" operator also can not evaluate parameterless generic types.

The "is" operator will test the entire inheritance chain, including interfaces.

So, given an instance of any object, the following method will do the trick:

bool IsTypeof<T>(object t)
{
    return (t is T);
}

This is sort of redundant, but I figured I would go ahead and visualize it for everybody.

Given

var t = new Test();

The following lines of code would return true:

bool test1 = IsTypeof<GenericInterface<SomeType>>(t);

bool test2 = IsTypeof<GenericClass<SomeType>>(t);

bool test3 = IsTypeof<Test>(t);

On the other hand, if you want something specific to GenericClass, you could make it more specific, I suppose, like this:

bool IsTypeofGenericClass<SomeType>(object t)
{
    return (t is GenericClass<SomeType>);
}

Then you would test like this:

bool test1 = IsTypeofGenericClass<SomeType>(t);

How to print color in console using System.out.println?

I created a library called JColor that works on Linux, macOS, and Windows 10.

It uses the ANSI codes mentioned by WhiteFang, but abstracts them using words instead of codes which is more intuitive. Recently I added support for 8 and 24 bit colors

Choose your format, colorize it, and print it:

System.out.println(colorize("Green text on blue", GREEN_TEXT(), BLUE_BACK()));

You can also define a format once, and reuse it several times:

AnsiFormat fWarning = new AnsiFormat(RED_TEXT(), YELLOW_BACK(), BOLD());
System.out.println(colorize("Something bad happened!", fWarning));

Head over to JColor github repository for some examples.

Print a list of all installed node.js modules

in any os

npm -g list

and thats it

How do I send email with JavaScript without opening the mail client?

You need a server-side support to achieve this. Basically your form should be posted (AJAX is fine as well) to the server and that server should connect via SMTP to some mail provider and send that e-mail.

Even if it was possible to send e-mails directly using JavaScript (that is from users computer), the user would still have to connect to some SMTP server (like gmail.com), provide SMTP credentials, etc. This is normally handled on the server-side (in your application), which knows these credentials.

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

I'm not sure for JPA 1.0 but you can pass a Collection in JPA 2.0:

String qlString = "select item from Item item where item.name IN :names"; 
Query q = em.createQuery(qlString, Item.class);

List<String> names = Arrays.asList("foo", "bar");

q.setParameter("names", names);
List<Item> actual = q.getResultList();

assertNotNull(actual);
assertEquals(2, actual.size());

Tested with EclipseLInk. With Hibernate 3.5.1, you'll need to surround the parameter with parenthesis:

String qlString = "select item from Item item where item.name IN (:names)";

But this is a bug, the JPQL query in the previous sample is valid JPQL. See HHH-5126.

Disabling Minimize & Maximize On WinForm?

Right Click the form you want to hide them on, choose Controls -> Properties.

In Properties, set

  • Control Box -> False
  • Minimize Box -> False
  • Maximize Box -> False

You'll do this in the designer.

document.getElementByID is not a function

It worked like this for me:

document.getElementById("theElementID").setAttribute("src", source);
document.getElementById("task-text").innerHTML = "";

Change the

getElementById("theElementID")

for your element locator (name, css, xpath...)

How to get file path from OpenFileDialog and FolderBrowserDialog?

I am sorry if i am late to reply here but i just thought i should throw in a much simpler solution for the OpenDialog.

OpenDialog ofd = new OpenDialog();
var fullPathIncludingFileName = ofd.Filename; //returns the full path including the filename
var fullPathExcludingFileName = ofd.Filename.Replace(ofd.SafeFileName, "");//will remove the filename from the full path

I have not yet used a FolderBrowserDialog before so i will trust my fellow coders's take on this. I hope this helps.

How to calculate distance from Wifi router using Signal Strength?

Distance (km) = 10^((Free Space Path Loss – 92.45 – 20log10(f))/20)

How to implement the --verbose or -v option into a script?

@kindall's solution does not work with my Python version 3.5. @styles correctly states in his comment that the reason is the additional optional keywords argument. Hence my slightly refined version for Python 3 looks like this:

if VERBOSE:
    def verboseprint(*args, **kwargs):
        print(*args, **kwargs)
else:
    verboseprint = lambda *a, **k: None # do-nothing function

How can I format date by locale in Java?

Joda-Time

Using the Joda-Time 2.4 library. The DateTimeFormat class is a factory of DateTimeFormatter formatters. That class offers a forStyle method to access formatters appropriate to a Locale.

DateTimeFormatter formatter = DateTimeFormat.forStyle( "MM" ).withLocale( Java.util.Locale.CANADA_FRENCH );
String output = formatter.print( DateTime.now( DateTimeZone.forID( "America/Montreal" ) ) );

The argument with two letters specifies a format for the date portion and the time portion. Specify a character of 'S' for short style, 'M' for medium, 'L' for long, and 'F' for full. A date or time may be ommitted by specifying a style character '-' HYPHEN.

Note that we specified both a Locale and a time zone. Some people confuse the two.

  • A time zone is an offset from UTC and a set of rules for Daylight Saving Time and other anomalies along with their historical changes.
  • A Locale is a human language such as Français, plus a country code such as Canada that represents cultural practices including formatting of date-time strings.

We need all those pieces to properly generate a string representation of a date-time value.

How to get a jqGrid cell value when editing

you can use this directly....

onCellSelect: function(rowid,iCol,cellcontent,e) {
            alert(cellcontent);
        }

How to remove all namespaces from XML with C#?

For attributes to work the for loop for adding attribute should go after recursion, also need to check if IsNamespaceDeclaration:

private static XElement RemoveAllNamespaces(XElement xmlDocument)
{
    XElement xElement;

    if (!xmlDocument.HasElements)
    {
        xElement = new XElement(xmlDocument.Name.LocalName) { Value = xmlDocument.Value };
    }
    else
    {
        xElement = new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(RemoveAllNamespaces));
    }

    foreach (var attribute in xmlDocument.Attributes())
    {
        if (!attribute.IsNamespaceDeclaration)
        {
            xElement.Add(attribute);
        }
    }

    return xElement;
}

jquery, selector for class within id

Also $( "#container" ).find( "div.robotarm" );
is equal to: $( "div.robotarm", "#container" )

Safe String to BigDecimal conversion

The code could be cleaner, but this seems to do the trick for different locales.

import java.math.BigDecimal;
import java.text.DecimalFormatSymbols;
import java.util.Locale;


public class Main
{
    public static void main(String[] args)
    {
        final BigDecimal numberA;
        final BigDecimal numberB;

        numberA = stringToBigDecimal("1,000,000,000.999999999999999", Locale.CANADA);
        numberB = stringToBigDecimal("1.000.000.000,999999999999999", Locale.GERMANY);
        System.out.println(numberA);
        System.out.println(numberB);
    }

    private static BigDecimal stringToBigDecimal(final String formattedString,
                                                 final Locale locale)
    {
        final DecimalFormatSymbols symbols;
        final char                 groupSeparatorChar;
        final String               groupSeparator;
        final char                 decimalSeparatorChar;
        final String               decimalSeparator;
        String                     fixedString;
        final BigDecimal           number;

        symbols              = new DecimalFormatSymbols(locale);
        groupSeparatorChar   = symbols.getGroupingSeparator();
        decimalSeparatorChar = symbols.getDecimalSeparator();

        if(groupSeparatorChar == '.')
        {
            groupSeparator = "\\" + groupSeparatorChar;
        }
        else
        {
            groupSeparator = Character.toString(groupSeparatorChar);
        }

        if(decimalSeparatorChar == '.')
        {
            decimalSeparator = "\\" + decimalSeparatorChar;
        }
        else
        {
            decimalSeparator = Character.toString(decimalSeparatorChar);
        }

        fixedString = formattedString.replaceAll(groupSeparator , "");
        fixedString = fixedString.replaceAll(decimalSeparator , ".");
        number      = new BigDecimal(fixedString);

        return (number);
    }
}

Best way to increase heap size in catalina.bat file

If you look in your installation's bin directory you will see catalina.sh or .bat scripts. If you look in these you will see that they run a setenv.sh or setenv.bat script respectively, if it exists, to set environment variables. The relevant environment variables are described in the comments at the top of catalina.sh/bat. To use them create, for example, a file $CATALINA_HOME/bin/setenv.sh with contents

export JAVA_OPTS="-server -Xmx512m"

For Windows you will need, in setenv.bat, something like

set JAVA_OPTS=-server -Xmx768m

Original answer here

After you run startup.bat, you can easily confirm the correct settings have been applied provided you have turned @echo on somewhere in your catatlina.bat file (a good place could be immediately after echo Using CLASSPATH: "%CLASSPATH%"):

enter image description here

Fake "click" to activate an onclick method

For IE there is fireEvent() method. Don't know if that works for other browsers.

Git ignore local file changes

git pull wants you to either remove or save your current work so that the merge it triggers doesn't cause conflicts with your uncommitted work. Note that you should only need to remove/save untracked files if the changes you're pulling create files in the same locations as your local uncommitted files.

Remove your uncommitted changes

Tracked files

git checkout -f

Untracked files

git clean -fd

Save your changes for later

Tracked files

git stash

Tracked files and untracked files

git stash -u

Reapply your latest stash after git pull:

git stash pop

What is an example of the Liskov Substitution Principle?

Substitutability is a principle in object-oriented programming stating that, in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S

Let's do a simple example in Java:

Bad example

public class Bird{
    public void fly(){}
}
public class Duck extends Bird{}

The duck can fly because it is a bird, but what about this:

public class Ostrich extends Bird{}

Ostrich is a bird, but it can't fly, Ostrich class is a subtype of class Bird, but it shouldn't be able to use the fly method, that means we are breaking the LSP principle.

Good example

public class Bird{}
public class FlyingBirds extends Bird{
    public void fly(){}
}
public class Duck extends FlyingBirds{}
public class Ostrich extends Bird{} 

Stopword removal with NLTK

I suggest you create your own list of operator words that you take out of the stopword list. Sets can be conveniently subtracted, so:

operators = set(('and', 'or', 'not'))
stop = set(stopwords...) - operators

Then you can simply test if a word is in or not in the set without relying on whether your operators are part of the stopword list. You can then later switch to another stopword list or add an operator.

if word.lower() not in stop:
    # use word

Mockito How to mock only the call of a method of the superclass

The reason is your base class is not public-ed, then Mockito cannot intercept it due to visibility, if you change base class as public, or @Override in sub class (as public), then Mockito can mock it correctly.

public class BaseService{
  public boolean foo(){
    return true;
  }
}

public ChildService extends BaseService{
}

@Test
@Mock ChildService childService;
public void testSave() {
  Mockito.when(childService.foo()).thenReturn(false);

  // When
  assertFalse(childService.foo());
}

T-SQL: Selecting rows to delete via joins

The syntax above doesn't work in Interbase 2007. Instead, I had to use something like:

DELETE FROM TableA a WHERE [filter condition on TableA] 
  AND (a.BId IN (SELECT a.BId FROM TableB b JOIN TableA a 
                 ON a.BId = b.BId 
                 WHERE [filter condition on TableB]))

(Note Interbase doesn't support the AS keyword for aliases)

Get the Last Inserted Id Using Laravel Eloquent

public function store( UserStoreRequest $request ) {
    $input = $request->all();
    $user = User::create($input);
    $userId=$user->id 
}

How to compare character ignoring case in primitive types

You can't actually do the job quite right with toLowerCase, either on a string or in a character. The problem is that there are variant glyphs in either upper or lower case, and depending on whether you uppercase or lowercase your glyphs may or may not be preserved. It's not even clear what you mean when you say that two variants of a lower-case glyph are compared ignoring case: are they or are they not the same? (Note that there are also mixed-case glyphs: \u01c5, \u01c8, \u01cb, \u01f2 or ?, ?, ?, ?, but any method suggested here will work on those as long as they should count as the same as their fully upper or full lower case variants.)

There is an additional problem with using Char: there are some 80 code points not representable with a single Char that are upper/lower case variants (40 of each), at least as detected by Java's code point upper/lower casing. You therefore need to get the code points and change the case on these.

But code points don't help with the variant glyphs.

Anyway, here's a complete list of the glyphs that are problematic due to variants, showing how they fare against 6 variant methods:

  1. Character toLowerCase
  2. Character toUpperCase
  3. String toLowerCase
  4. String toUpperCase
  5. String equalsIgnoreCase
  6. Character toLowerCase(toUpperCase) (or vice versa)

For these methods, S means that the variants are treated the same as each other, D means the variants are treated as different from each other.

Behavior     Unicode                             Glyphs
===========  ==================================  =========
1 2 3 4 5 6  Upper  Lower  Var Up Var Lo Vr Lo2  U L u l l2
- - - - - -  ------ ------ ------ ------ ------  - - - - -
D D D D S S  \u0049 \u0069 \u0130 \u0131         I i I i   
S D S D S S  \u004b \u006b \u212a                K k K     
D S D S S S  \u0053 \u0073        \u017f         S s   ?   
D S D S S S  \u039c \u03bc        \u00b5         ? µ   µ   
S D S D S S  \u00c5 \u00e5 \u212b                Å å Å     
D S D S S S  \u0399 \u03b9        \u0345 \u1fbe  ? ?   ? ? 
D S D S S S  \u0392 \u03b2        \u03d0         ? ß   ?   
D S D S S S  \u0395 \u03b5        \u03f5         ? e   ?   
D D D D S S  \u0398 \u03b8 \u03f4 \u03d1         T ? ? ?   
D S D S S S  \u039a \u03ba        \u03f0         ? ?   ?   
D S D S S S  \u03a0 \u03c0        \u03d6         ? p   ?   
D S D S S S  \u03a1 \u03c1        \u03f1         ? ?   ?   
D S D S S S  \u03a3 \u03c3        \u03c2         S s   ?   
D S D S S S  \u03a6 \u03c6        \u03d5         F f   ?   
S D S D S S  \u03a9 \u03c9 \u2126                O ? ?     
D S D S S S  \u1e60 \u1e61        \u1e9b         ? ?   ?   

Complicating this still further is that there is no way to get the Turkish I's right (i.e. the dotted versions are different than the undotted versions) unless you know you're in Turkish; none of these methods give correct behavior and cannot unless you know the locale (i.e. non-Turkish: i and I are the same ignoring case; Turkish, not).

Overall, using toUpperCase gives you the closest approximation, since you have only five uppercase variants (or four, not counting Turkish).

You can also try to specifically intercept those five troublesome cases and call toUpperCase(toLowerCase(c)) on them alone. If you choose your guards carefully (just toUpperCase if c < 0x130 || c > 0x212B, then work through the other alternatives) you can get only a ~20% speed penalty for characters in the low range (as compared to ~4x if you convert single characters to strings and equalsIgnoreCase them) and only about a 2x penalty if you have a lot in the danger zone. You still have the locale problem with dotted I, but otherwise you're in decent shape. Of course if you can use equalsIgnoreCase on a larger string, you're better off doing that.

Here is sample Scala code that does the job:

def elevateCase(c: Char): Char = {
  if (c < 0x130 || c > 0x212B) Character.toUpperCase(c)
  else if (c == 0x130 || c == 0x3F4 || c == 0x2126 || c >= 0x212A)
    Character.toUpperCase(Character.toLowerCase(c))
  else Character.toUpperCase(c)
}

Generic Interface

Here's another suggestion:

public interface Service<T> {
   T execute();
}

using this simple interface you can pass arguments via constructor in the concrete service classes:

public class FooService implements Service<String> {

    private final String input1;
    private final int input2;

    public FooService(String input1, int input2) {
       this.input1 = input1;
       this.input2 = input2;
    }

    @Override
    public String execute() {
        return String.format("'%s%d'", input1, input2);
    }
}

What is "entropy and information gain"?

I assume entropy was mentioned in the context of building decision trees.

To illustrate, imagine the task of learning to classify first-names into male/female groups. That is given a list of names each labeled with either m or f, we want to learn a model that fits the data and can be used to predict the gender of a new unseen first-name.

name       gender
-----------------        Now we want to predict 
Ashley        f              the gender of "Amro" (my name)
Brian         m
Caroline      f
David         m

First step is deciding what features of the data are relevant to the target class we want to predict. Some example features include: first/last letter, length, number of vowels, does it end with a vowel, etc.. So after feature extraction, our data looks like:

# name    ends-vowel  num-vowels   length   gender
# ------------------------------------------------
Ashley        1         3           6        f
Brian         0         2           5        m
Caroline      1         4           8        f
David         0         2           5        m

The goal is to build a decision tree. An example of a tree would be:

length<7
|   num-vowels<3: male
|   num-vowels>=3
|   |   ends-vowel=1: female
|   |   ends-vowel=0: male
length>=7
|   length=5: male

basically each node represent a test performed on a single attribute, and we go left or right depending on the result of the test. We keep traversing the tree until we reach a leaf node which contains the class prediction (m or f)

So if we run the name Amro down this tree, we start by testing "is the length<7?" and the answer is yes, so we go down that branch. Following the branch, the next test "is the number of vowels<3?" again evaluates to true. This leads to a leaf node labeled m, and thus the prediction is male (which I happen to be, so the tree predicted the outcome correctly).

The decision tree is built in a top-down fashion, but the question is how do you choose which attribute to split at each node? The answer is find the feature that best splits the target class into the purest possible children nodes (ie: nodes that don't contain a mix of both male and female, rather pure nodes with only one class).

This measure of purity is called the information. It represents the expected amount of information that would be needed to specify whether a new instance (first-name) should be classified male or female, given the example that reached the node. We calculate it based on the number of male and female classes at the node.

Entropy on the other hand is a measure of impurity (the opposite). It is defined for a binary class with values a/b as:

Entropy = - p(a)*log(p(a)) - p(b)*log(p(b))

This binary entropy function is depicted in the figure below (random variable can take one of two values). It reaches its maximum when the probability is p=1/2, meaning that p(X=a)=0.5 or similarlyp(X=b)=0.5 having a 50%/50% chance of being either a or b (uncertainty is at a maximum). The entropy function is at zero minimum when probability is p=1 or p=0 with complete certainty (p(X=a)=1 or p(X=a)=0 respectively, latter implies p(X=b)=1).

https://en.wikipedia.org/wiki/File:Binary_entropy_plot.svg

Of course the definition of entropy can be generalized for a discrete random variable X with N outcomes (not just two):

entropy

(the log in the formula is usually taken as the logarithm to the base 2)


Back to our task of name classification, lets look at an example. Imagine at some point during the process of constructing the tree, we were considering the following split:

     ends-vowel
      [9m,5f]          <--- the [..,..] notation represents the class
    /          \            distribution of instances that reached a node
   =1          =0
 -------     -------
 [3m,4f]     [6m,1f]

As you can see, before the split we had 9 males and 5 females, i.e. P(m)=9/14 and P(f)=5/14. According to the definition of entropy:

Entropy_before = - (5/14)*log2(5/14) - (9/14)*log2(9/14) = 0.9403

Next we compare it with the entropy computed after considering the split by looking at two child branches. In the left branch of ends-vowel=1, we have:

Entropy_left = - (3/7)*log2(3/7) - (4/7)*log2(4/7) = 0.9852

and the right branch of ends-vowel=0, we have:

Entropy_right = - (6/7)*log2(6/7) - (1/7)*log2(1/7) = 0.5917

We combine the left/right entropies using the number of instances down each branch as weight factor (7 instances went left, and 7 instances went right), and get the final entropy after the split:

Entropy_after = 7/14*Entropy_left + 7/14*Entropy_right = 0.7885

Now by comparing the entropy before and after the split, we obtain a measure of information gain, or how much information we gained by doing the split using that particular feature:

Information_Gain = Entropy_before - Entropy_after = 0.1518

You can interpret the above calculation as following: by doing the split with the end-vowels feature, we were able to reduce uncertainty in the sub-tree prediction outcome by a small amount of 0.1518 (measured in bits as units of information).

At each node of the tree, this calculation is performed for every feature, and the feature with the largest information gain is chosen for the split in a greedy manner (thus favoring features that produce pure splits with low uncertainty/entropy). This process is applied recursively from the root-node down, and stops when a leaf node contains instances all having the same class (no need to split it further).

Note that I skipped over some details which are beyond the scope of this post, including how to handle numeric features, missing values, overfitting and pruning trees, etc..

How to get SLF4J "Hello World" working with log4j?

you need to add 3 dependency ( API+ API implementation + log4j dependency) 
Add also this 
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.5</version>
</dependency>

# And to see log in command line , set log4j.properties 

# Root logger option
log4j.rootLogger=INFO, file, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

#And to see log in file  , set log4j.properties 
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./logs/logging.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

how to run mysql in ubuntu through terminal

You have to give a valid username. For example, to run query with user root you have to type the following command and then enter password when prompted:

mysql -u root -p

Once you are connected, prompt will be something like:

mysql>

Here you can write your query, after database selection, for example:

mysql> USE your_database;
mysql> SELECT * FROM your_table;

How to programmatically set style attribute in a view

You can do style attributes like so:

Button myButton = new Button(this, null,android.R.attr.buttonBarButtonStyle);

in place of:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btn"
    style="?android:attr/buttonBarButtonStyle"

    />

Delete sql rows where IDs do not have a match from another table

DELETE FROM blob
WHERE NOT EXISTS (
    SELECT *
    FROM files
    WHERE id=blob.id
)

How to right align widget in horizontal linear layout Android?

setting the view's layout_weight="1" would do the trick.!

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
    android:id="@+id/textView1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1" />

<RadioButton
    android:id="@+id/radioButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

Oracle date function for the previous month

It is working with me in Oracle sql developer

    SELECT add_months(trunc(sysdate,'mm'), -1),
           last_day(add_months(trunc(sysdate,'mm'), -1)) 
    FROM dual

How to get current memory usage in android?

I looked at Android Source Tree.

Inside com.android.server.am.ActivityManagerService.java (internal service exposed by android.app.ActivityManager).

public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
    final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
    final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
    outInfo.availMem = Process.getFreeMemory();
    outInfo.totalMem = Process.getTotalMemory();
    outInfo.threshold = homeAppMem;
    outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
    outInfo.hiddenAppThreshold = hiddenAppMem;
    outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
            ProcessList.SERVICE_ADJ);
    outInfo.visibleAppThreshold = mProcessList.getMemLevel(
            ProcessList.VISIBLE_APP_ADJ);
    outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
            ProcessList.FOREGROUND_APP_ADJ);
}

Inside android.os.Process.java

/** @hide */
public static final native long getFreeMemory();

/** @hide */
public static final native long getTotalMemory();

It calls JNI method from android_util_Process.cpp

Conclusion

MemoryInfo.availMem = MemFree + Cached in /proc/meminfo.

Notes

Total Memory is added in API level 16.

Using a dictionary to select function to execute

Often classes are used to enclose methods and following is the extension for answers above with default method in case the method is not found.

class P:

     def p1(self):
         print('Start')

     def p2(self):
         print('Help')

     def ps(self):
         print('Settings')

     def d(self):
         print('Default function')

     myDict = {
         "start": p1,
         "help": p2,
         "settings": ps
     }

     def call_it(self):
         name = 'start'
         f = lambda self, x : self.myDict.get(x, lambda x : self.d())(self)
         f(self, name)


 p = P()
 p.call_it()

Insert an element at a specific index in a list and return the updated list

The shortest I got: b = a[:2] + [3] + a[2:]

>>>
>>> a = [1, 2, 4]
>>> print a
[1, 2, 4]
>>> b = a[:2] + [3] + a[2:]
>>> print a
[1, 2, 4]
>>> print b
[1, 2, 3, 4]

How to change shape color dynamically?

    LayerDrawable bgDrawable = (LayerDrawable) button.getBackground();
    final GradientDrawable shape = (GradientDrawable)
            bgDrawable.findDrawableByLayerId(R.id.round_button_shape);
    shape.setColor(Color.BLACK);

Output grep results to text file, need cleaner output

Redirection of program output is performed by the shell.

grep ... > output.txt

grep has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1) man page for details, specifically the -C and --color options.

Select element by exact match of its content

Like T.J. Crowder stated above, the filter function does wonders. It wasn't working for me in my specific case. I needed to search multiple tables and their respective td tags inside a div (in this case a jQuery dialog).

$("#MyJqueryDialog table tr td").filter(function () {
    // The following implies that there is some text inside the td tag.
    if ($.trim($(this).text()) == "Hello World!") {
       // Perform specific task.
    }
});

I hope this is helpful to someone!

Write output to a text file in PowerShell

Use the Out-File cmdlet

 Compare-Object ... | Out-File C:\filename.txt

Optionally, add -Encoding utf8 to Out-File as the default encoding is not really ideal for many uses.

How can I get query string values in JavaScript?

This will work... You need to call this function where you need get the parameter by passing its name...

function getParameterByName(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  alert(results[1]);
  if (results == null)
    return "";
  else
    return results[1];
}

Calling a JavaScript function named in a variable

Definitely avoid using eval to do something like this, or you will open yourself to XSS (Cross-Site Scripting) vulnerabilities.

For example, if you were to use the eval solutions proposed here, a nefarious user could send a link to their victim that looked like this:

http://yoursite.com/foo.html?func=function(){alert('Im%20In%20Teh%20Codez');}

And their javascript, not yours, would get executed. This code could do something far worse than just pop up an alert of course; it could steal cookies, send requests to your application, etc.

So, make sure you never eval untrusted code that comes in from user input (and anything on the query string id considered user input). You could take user input as a key that will point to your function, but make sure that you don't execute anything if the string given doesn't match a key in your object. For example:

// set up the possible functions:
var myFuncs = {
  func1: function () { alert('Function 1'); },
  func2: function () { alert('Function 2'); },
  func3: function () { alert('Function 3'); },
  func4: function () { alert('Function 4'); },
  func5: function () { alert('Function 5'); }
};
// execute the one specified in the 'funcToRun' variable:
myFuncs[funcToRun]();

This will fail if the funcToRun variable doesn't point to anything in the myFuncs object, but it won't execute any code.

How do you change the colour of each category within a highcharts column chart?

Add which colors you want to colors and then set colorByPoint to true.

colors: [
'#4572A7', 
'#AA4643', 
'#89A54E', 
'#80699B', 
'#3D96AE', 
'#DB843D', 
'#92A8CD', 
'#A47D7C', 
'#B5CA92'
],

plotOptions: {
    column: {
        colorByPoint: true
    }
}

demo

Reference:

Map HTML to JSON

I just wrote this function that does what you want; try it out let me know if it doesn't work correctly for you:

// Test with an element.
var initElement = document.getElementsByTagName("html")[0];
var json = mapDOM(initElement, true);
console.log(json);

// Test with a string.
initElement = "<div><span>text</span>Text2</div>";
json = mapDOM(initElement, true);
console.log(json);

function mapDOM(element, json) {
    var treeObject = {};
    
    // If string convert to document Node
    if (typeof element === "string") {
        if (window.DOMParser) {
              parser = new DOMParser();
              docNode = parser.parseFromString(element,"text/xml");
        } else { // Microsoft strikes again
              docNode = new ActiveXObject("Microsoft.XMLDOM");
              docNode.async = false;
              docNode.loadXML(element); 
        } 
        element = docNode.firstChild;
    }
    
    //Recursively loop through DOM elements and assign properties to object
    function treeHTML(element, object) {
        object["type"] = element.nodeName;
        var nodeList = element.childNodes;
        if (nodeList != null) {
            if (nodeList.length) {
                object["content"] = [];
                for (var i = 0; i < nodeList.length; i++) {
                    if (nodeList[i].nodeType == 3) {
                        object["content"].push(nodeList[i].nodeValue);
                    } else {
                        object["content"].push({});
                        treeHTML(nodeList[i], object["content"][object["content"].length -1]);
                    }
                }
            }
        }
        if (element.attributes != null) {
            if (element.attributes.length) {
                object["attributes"] = {};
                for (var i = 0; i < element.attributes.length; i++) {
                    object["attributes"][element.attributes[i].nodeName] = element.attributes[i].nodeValue;
                }
            }
        }
    }
    treeHTML(element, treeObject);
    
    return (json) ? JSON.stringify(treeObject) : treeObject;
}

Working example: http://jsfiddle.net/JUSsf/ (Tested in Chrome, I can't guarantee full browser support - you will have to test this).

?It creates an object that contains the tree structure of the HTML page in the format you requested and then uses JSON.stringify() which is included in most modern browsers (IE8+, Firefox 3+ .etc); If you need to support older browsers you can include json2.js.

It can take either a DOM element or a string containing valid XHTML as an argument (I believe, I'm not sure whether the DOMParser() will choke in certain situations as it is set to "text/xml" or whether it just doesn't provide error handling. Unfortunately "text/html" has poor browser support).

You can easily change the range of this function by passing a different value as element. Whatever value you pass will be the root of your JSON map.

Getting value from table cell in JavaScript...not jQuery

The code yo have provided runs fine. Remember that if you have your code in the header, you need to wait for the dom to be loaded first. In jQuery it would just be as simple as putting your code inside $(function(e){...});

In normal javascript use window.onLoad(..) or the like... or have the script after the table defnition (yuck!). The snippet you provided runs fine when I have it that way for the following:

<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=windows-1250">
  <meta name="generator" content="PSPad editor, www.pspad.com">
  <title></title>
</head>
<body>
  <table id='ddReferences'>
    <tr>
      <td>dfsdf</td> 
      <td>sdfs</td>
      <td>frtyr</td>
      <td>hjhj</td>
    </tr>
  </table>

<script>
var refTab = document.getElementById("ddReferences")
var  ttl;
// Loop through all rows and columns of the table and popup alert with the value
// /content of each cell.
for ( var i = 0; row = refTab.rows[i]; i++ ) {
   row = refTab.rows[i];
   for ( var j = 0; col = row.cells[j]; j++ ) {
      alert(col.firstChild.nodeValue);
   }
}

</script>
</body>
</html>

how to use python2.7 pip instead of default pip

An alternative is to call the pip module by using python2.7, as below:

python2.7 -m pip <commands>

For example, you could run python2.7 -m pip install <package> to install your favorite python modules. Here is a reference: https://stackoverflow.com/a/50017310/4256346.

In case the pip module has not yet been installed for this version of python, you can run the following:

python2.7 -m ensurepip

Running this command will "bootstrap the pip installer". Note that running this may require administrative privileges (i.e. sudo). Here is a reference: https://docs.python.org/2.7/library/ensurepip.html and another reference https://stackoverflow.com/a/46631019/4256346.

How to create an empty file at the command line in Windows?

As a VIM user on windows, I failed to find the answer in this question thread.

As a solution from this thread, please install the gvim firstly.
During the installation, please remember to check the option "Create .bat files for command line use" as shown below.

enter image description here

Some bat files like vim.bat and gvim.bat will be installed under C:\Windows. Add C:\Windows to system Path if it's not done.

Relaunch the cmd.exe and type gvim empty_file.txt, you will launch the gvim to edit the empty file from scratch. If you don't want to leave your "Command Prompt" console, type vim empty_file.txt instead.

Hope this answer can help those who want to launch VIM from windows Command Prompt when creating an empty file.

Where is shared_ptr?

If your'e looking bor boost's shared_ptr, you could have easily found the answer by googling shared_ptr, following the links to the docs, and pulling up a complete working example such as this.

In any case, here is a minimalistic complete working example for you which I just hacked up:

#include <boost/shared_ptr.hpp>

struct MyGizmo
{
    int n_;
};

int main()
{
    boost::shared_ptr<MyGizmo> p(new MyGizmo);
    return 0;
}

In order for the #include to find the header, the libraries obviously need to be in the search path. In MSVC, you set this in Project Settings>Configuration Properties>C/C++>Additional Include Directories. In my case, this is set to C:\Program Files (x86)\boost\boost_1_42

What is difference between sleep() method and yield() method of multi threading?

sleep() causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power saving mode).

yield() basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should. Otherwise, the current thread will continue to run.

How to calculate distance between two locations using their longitude and latitude value

Try this code.

startPoint.distanceTo(endPoint) function returns the distance between those places in meters.

Location startPoint=new Location("locationA");
startPoint.setLatitude(17.372102);
startPoint.setLongitude(78.484196);

Location endPoint=new Location("locationA");
endPoint.setLatitude(17.375775);
endPoint.setLongitude(78.469218);

double distance=startPoint.distanceTo(endPoint);

here "distance" is our required result in Meters. I hope it will work for android.

What is the correct value for the disabled attribute?

I just tried all of these, and for IE11, the only thing that seems to work is disabled="true". Values of disabled or no value given didnt work. As a matter of fact, the jsp got an error that equal is required for all fields, so I had to specify disabled="true" for this to work.

phpmyadmin.pma_table_uiprefs doesn't exist

You are missing at least one of the phpMyAdmin configuration storage tables, or the configured table name does not match the actual table name.

See http://docs.phpmyadmin.net/en/latest/setup.html#phpmyadmin-configuration-storage.

A quick summary of what to do can be:

  1. On the shell: locate create_tables.sql.
  2. import /usr/share/doc/phpmyadmin/examples/create_tables.sql.gz using phpMyAdmin.
  3. open /etc/phpmyadmin/config.inc.php and edit lines 81-92: change pma_bookmark to pma__bookmark and so on.

declaring a priority_queue in c++ with a custom comparator

In case this helps anyone :

static bool myFunction(Node& p1, Node& p2) {}
priority_queue <Node, vector<Node>, function<bool(Node&, Node&)>> pq1(myFunction);

How do I compare two DateTime objects in PHP 5.2.8?

If you want to compare dates and not time, you could use this:

$d1->format("Y-m-d") == $d2->format("Y-m-d")

Difference between Pig and Hive? Why have both?

When we are using Hadoop in the sense it means we are trying to huge data processing The end goal of the data processing would be to generate content/reports out of it.

So it internally consists of 2 prime activities:

1) Loading Data Processing

2) Generate content and use it for the reporting /etc..

Loading /Data Processing -> Pig would be helpful in it.

This helps as an ETL (We can perform etl operations using pig scripts.).

Once the result is processed we can use hive to generate the reports based on the processed result.

Hive: Its built on top of hdfs for warehouse processing.

We can generate adhoc reports easily using hive from the processed content generated from pig.

How do I get java logging output to appear on a single line?

if you're using java.util.logging, then there is a configuration file that is doing this to log contents (unless you're using programmatic configuration). So, your options are
1) run post -processor that removes the line breaks
2) change the log configuration AND remove the line breaks from it. Restart your application (server) and you should be good.

Getting Keyboard Input

You can use Scanner class like this:

  import java.util.Scanner;

public class Main{
    public static void main(String args[]){

    Scanner scan= new Scanner(System.in);

    //For string

    String text= scan.nextLine();

    System.out.println(text);

    //for int

    int num= scan.nextInt();

    System.out.println(num);
    }
}

How to clear the text of all textBoxes in the form?

You can try this code

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {


        if(keyData==Keys.C)
        {
            RefreshControl();
            return true;
        }


        return base.ProcessCmdKey(ref msg, keyData);
    }

Is null check needed before calling instanceof?

No, a null check is not needed before using instanceof.

The expression x instanceof SomeClass is false if x is null.

From the Java Language Specification, section 15.20.2, "Type comparison operator instanceof":

"At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false."

So if the operand is null, the result is false.

How to efficiently build a tree from a flat structure?

I can do this in 4 lines of code and O(n log n) time, assuming that Dictionary is something like a TreeMap.

dict := Dictionary new.
ary do: [:each | dict at: each id put: each].
ary do: [:each | (dict at: each parent) addChild: each].
root := dict at: nil.

EDIT: Ok, and now I read that some parentIDs are fake, so forget the above, and do this:

dict := Dictionary new.
dict at: nil put: OrderedCollection new.
ary do: [:each | dict at: each id put: each].
ary do: [:each | 
    (dict at: each parent ifAbsent: [dict at: nil]) 
          add: each].
roots := dict at: nil.

How to pass parameters to maven build using pom.xml?

We can Supply parameter in different way after some search I found some useful

<plugin>
  <artifactId>${release.artifactId}</artifactId>
  <version>${release.version}-${release.svm.version}</version>...

...

Actually in my application I need to save and supply SVN Version as parameter so i have implemented as above .

While Running build we need supply value for those parameter as follows.

RestProj_Bizs>mvn clean install package -Drelease.artifactId=RestAPIBiz -Drelease.version=10.6 -Drelease.svm.version=74

Here I am supplying

release.artifactId=RestAPIBiz
release.version=10.6
release.svm.version=74

It worked for me. Thanks

How to set the context path of a web application in Tomcat 7.0

In Tomcat 9.0, I only have to change the following in the server.xml

<Context docBase="web" path="/web" reloadable="true" source="org.eclipse.jst.jee.server:web"/>

to

<Context docBase="web" path="" reloadable="true" source="org.eclipse.jst.jee.server:web"/>

Correct way of looping through C++ arrays

How about:

#include <iostream>
#include <array>
#include <algorithm>

int main ()
{
    std::array<std::string, 3> text = {"Apple", "Banana", "Orange"};
    std::for_each(text.begin(), text.end(), [](std::string &string){ std::cout << string << "\n"; });

    return 0;
}

Compiles and works with C++ 11 and has no 'raw' looping :)

Jquery- Get the value of first td in table

$(this).parent().siblings(":first").text()

parent gives you the <td> around the link,

siblings gives all the <td> tags in that <tr>,

:first gives the first matched element in the set.

text() gives the contents of the tag.

HTML.ActionLink method

I think what you want is this:

ASP.NET MVC1

Html.ActionLink(article.Title, 
                "Login",  // <-- Controller Name.
                "Item",   // <-- ActionMethod
                new { id = article.ArticleID }, // <-- Route arguments.
                null  // <-- htmlArguments .. which are none. You need this value
                      //     otherwise you call the WRONG method ...
                      //     (refer to comments, below).
                )

This uses the following method ActionLink signature:

public static string ActionLink(this HtmlHelper htmlHelper, 
                                string linkText,
                                string controllerName,
                                string actionName,
                                object values, 
                                object htmlAttributes)

ASP.NET MVC2

two arguments have been switched around

Html.ActionLink(article.Title, 
                "Item",   // <-- ActionMethod
                "Login",  // <-- Controller Name.
                new { id = article.ArticleID }, // <-- Route arguments.
                null  // <-- htmlArguments .. which are none. You need this value
                      //     otherwise you call the WRONG method ...
                      //     (refer to comments, below).
                )

This uses the following method ActionLink signature:

public static string ActionLink(this HtmlHelper htmlHelper, 
                                string linkText,
                                string actionName,
                                string controllerName,
                                object values, 
                                object htmlAttributes)

ASP.NET MVC3+

arguments are in the same order as MVC2, however the id value is no longer required:

Html.ActionLink(article.Title, 
                "Item",   // <-- ActionMethod
                "Login",  // <-- Controller Name.
                new { article.ArticleID }, // <-- Route arguments.
                null  // <-- htmlArguments .. which are none. You need this value
                      //     otherwise you call the WRONG method ...
                      //     (refer to comments, below).
                )

This avoids hard-coding any routing logic into the link.

 <a href="/Item/Login/5">Title</a> 

This will give you the following html output, assuming:

  1. article.Title = "Title"
  2. article.ArticleID = 5
  3. you still have the following route defined

. .

routes.MapRoute(
    "Default",     // Route name
    "{controller}/{action}/{id}",                           // URL with parameters
    new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
);

How to enter a multi-line command

You can use a space followed by the grave accent (backtick):

Get-ChildItem -Recurse `
  -Filter *.jpg `
  | Select LastWriteTime

However, this is only ever necessary in such cases as shown above. Usually you get automatic line continuation when a command cannot syntactically be complete at that point. This includes starting a new pipeline element:

Get-ChildItem |
  Select Name,Length

will work without problems since after the | the command cannot be complete since it's missing another pipeline element. Also opening curly braces or any other kind of parentheses will allow line continuation directly:

$x=1..5
$x[
  0,3
] | % {
  "Number: $_"
}

Similar to the | a comma will also work in some contexts:

1,
2

Keep in mind, though, similar to JavaScript's Automatic Semicolon Insertion, there are some things that are similarly broken because the line break occurs at a point where it is preceded by a valid statement:

return
  5

will not work.

Finally, strings (in all varieties) may also extend beyond a single line:

'Foo
bar'

They include the line breaks within the string, then.

plotting different colors in matplotlib

@tcaswell already answered, but I was in the middle of typing my answer up, so I'll go ahead and post it...

There are a number of different ways you could do this. To begin with, matplotlib will automatically cycle through colors. By default, it cycles through blue, green, red, cyan, magenta, yellow, black:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
for i in range(1, 6):
    plt.plot(x, i * x + i, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

If you want to control which colors matplotlib cycles through, use ax.set_color_cycle:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
fig, ax = plt.subplots()
ax.set_color_cycle(['red', 'black', 'yellow'])
for i in range(1, 6):
    plt.plot(x, i * x + i, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

If you'd like to explicitly specify the colors that will be used, just pass it to the color kwarg (html colors names are accepted, as are rgb tuples and hex strings):

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
for i, color in enumerate(['red', 'black', 'blue', 'brown', 'green'], start=1):
    plt.plot(x, i * x + i, color=color, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

Finally, if you'd like to automatically select a specified number of colors from an existing colormap:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
number = 5
cmap = plt.get_cmap('gnuplot')
colors = [cmap(i) for i in np.linspace(0, 1, number)]

for i, color in enumerate(colors, start=1):
    plt.plot(x, i * x + i, color=color, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

How to determine the Schemas inside an Oracle Data Pump Export file

The running the impdp command to produce an sqlfile, you will need to run it as a user which has the DATAPUMP_IMP_FULL_DATABASE role.

Or... run it as a low privileged user and use the MASTER_ONLY=YES option, then inspect the master table. e.g.

select value_t 
from SYS_IMPORT_TABLE_01 
where name = 'CLIENT_COMMAND' 
and process_order = -59;

col object_name for a30
col processing_status head STATUS for a6
col processing_state head STATE for a5
select distinct
  object_schema,
  object_name,
  object_type,
  object_tablespace,
  process_order,
  duplicate,
  processing_status,
  processing_state
from sys_import_table_01
where process_order > 0
and object_name is not null
order by object_schema, object_name
/

http://download.oracle.com/otndocs/products/database/enterprise_edition/utilities/pdf/oow2011_dp_mastering.pdf

Formatting "yesterday's" date in python

To expand on the answer given by Chris

if you want to store the date in a variable in a specific format, this is the shortest and most effective way as far as I know

>>> from datetime import date, timedelta                   
>>> yesterday = (date.today() - timedelta(days=1)).strftime('%m%d%y')
>>> yesterday
'020817'

If you want it as an integer (which can be useful)

>>> yesterday = int((date.today() - timedelta(days=1)).strftime('%m%d%y'))
>>> yesterday
20817

python pandas convert index to datetime

I just give other option for this question - you need to use '.dt' in your code:

_x000D_
_x000D_
import pandas as pd_x000D_
_x000D_
df.index = pd.to_datetime(df.index)_x000D_
_x000D_
#for get year_x000D_
df.index.dt.year_x000D_
_x000D_
#for get month_x000D_
df.index.dt.month_x000D_
_x000D_
#for get day_x000D_
df.index.dt.day_x000D_
_x000D_
#for get hour_x000D_
df.index.dt.hour_x000D_
_x000D_
#for get minute_x000D_
df.index.dt.minute
_x000D_
_x000D_
_x000D_

Excel Date to String conversion

=TEXT(A1,"DD/MM/YYYY hh:mm:ss")

(24 hour time)

=TEXT(A1,"DD/MM/YYYY hh:mm:ss AM/PM")

(standard time)

Overlay a background-image with an rgba background-color

Ideally the background property would allow us to layer various backgrounds similar to the background image layering detailed at http://www.css3.info/preview/multiple-backgrounds/. Unfortunately, at least in Chrome (40.0.2214.115), adding an rgba background alongside a url() image background seems to break the property.

The solution I've found is to render the rgba layer as a 1px*1px Base64 encoded image and inline it.

.the-div:hover {
  background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNgkAQAABwAGkn5GOoAAAAASUVORK5CYII=), url("the-image.png");
}

for base64 encoded 1*1 pixel images I used http://px64.net/

Here is your jsfiddle with these changes made. http://jsfiddle.net/325Ft/49/ (I also swapped the image to one that still exists on the internet)

how to generate public key from windows command prompt

If you've got git-bash installed (which comes with Git, Github for Windows, or Visual Studio 2015), then that includes a Windows version of ssh-keygen.

https://help.github.com/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent/

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

Because interfaces specify only what the class is doing, not how it is doing it.

The problem with multiple inheritance is that two classes may define different ways of doing the same thing, and the subclass can't choose which one to pick.

Sorting arraylist in alphabetical order (case insensitive)

try this code

Collections.sort(yourarraylist, new SortBasedOnName());



import java.util.Comparator;
import com.RealHelp.objects.FBFriends_Obj;
import com.RealHelp.ui.importFBContacts;

public class SortBasedOnName implements Comparator
{
public int compare(Object o1, Object o2) 
{

    FBFriends_Obj dd1 = (FBFriends_Obj)o1;// where FBFriends_Obj is your object class
    FBFriends_Obj dd2 = (FBFriends_Obj)o2;
    return dd1.uname.compareToIgnoreCase(dd2.uname);//where uname is field name
}

}

elasticsearch bool query combine must with OR

I recently had to solve this problem too, and after a LOT of trial and error I came up with this (in PHP, but maps directly to the DSL):

'query' => [
    'bool' => [
        'should' => [
            ['prefix' => ['name_first' => $query]],
            ['prefix' => ['name_last' => $query]],
            ['prefix' => ['phone' => $query]],
            ['prefix' => ['email' => $query]],
            [
                'multi_match' => [
                    'query' => $query,
                    'type' => 'cross_fields',
                    'operator' => 'and',
                    'fields' => ['name_first', 'name_last']
                ]
            ]
        ],
        'minimum_should_match' => 1,
        'filter' => [
            ['term' => ['state' => 'active']],
            ['term' => ['company_id' => $companyId]]
        ]
    ]
]

Which maps to something like this in SQL:

SELECT * from <index> 
WHERE (
    name_first LIKE '<query>%' OR
    name_last LIKE '<query>%' OR
    phone LIKE  '<query>%' OR
    email LIKE '<query>%'
)
AND state = 'active'
AND company_id = <query>

The key in all this is the minimum_should_match setting. Without this the filter totally overrides the should.

Hope this helps someone!

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

This is a helper function for mustacheJS, without pre-formatting the data and instead getting it during render.

var data = {
    valueFromMap: function() {
        return function(text, render) {
            // "this" will be an object with map key property
            // text will be color that we have between the mustache-tags
            // in the template
            // render is the function that mustache gives us

            // still need to loop since we have no idea what the key is
            // but there will only be one
            for ( var key in this) {
                if (this.hasOwnProperty(key)) {
                    return render(this[key][text]);
                }
            }
        };
    },

    list: {
        blueHorse: {
            color: 'blue'
        },

        redHorse: {
            color: 'red'
        }
    }
};

Template:

{{#list}}
    {{#.}}<span>color: {{#valueFromMap}}color{{/valueFromMap}}</span> <br/>{{/.}}
{{/list}}

Outputs:

color: blue
color: red

(order might be random - it's a map) This might be useful if you know the map element that you want. Just watch out for falsy values.

Tomcat is not deploying my web project from Eclipse

I encountered with same error and resolved it with redeployment after removing deployment.

Swapping pointers in C (char, int)

The first thing you need to understand is that when you pass something to a function, that something is copied to the function's arguments.

Suppose you have the following:

void swap1(int a, int b) {
    int temp = a;
    a = b;
    b = temp;
    assert(a == 17);
    assert(b == 42);
    // they're swapped!
}

int x = 42;
int y = 17;
swap1(x, y);
assert(x == 42);
assert(y == 17);
// no, they're not swapped!

The original variables will not be swapped, because their values are copied into the function's arguments. The function then proceeds to swap the values of those arguments, and then returns. The original values are not changed, because the function only swaps its own private copies.

Now how do we work around this? The function needs a way to refer to the original variables, not copies of their values. How can we refer to other variables in C? Using pointers.

If we pass pointers to our variables into the function, the function can swap the values in our variables, instead of its own argument copies.

void swap2(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
    assert(*a == 17);
    assert(*b == 42);
    // they're swapped!
}

int x = 42;
int y = 17;
swap2(&x, &y); // give the function pointers to our variables
assert(x == 17);
assert(y == 42);
// yes, they're swapped!

Notice how inside the function we're not assigning to the pointers, but assigning to what they point to. And the pointers point to our variables x and y. The function is changing directly the values stored in our variables through the pointers we give it. And that's exactly what we needed.

Now what happens if we have two pointer variables and want to swap the pointers themselves (as opposed to the values they point to)? If we pass pointers, the pointers will simply be copied (not the values they point to) to the arguments.

void swap3(int* a, int* b) {
    int* temp = a;
    a = b;
    b = temp;
    assert(*a == 17);
    assert(*b == 42);
    // they're swapped!
}
void swap4(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
    assert(*a == 17);
    assert(*b == 42);
    // they're swapped!
}

int x = 42;
int y = 17;
int* xp = &x;
int* yp = &y;
swap3(xp, yp);
assert(xp == &x);
assert(yp == &y);
assert(x == 42);
assert(y == 17);
// Didn't swap anything!
swap4(xp, yp);
assert(xp == &x);
assert(yp == &y);
assert(x == 17);
assert(y == 42);
// Swapped the stored values instead!

The function swap3 only swaps its own private copies of our pointers that it gets in its arguments. It's the same issue we had with swap1. And swap4 is changing the values our variables point to, not the pointers! We're giving the function a means to refer to the variables x and y but we want them to refer to xp and yp.

How do we do that? We pass it their addresses!

void swap5(int** a, int** b) {
    int* temp = *a;
    *a = *b;
    *b = temp;
    assert(**a == 17);
    assert(**b == 42);
    // they're swapped!
}


int x = 42;
int y = 17;
int* xp = &x;
int* yp = &y;
swap5(&xp, &yp);
assert(xp == &y);
assert(yp == &x);
assert(x == 42);
assert(y == 17);
// swapped only the pointers variables

This way it swaps our pointer variables (notice how xp now points to y) but not the values they point to. We gave it a way to refer to our pointer variables, so it can change them!

By now it should be easy to understand how to swap two strings in the form of char* variables. The swap function needs to receive pointers to char*.

void swapStrings(char** a, char** b){
    char *temp = *a;
    *a = *b;
    *b = temp;
    assert(strcmp(*a, "world") == 0);
    assert(strcmp(*b, "Hello") == 0);
}

char* x = "Hello";
char* y = "world";
swapStrings(&x, &y);
assert(strcmp(x, "world") == 0);
assert(strcmp(y, "Hello") == 0);

Increase max execution time for php

Well, since your on a shared server, you can't do anything about it. They usually set the max execution time so that you can't override it. I suggest you contact them.

Can dplyr package be used for conditional mutating?

case_when is now a pretty clean implementation of the SQL-style case when:

structure(list(a = c(1, 3, 4, 6, 3, 2, 5, 1), b = c(1, 3, 4, 
2, 6, 7, 2, 6), c = c(6, 3, 6, 5, 3, 6, 5, 3), d = c(6, 2, 4, 
5, 3, 7, 2, 6), e = c(1, 2, 4, 5, 6, 7, 6, 3), f = c(2, 3, 4, 
2, 2, 7, 5, 2)), .Names = c("a", "b", "c", "d", "e", "f"), row.names = c(NA, 
8L), class = "data.frame") -> df


df %>% 
    mutate( g = case_when(
                a == 2 | a == 5 | a == 7 | (a == 1 & b == 4 )     ~   2,
                a == 0 | a == 1 | a == 4 |  a == 3 | c == 4       ~   3
))

Using dplyr 0.7.4

The manual: http://dplyr.tidyverse.org/reference/case_when.html

What is the difference between npm install and npm run build?

NPM in 2019

npm build no longer exists. You must call npm run build now. More info below.

TLDR;

npm install: installs dependencies, then calls the install from the package.json scripts field.

npm run build: runs the build field from the package.json scripts field.


NPM Scripts Field

https://docs.npmjs.com/misc/scripts

There are many things you can put into the npm package.json scripts field. Check out the documentation link above more above the lifecycle of the scripts - most have pre and post hooks that you can run scripts before/after install, publish, uninstall, test, start, stop, shrinkwrap, version.


To Complicate Things

  • npm install is not the same as npm run install
  • npm install installs package.json dependencies, then runs the package.json scripts.install
    • (Essentially calls npm run install after dependencies are installed.
  • npm run install only runs the package.json scripts.install, it will not install dependencies.
  • npm build used to be a valid command (used to be the same as npm run build) but it no longer is; it is now an internal command. If you run it you'll get: npm WARN build npm build called with no arguments. Did you mean to npm run-script build? You can read more on the documentation: https://docs.npmjs.com/cli/build

Extra Notes

There are still two top level commands that will run scripts, they are:

  • npm start which is the same as npm run start
  • npm test ==> npm run test

Retrieve data from website in android app

You can use jsoup to parse any kind of web page. Here you can find the jsoup library and full source code.

Here is an example: http://desicoding.blogspot.com/2011/03/how-to-parse-html-in-java-jsoup.html

To install in Eclipse:

  1. Right Click on project
  2. BuildPath
  3. Add External Archives
  4. select the .jar file

You can parse according to tag/parent/child very comfortably

How To Pass GET Parameters To Laravel From With GET Method ?

The simplest way is just to accept the incoming request, and pull out the variables you want in the Controller:

Route::get('search', ['as' => 'search', 'uses' => 'SearchController@search']);

and then in SearchController@search:

class SearchController extends BaseController {

    public function search()
    {
        $category = Input::get('category', 'default category');
        $term = Input::get('term', false);

        // do things with them...
    }
}

Usefully, you can set defaults in Input::get() in case nothing is passed to your Controller's action.

As joe_archer says, it's not necessary to put these terms into the URL, and it might be better as a POST (in which case you should update your call to Form::open() and also your search route in routes.php - Input::get() remains the same)

AJAX jQuery refresh div every 5 seconds

you can use this one.

<div id="test"></div>

you java script code should be like that.

setInterval(function(){
      $('#test').load('test.php');
 },5000);

Correct way to use StringBuilder in SQL

In the code you have posted there would be no advantages, as you are misusing the StringBuilder. You build the same String in both cases. Using StringBuilder you can avoid the + operation on Strings using the append method. You should use it this way:

return new StringBuilder("select id1, ").append(" id2 ").append(" from ").append(" table").toString();

In Java, the String type is an inmutable sequence of characters, so when you add two Strings the VM creates a new String value with both operands concatenated.

StringBuilder provides a mutable sequence of characters, which you can use to concat different values or variables without creating new String objects, and so it can sometimes be more efficient than working with strings

This provides some useful features, as changing the content of a char sequence passed as parameter inside another method, which you can't do with Strings.

private void addWhereClause(StringBuilder sql, String column, String value) {
   //WARNING: only as an example, never append directly a value to a SQL String, or you'll be exposed to SQL Injection
   sql.append(" where ").append(column).append(" = ").append(value);
}

More info at http://docs.oracle.com/javase/tutorial/java/data/buffers.html

How to install a Notepad++ plugin offline?

The solution for me is:

  1. Put the plugin inside /plugin folder (for me it's XMLTools.dll, with some additional files that is instructed to be placed in the installdir)
  2. "Run as administrator" on notepad++.exe
  3. Settings>Import>Import plugin(s)..., browse to intended .dll, select it
  4. Prompt comes up telling me to restart
  5. Done!

Spring Resttemplate exception handling

Here is my POST method with HTTPS which returns a response body for any type of bad responses.

public String postHTTPSRequest(String url,String requestJson)
{
    //SSL Context
    CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);
    //Initiate REST Template
    RestTemplate restTemplate = new RestTemplate(requestFactory);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    //Send the Request and get the response.
    HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
    ResponseEntity<String> response;
    String stringResponse = "";
    try {
        response = restTemplate.postForEntity(url, entity, String.class);
        stringResponse = response.getBody();
    }
    catch (HttpClientErrorException e)
    {
        stringResponse = e.getResponseBodyAsString();
    }
    return stringResponse;
}

nodeJS - How to create and read session with express

It is cumbersome to interoperate socket.io and connect sessions support. The problem is not because socket.io "hijacks" request somehow, but because certain socket.io transports (I think flashsockets) don't support cookies. I could be wrong with cookies, but my approach is the following:

  1. Implement a separate session store for socket.io that stores data in the same format as connect-redis
  2. Make connect session cookie not http-only so it's accessible from client JS
  3. Upon a socket.io connection, send session cookie over socket.io from browser to server
  4. Store the session id in a socket.io connection, and use it to access session data from redis.

how to convert numeric to nvarchar in sql command

If the culture of the result doesn't matters or we're only talking of integer values, CONVERT or CAST will be fine.

However, if the result must match a specific culture, FORMAT might be the function to go:

DECLARE @value DECIMAL(19,4) = 1505.5698
SELECT CONVERT(NVARCHAR, @value)        -->  1505.5698
SELECT FORMAT(@value, 'N2', 'en-us')    --> 1,505.57
SELECT FORMAT(@value, 'N2', 'de-de')    --> 1.505,57

For more information on FORMAT see here.

Of course, formatting the result should be a matter of the UI layer of the software.

How do you develop Java Servlets using Eclipse?

I use Eclipse Java EE edition

Create a "Dynamic Web Project"

Install a local server in the server view, for the version of Tomcat I'm using. Then debug, and run on that server for testing.

When I deploy I export the project to a war file.

C - determine if a number is prime

After reading this question, I was intrigued by the fact that some answers offered optimization by running a loop with multiples of 2*3=6.

So I create a new function with the same idea, but with multiples of 2*3*5=30.

int check235(unsigned long n)
{
    unsigned long sq, i;

    if(n<=3||n==5)
        return n>1;

    if(n%2==0 || n%3==0 || n%5==0)
        return 0;

    if(n<=30)
        return checkprime(n); /* use another simplified function */

    sq=ceil(sqrt(n));
    for(i=7; i<=sq; i+=30)
        if (n%i==0 || n%(i+4)==0 || n%(i+6)==0 || n%(i+10)==0 || n%(i+12)==0 
           || n%(i+16)==0 || n%(i+22)==0 || n%(i+24)==0)
            return 0;

        return 1;
}

By running both functions and checking times I could state that this function is really faster. Lets see 2 tests with 2 different primes:

$ time ./testprimebool.x 18446744069414584321 0
f(2,3)
Yes, its prime.    
real    0m14.090s
user    0m14.096s
sys     0m0.000s

$ time ./testprimebool.x 18446744069414584321 1
f(2,3,5)
Yes, its prime.    
real    0m9.961s
user    0m9.964s
sys     0m0.000s

$ time ./testprimebool.x 18446744065119617029 0
f(2,3)
Yes, its prime.    
real    0m13.990s
user    0m13.996s
sys     0m0.004s

$ time ./testprimebool.x 18446744065119617029 1
f(2,3,5)
Yes, its prime.    
real    0m10.077s
user    0m10.068s
sys     0m0.004s

So I thought, would someone gain too much if generalized? I came up with a function that will do a siege first to clean a given list of primordial primes, and then use this list to calculate the bigger one.

int checkn(unsigned long n, unsigned long *p, unsigned long t)
{
    unsigned long sq, i, j, qt=1, rt=0;
    unsigned long *q, *r;

    if(n<2)
        return 0;

    for(i=0; i<t; i++)
    {
        if(n%p[i]==0)
            return 0;
        qt*=p[i];
    }
    qt--;

    if(n<=qt)
        return checkprime(n); /* use another simplified function */

    if((q=calloc(qt, sizeof(unsigned long)))==NULL)
    {
        perror("q=calloc()");
        exit(1);
    }
    for(i=0; i<t; i++)
        for(j=p[i]-2; j<qt; j+=p[i])
            q[j]=1;

    for(j=0; j<qt; j++)
        if(q[j])
            rt++;

    rt=qt-rt;
    if((r=malloc(sizeof(unsigned long)*rt))==NULL)
    {
        perror("r=malloc()");
        exit(1);
    }
    i=0;
    for(j=0; j<qt; j++)
        if(!q[j])
            r[i++]=j+1;

    free(q);

    sq=ceil(sqrt(n));
    for(i=1; i<=sq; i+=qt+1)
    {
        if(i!=1 && n%i==0)
            return 0;
        for(j=0; j<rt; j++)
            if(n%(i+r[j])==0)
                return 0;
    }
    return 1;
}

I assume I did not optimize the code, but it's fair. Now, the tests. Because so many dynamic memory, I expected the list 2 3 5 to be a little slower than the 2 3 5 hard-coded. But it was ok as you can see bellow. After that, time got smaller and smaller, culminating the best list to be:

2 3 5 7 11 13 17 19

With 8.6 seconds. So if someone would create a hardcoded program that makes use of such technique I would suggest use the list 2 3 and 5, because the gain is not that big. But also, if willing to code, this list is ok. Problem is you cannot state all cases without a loop, or your code would be very big (There would be 1658879 ORs, that is || in the respective internal if). The next list:

2 3 5 7 11 13 17 19 23

time started to get bigger, with 13 seconds. Here the whole test:

$ time ./testprimebool.x 18446744065119617029 2 3 5
f(2,3,5)
Yes, its prime.
real    0m12.668s
user    0m12.680s
sys     0m0.000s

$ time ./testprimebool.x 18446744065119617029 2 3 5 7
f(2,3,5,7)
Yes, its prime.
real    0m10.889s
user    0m10.900s
sys     0m0.000s

$ time ./testprimebool.x 18446744065119617029 2 3 5 7 11
f(2,3,5,7,11)
Yes, its prime.
real    0m10.021s
user    0m10.028s
sys     0m0.000s

$ time ./testprimebool.x 18446744065119617029 2 3 5 7 11 13
f(2,3,5,7,11,13)
Yes, its prime.
real    0m9.351s
user    0m9.356s
sys     0m0.004s

$ time ./testprimebool.x 18446744065119617029 2 3 5 7 11 13 17
f(2,3,5,7,11,13,17)
Yes, its prime.
real    0m8.802s
user    0m8.800s
sys     0m0.008s

$ time ./testprimebool.x 18446744065119617029 2 3 5 7 11 13 17 19
f(2,3,5,7,11,13,17,19)
Yes, its prime.
real    0m8.614s
user    0m8.564s
sys     0m0.052s

$ time ./testprimebool.x 18446744065119617029 2 3 5 7 11 13 17 19 23
f(2,3,5,7,11,13,17,19,23)
Yes, its prime.
real    0m13.013s
user    0m12.520s
sys     0m0.504s

$ time ./testprimebool.x 18446744065119617029 2 3 5 7 11 13 17 19 23 29
f(2,3,5,7,11,13,17,19,23,29)                                                                                                                         
q=calloc(): Cannot allocate memory

PS. I did not free(r) intentionally, giving this task to the OS, as the memory would be freed as soon as the program exited, to gain some time. But it would be wise to free it if you intend to keep running your code after the calculation.


BONUS

int check2357(unsigned long n)
{
    unsigned long sq, i;

    if(n<=3||n==5||n==7)
        return n>1;

    if(n%2==0 || n%3==0 || n%5==0 || n%7==0)
        return 0;

    if(n<=210)
        return checkprime(n); /* use another simplified function */

    sq=ceil(sqrt(n));
    for(i=11; i<=sq; i+=210)
    {    
        if(n%i==0 || n%(i+2)==0 || n%(i+6)==0 || n%(i+8)==0 || n%(i+12)==0 || 
   n%(i+18)==0 || n%(i+20)==0 || n%(i+26)==0 || n%(i+30)==0 || n%(i+32)==0 || 
   n%(i+36)==0 || n%(i+42)==0 || n%(i+48)==0 || n%(i+50)==0 || n%(i+56)==0 || 
   n%(i+60)==0 || n%(i+62)==0 || n%(i+68)==0 || n%(i+72)==0 || n%(i+78)==0 || 
   n%(i+86)==0 || n%(i+90)==0 || n%(i+92)==0 || n%(i+96)==0 || n%(i+98)==0 || 
   n%(i+102)==0 || n%(i+110)==0 || n%(i+116)==0 || n%(i+120)==0 || n%(i+126)==0 || 
   n%(i+128)==0 || n%(i+132)==0 || n%(i+138)==0 || n%(i+140)==0 || n%(i+146)==0 || 
   n%(i+152)==0 || n%(i+156)==0 || n%(i+158)==0 || n%(i+162)==0 || n%(i+168)==0 || 
   n%(i+170)==0 || n%(i+176)==0 || n%(i+180)==0 || n%(i+182)==0 || n%(i+186)==0 || 
   n%(i+188)==0 || n%(i+198)==0)
            return 0;
    }
    return 1;
}

Time:

$ time ./testprimebool.x 18446744065119617029 7
h(2,3,5,7)
Yes, its prime.
real    0m9.123s
user    0m9.132s
sys     0m0.000s

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

I ran into this exact same error message. I tried Aditi's example, and then I realized what the real issue was. (Because I had another apiEndpoint making a similar call that worked fine.) In this case The object in my list had not had an interface extracted from it yet. So because I apparently missed a step, when it went to do the bind to the

List<OfthisModelType>

It failed to deserialize.

If you see this issue, check to see if that could be the issue.

python pandas dataframe to dictionary

mydict = dict(zip(df.id, df.value))

Expression must be a modifiable L-value

lvalue means "left value" -- it should be assignable. You cannot change the value of text since it is an array, not a pointer.

Either declare it as char pointer (in this case it's better to declare it as const char*):

const char *text;
if(number == 2) 
    text = "awesome"; 
else 
    text = "you fail";

Or use strcpy:

char text[60];
if(number == 2) 
    strcpy(text, "awesome"); 
else 
    strcpy(text, "you fail");

Simpler way to check if variable is not equal to multiple string values?

An alternative that might make sense especially if this test is being made multiple times and you are running PHP 7+ and have installed the Set class is:

use Ds\Set;

$strings = new Set(['uk', 'in']);    
if (!$strings->contains($some_variable)) {

Or on any version of PHP you can use an associative array to simulate a set:

$strings = ['uk' => 1, 'in' => 1];
if (!isset($strings[$some_variable])) {

There is additional overhead in creating the set but each test then becomes an O(1) operation. Of course the savings becomes greater the longer the list of strings being compared is.

Why don't self-closing script elements work?

To add to what Brad and squadette have said, the self-closing XML syntax <script /> actually is correct XML, but for it to work in practice, your web server also needs to send your documents as properly formed XML with an XML mimetype like application/xhtml+xml in the HTTP Content-Type header (and not as text/html).

However, sending an XML mimetype will cause your pages not to be parsed by IE7, which only likes text/html.

From w3:

In summary, 'application/xhtml+xml' SHOULD be used for XHTML Family documents, and the use of 'text/html' SHOULD be limited to HTML-compatible XHTML 1.0 documents. 'application/xml' and 'text/xml' MAY also be used, but whenever appropriate, 'application/xhtml+xml' SHOULD be used rather than those generic XML media types.

I puzzled over this a few months ago, and the only workable (compatible with FF3+ and IE7) solution was to use the old <script></script> syntax with text/html (HTML syntax + HTML mimetype).

If your server sends the text/html type in its HTTP headers, even with otherwise properly formed XHTML documents, FF3+ will use its HTML rendering mode which means that <script /> will not work (this is a change, Firefox was previously less strict).

This will happen regardless of any fiddling with http-equiv meta elements, the XML prolog or doctype inside your document -- Firefox branches once it gets the text/html header, that determines whether the HTML or XML parser looks inside the document, and the HTML parser does not understand <script />.

Inner join with count() on three tables

It makes more sense to join the item with the orders than with the people !

SELECT
    people.pe_name,
    COUNT(distinct orders.ord_id) AS num_orders,
    COUNT(items.item_id) AS num_items
FROM
    people
    INNER JOIN orders ON orders.pe_id = people.pe_id
         INNER JOIN items ON items.ord_id = orders.ord_id
GROUP BY
    people.pe_id;

Joining the items with the people provokes a lot of doublons. For example, the cake items in order 3 will be linked with the order 2 via the join between the people, and you don't want this to happen !!

So :

1- You need a good understanding of your schema. Items are link to orders, and not to people.

2- You need to count distinct orders for one person, else you will count as many items as orders.

How to add button tint programmatically

Seems like views have own mechanics for tint management, so better will be put tint list:

ViewCompat.setBackgroundTintList(
    editText, 
    ColorStateList.valueOf(errorColor));

Node.js quick file server (static files over HTTP)

A good "ready-to-use tool" option could be http-server:

npm install http-server -g

To use it:

cd D:\Folder
http-server

Or, like this:

http-server D:\Folder

Check it out: https://github.com/nodeapps/http-server

How do I convert a C# List<string[]> to a Javascript array?

Here's how you accomplish that:

//View.cshtml
<script type="text/javascript">
    var arrayOfArrays = JSON.parse('@Html.Raw(Json.Encode(Model.Addresses))');
</script>

C# using streams

To expand a little on other answers here, and help explain a lot of the example code you'll see dotted about, most of the time you don't read and write to a stream directly. Streams are a low-level means to transfer data.

You'll notice that the functions for reading and writing are all byte orientated, e.g. WriteByte(). There are no functions for dealing with integers, strings etc. This makes the stream very general-purpose, but less simple to work with if, say, you just want to transfer text.

However, .NET provides classes that convert between native types and the low-level stream interface, and transfers the data to or from the stream for you. Some notable such classes are:

StreamWriter // Badly named. Should be TextWriter.
StreamReader // Badly named. Should be TextReader.
BinaryWriter
BinaryReader

To use these, first you acquire your stream, then you create one of the above classes and associate it with the stream. E.g.

MemoryStream memoryStream = new MemoryStream();
StreamWriter myStreamWriter = new StreamWriter(memoryStream);

StreamReader and StreamWriter convert between native types and their string representations then transfer the strings to and from the stream as bytes. So

myStreamWriter.Write(123);

will write "123" (three characters '1', '2' then '3') to the stream. If you're dealing with text files (e.g. html), StreamReader and StreamWriter are the classes you would use.

Whereas

myBinaryWriter.Write(123);

will write four bytes representing the 32-bit integer value 123 (0x7B, 0x00, 0x00, 0x00). If you're dealing with binary files or network protocols BinaryReader and BinaryWriter are what you might use. (If you're exchanging data with networks or other systems, you need to be mindful of endianness, but that's another post.)

What does "exited with code 9009" mean during this build?

Yet another reason: If your pre-build event references another projects bin path and you see this error when running msbuild, but not Visual Studio, then you have to manually arrange the projects in the *.sln file (with a text editor) so that the project you are targeting in the event is built before the event's project. In other words, msbuild uses the order that projects are listed in the *.sln file whereas VS uses knowledge of project dependencies. I had this happen when a tool that creates a database to be included in a wixproj was listed after the wixproj.

Django set default form values

I had this other solution (I'm posting it in case someone else as me is using the following method from the model):

class onlyUserIsActiveField(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(onlyUserIsActiveField, self).__init__(*args, **kwargs)
        self.fields['is_active'].initial = False

    class Meta:
        model = User
        fields = ['is_active']
        labels = {'is_active': 'Is Active'}
        widgets = {
            'is_active': forms.CheckboxInput( attrs={
                            'class':          'form-control bootstrap-switch',
                            'data-size':      'mini',
                            'data-on-color':  'success',
                            'data-on-text':   'Active',
                            'data-off-color': 'danger',
                            'data-off-text':  'Inactive',
                            'name':           'is_active',

            })
        }

The initial is definded on the __init__ function as self.fields['is_active'].initial = False

How to convert file to base64 in JavaScript?

const fileInput = document.querySelector('input');

fileInput.addEventListener('change', (e) => {

// get a reference to the file
const file = e.target.files[0];

// encode the file using the FileReader API
const reader = new FileReader();
reader.onloadend = () => {

    // use a regex to remove data url part
    const base64String = reader.result
        .replace('data:', '')
        .replace(/^.+,/, '');

    // log to console
    // logs wL2dvYWwgbW9yZ...
    console.log(base64String);
};
reader.readAsDataURL(file);});

Default settings Raspberry Pi /etc/network/interfaces

These are the default settings I have for /etc/network/interfaces (including WiFi settings) for my Raspberry Pi 1:

auto lo

iface lo inet loopback
iface eth0 inet dhcp

allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp

Git: How to check if a local repo is up to date?

Not really - but I don't see how git fetch would hurt as it won't change any of your local branches.

R adding days to a date

Just use

 as.Date("2001-01-01") + 45

from base R, or date functionality in one of the many contributed packages. My RcppBDT package wraps functionality from Boost Date_Time including things like 'date of third Wednesday' in a given month.

Edit: And egged on by @Andrie, here is a bit more from RcppBDT (which is mostly a test case for Rcpp modules, really).

R> library(RcppBDT)
Loading required package: Rcpp
R> 
R> str(bdt)
Reference class 'Rcpp_date' [package ".GlobalEnv"] with 0 fields
 and 42 methods, of which 31 are possibly relevant:
   addDays, finalize, fromDate, getDate, getDay, getDayOfWeek, getDayOfYear, 
   getEndOfBizWeek, getEndOfMonth, getFirstDayOfWeekAfter,
   getFirstDayOfWeekInMonth, getFirstOfNextMonth, getIMMDate, getJulian, 
   getLastDayOfWeekBefore, getLastDayOfWeekInMonth, getLocalClock, getModJulian,
   getMonth, getNthDayOfWeek, getUTC, getWeekNumber, getYear, initialize, 
   setEndOfBizWeek, setEndOfMonth, setFirstOfNextMonth, setFromLocalClock,
   setFromUTC, setIMMDate, subtractDays
R> bdt$fromDate( as.Date("2001-01-01") )
R> bdt$addDays( 45 )
R> print(bdt)
[1] "2001-02-15"
R> 

PostgreSQL, checking date relative to "today"

This should give you the current date minus 1 year:

select now() - interval '1 year';

jquery ajax get responsetext from http url

The only way that I know that enables you to use ajax cross-domain is JSONP (http://ajaxian.com/archives/jsonp-json-with-padding).

And here's a post that posts some various techniques to achieve cross-domain ajax (http://usejquery.com/posts/9/the-jquery-cross-domain-ajax-guide)

How to copy data from one HDFS to another HDFS?

distcp is used for copying data to and from the hadoop filesystems in parallel. It is similar to the generic hadoop fs -cp command. In the background process, distcp is implemented as a MapReduce job where mappers are only implemented for copying in parallel across the cluster.

Usage:

  • copy one file to another

    % hadoop distcp file1 file2

  • copy directories from one location to another

    % hadoop distcp dir1 dir2

If dir2 doesn't exist then it will create that folder and copy the contents. If dir2 already exists, then dir1 will be copied under it. -overwrite option forces the files to be overwritten within the same folder. -update option updates only the files that are changed.

  • transferring data between two HDFS clusters

    % hadoop distcp -update -delete hdfs://nn1/dir1 hdfs://nn2/dir2

-delete option deletes the files or directories from the destination that are not present in the source.

use video as background for div

I believe this is what you're looking for. It automatically scaled the video to fit the container.

DEMO: http://jsfiddle.net/t8qhgxuy/

Video need to have height and width always set to 100% of the parent.

HTML:

<div class="one"> CONTENT OVER VIDEO
    <video class="video-background" no-controls autoplay src="https://dl.dropboxusercontent.com/u/8974822/cloud-troopers-video.mp4" poster="http://thumb.multicastmedia.com/thumbs/aid/w/h/t1351705158/1571585.jpg"></video>
</div>

<div class="two">
    <video class="video-background" no-controls autoplay src="https://dl.dropboxusercontent.com/u/8974822/cloud-troopers-video.mp4" poster="http://thumb.multicastmedia.com/thumbs/aid/w/h/t1351705158/1571585.jpg"></video> CONTENT OVER VIDEO
</div>

CSS:

body {
    overflow: scroll;
    padding:  60px 20px;
}

.one {
    width: 90%;
    height: 30vw;
    overflow: hidden;
    border: 15px solid red;
    margin-bottom: 40px;
    position: relative;
}

.two{
    width: 30%;
    height: 300px;
    overflow: hidden;
    border: 15px solid blue;
    position: relative;
}

.video-background { /* class name used in javascript too */
    width: 100%; /* width needs to be set to 100% */
    height: 100%; /* height needs to be set to 100% */
    position: absolute;
    left: 0;
    top: 0;
    z-index: -1;
}

JS:

function scaleToFill() {
    $('video.video-background').each(function(index, videoTag) {
       var $video = $(videoTag),
           videoRatio = videoTag.videoWidth / videoTag.videoHeight,
           tagRatio = $video.width() / $video.height(),
           val;

       if (videoRatio < tagRatio) {
           val = tagRatio / videoRatio * 1.02; <!-- size increased by 2% because value is not fine enough and sometimes leaves a couple of white pixels at the edges -->
       } else if (tagRatio < videoRatio) {
           val = videoRatio / tagRatio * 1.02;
       }

       $video.css('transform','scale(' + val  + ',' + val + ')');

    });    
}

$(function () {
    scaleToFill();

    $('.video-background').on('loadeddata', scaleToFill);

    $(window).resize(function() {
        scaleToFill();
    });
});

What is external linkage and internal linkage?

In terms of 'C' (Because static keyword has different meaning between 'C' & 'C++')

Lets talk about different scope in 'C'

SCOPE: It is basically how long can I see something and how far.

  1. Local variable : Scope is only inside a function. It resides in the STACK area of RAM. Which means that every time a function gets called all the variables that are the part of that function, including function arguments are freshly created and are destroyed once the control goes out of the function. (Because the stack is flushed every time function returns)

  2. Static variable: Scope of this is for a file. It is accessible every where in the file
    in which it is declared. It resides in the DATA segment of RAM. Since this can only be accessed inside a file and hence INTERNAL linkage. Any
    other files cannot see this variable. In fact STATIC keyword is the only way in which we can introduce some level of data or function
    hiding in 'C'

  3. Global variable: Scope of this is for an entire application. It is accessible form every where of the application. Global variables also resides in DATA segment Since it can be accessed every where in the application and hence EXTERNAL Linkage

By default all functions are global. In case, if you need to hide some functions in a file from outside, you can prefix the static keyword to the function. :-)

Send Message in C#

public static extern int FindWindow(string lpClassName, String lpWindowName);

In order to find the window, you need the class name of the window. Here are some examples:

C#:

const string lpClassName = "Winamp v1.x";
IntPtr hwnd = FindWindow(lpClassName, null);

Example from a program that I made, written in VB:

hParent = FindWindow("TfrmMain", vbNullString)

In order to get the class name of a window, you'll need something called Win Spy

Once you have the handle of the window, you can send messages to it using the SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam) function.

hWnd, here, is the result of the FindWindow function. In the above examples, this will be hwnd and hParent. It tells the SendMessage function which window to send the message to.

The second parameter, wMsg, is a constant that signifies the TYPE of message that you are sending. The message might be a keystroke (e.g. send "the enter key" or "the space bar" to a window), but it might also be a command to close the window (WM_CLOSE), a command to alter the window (hide it, show it, minimize it, alter its title, etc.), a request for information within the window (getting the title, getting text within a text box, etc.), and so on. Some common examples include the following:

Public Const WM_CHAR = &H102
Public Const WM_SETTEXT = &HC
Public Const WM_KEYDOWN = &H100
Public Const WM_KEYUP = &H101
Public Const WM_LBUTTONDOWN = &H201
Public Const WM_LBUTTONUP = &H202
Public Const WM_CLOSE = &H10
Public Const WM_COMMAND = &H111
Public Const WM_CLEAR = &H303
Public Const WM_DESTROY = &H2
Public Const WM_GETTEXT = &HD
Public Const WM_GETTEXTLENGTH = &HE
Public Const WM_LBUTTONDBLCLK = &H203

These can be found with an API viewer (or a simple text editor, such as notepad) by opening (Microsoft Visual Studio Directory)/Common/Tools/WINAPI/winapi32.txt.

The next two parameters are certain details, if they are necessary. In terms of pressing certain keys, they will specify exactly which specific key is to be pressed.

C# example, setting the text of windowHandle with WM_SETTEXT:

x = SendMessage(windowHandle, WM_SETTEXT, new IntPtr(0), m_strURL);

More examples from a program that I made, written in VB, setting a program's icon (ICON_BIG is a constant which can be found in winapi32.txt):

Call SendMessage(hParent, WM_SETICON, ICON_BIG, ByVal hIcon)

Another example from VB, pressing the space key (VK_SPACE is a constant which can be found in winapi32.txt):

Call SendMessage(button%, WM_KEYDOWN, VK_SPACE, 0)
Call SendMessage(button%, WM_KEYUP, VK_SPACE, 0)

VB sending a button click (a left button down, and then up):

Call SendMessage(button%, WM_LBUTTONDOWN, 0, 0&)
Call SendMessage(button%, WM_LBUTTONUP, 0, 0&)

No idea how to set up the listener within a .DLL, but these examples should help in understanding how to send the message.

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

I'm glad that worked out, so I guess you had to explicitly set 'auto' on IE6 in order for it to mimic other browsers!

I actually recently found another technique for scaling images, again designed for backgrounds. This technique has some interesting features:

  1. The image aspect ratio is preserved
  2. The image's original size is maintained (that is, it can never shrink only grow)

The markup relies on a wrapper element:

<div id="wrap"><img src="test.png" /></div>

Given the above markup you then use these rules:

#wrap {
  height: 100px;
  width: 100px;
}
#wrap img {
  min-height: 100%;
  min-width: 100%;
}

If you then control the size of wrapper you get the interesting scale effects that I list above.

To be explicit, consider the following base state: A container that is 100x100 and an image that is 10x10. The result is a scaled image of 100x100.

  1. Starting at the base state, the container resized to 20x100, the image stays resized at 100x100.
  2. Starting at the base state, the image is changed to 10x20, the image resizes to 100x200.

So, in other words, the image is always at least as big as the container, but will scale beyond it to maintain it's aspect ratio.

This probably isn't useful for your site, and it doesn't work in IE6. But, it is useful to get a scaled background for your view port or container.

Is there a way to get the source code from an APK file?

Simple way: use online tool https://www.decompiler.com/, upload apk and get source code.


Procedure for decoding .apk files, step-by-step method:

Step 1:

  1. Make a new folder and copy over the .apk file that you want to decode.

  2. Now rename the extension of this .apk file to .zip (e.g. rename from filename.apk to filename.zip) and save it. Now you can access the classes.dex files, etc. At this stage you are able to see drawables but not xml and java files, so continue.

Step 2:

  1. Now extract this .zip file in the same folder (or NEW FOLDER).

  2. Download dex2jar and extract it to the same folder (or NEW FOLDER).

  3. Move the classes.dex file into the dex2jar folder.

  4. Now open command prompt and change directory to that folder (or NEW FOLDER). Then write d2j-dex2jar classes.dex (for mac terminal or ubuntu write ./d2j-dex2jar.sh classes.dex) and press enter. You now have the classes.dex.dex2jar file in the same folder.

  5. Download java decompiler, double click on jd-gui, click on open file, and open classes.dex.dex2jar file from that folder: now you get class files.

  6. Save all of these class files (In jd-gui, click File -> Save All Sources) by src name. At this stage you get the java source but the .xml files are still unreadable, so continue.

Step 3:

Now open another new folder

  1. Put in the .apk file which you want to decode

  2. Download the latest version of apktool AND apktool install window (both can be downloaded from the same link) and place them in the same folder

  3. Open a command window

  4. Now run command like apktool if framework-res.apk (if you don't have it get it here)and next

  5. apktool d myApp.apk (where myApp.apk denotes the filename that you want to decode)

now you get a file folder in that folder and can easily read the apk's xml files.

Step 4:

It's not any step, just copy contents of both folders(in this case, both new folders) to the single one

and enjoy the source code...

How to set the text/value/content of an `Entry` widget using a button in tkinter

You might want to use insert method. You can find the documentation for the Tkinter Entry Widget here.

This script inserts a text into Entry. The inserted text can be changed in command parameter of the Button.

from tkinter import *

def set_text(text):
    e.delete(0,END)
    e.insert(0,text)
    return

win = Tk()

e = Entry(win,width=10)
e.pack()

b1 = Button(win,text="animal",command=lambda:set_text("animal"))
b1.pack()

b2 = Button(win,text="plant",command=lambda:set_text("plant"))
b2.pack()

win.mainloop()

CMake: How to build external projects and include their targets

This post has a reasonable answer:

CMakeLists.txt.in:

cmake_minimum_required(VERSION 2.8.2)

project(googletest-download NONE)

include(ExternalProject)
ExternalProject_Add(googletest
  GIT_REPOSITORY    https://github.com/google/googletest.git
  GIT_TAG           master
  SOURCE_DIR        "${CMAKE_BINARY_DIR}/googletest-src"
  BINARY_DIR        "${CMAKE_BINARY_DIR}/googletest-build"
  CONFIGURE_COMMAND ""
  BUILD_COMMAND     ""
  INSTALL_COMMAND   ""
  TEST_COMMAND      ""
)

CMakeLists.txt:

# Download and unpack googletest at configure time
configure_file(CMakeLists.txt.in
               googletest-download/CMakeLists.txt)
execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" .
  WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download )
execute_process(COMMAND ${CMAKE_COMMAND} --build .
  WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download )

# Prevent GoogleTest from overriding our compiler/linker options
# when building with Visual Studio
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)

# Add googletest directly to our build. This adds
# the following targets: gtest, gtest_main, gmock
# and gmock_main
add_subdirectory(${CMAKE_BINARY_DIR}/googletest-src
                 ${CMAKE_BINARY_DIR}/googletest-build)

# The gtest/gmock targets carry header search path
# dependencies automatically when using CMake 2.8.11 or
# later. Otherwise we have to add them here ourselves.
if (CMAKE_VERSION VERSION_LESS 2.8.11)
  include_directories("${gtest_SOURCE_DIR}/include"
                      "${gmock_SOURCE_DIR}/include")
endif()

# Now simply link your own targets against gtest, gmock,
# etc. as appropriate

However it does seem quite hacky. I'd like to propose an alternative solution - use Git submodules.

cd MyProject/dependencies/gtest
git submodule add https://github.com/google/googletest.git
cd googletest
git checkout release-1.8.0
cd ../../..
git add *
git commit -m "Add googletest"

Then in MyProject/dependencies/gtest/CMakeList.txt you can do something like:

cmake_minimum_required(VERSION 3.3)

if(TARGET gtest) # To avoid diamond dependencies; may not be necessary depending on you project.
    return()
endif()

add_subdirectory("googletest")

I haven't tried this extensively yet but it seems cleaner.

Edit: There is a downside to this approach: The subdirectory might run install() commands that you don't want. This post has an approach to disable them but it was buggy and didn't work for me.

Edit 2: If you use add_subdirectory("googletest" EXCLUDE_FROM_ALL) it seems means the install() commands in the subdirectory aren't used by default.

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

If you already have MinGW installed in Windows 7, just simply do the following:

  1. Make another copy of C:\MinGW\bin\mingw32-make.exe file in the same folder.
  2. Rename the file name from mingw32-make.exe to make.exe.
  3. Run make command again.

Tested working in my laptop for above steps.

Entity Framework: There is already an open DataReader associated with this Command

In my case the issue had nothing to do with MARS connection string but with json serialization. After upgrading my project from NetCore2 to 3 i got this error.

More information can be found here

What's the best practice using a settings file in Python?

You can have a regular Python module, say config.py, like this:

truck = dict(
    color = 'blue',
    brand = 'ford',
)
city = 'new york'
cabriolet = dict(
    color = 'black',
    engine = dict(
        cylinders = 8,
        placement = 'mid',
    ),
    doors = 2,
)

and use it like this:

import config
print(config.truck['color'])  

Best practices for adding .gitignore file for Python projects?

Covers most of the general stuff -

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
#  Usually these files are written by a python script from a template
#  before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/

Reference: python .gitignore

How display only years in input Bootstrap Datepicker?

always year for bootstrap 3 datetimepicker https://eonasdan.github.io/bootstrap-datetimepicker/

   $('#year').datetimepicker({
        format: 'YYYY',
        viewMode: "years",
    });

    $("#year").on("dp.hide", function (e) {
        $('#year').datetimepicker('destroy');
        $('#year').datetimepicker({
            format: 'YYYY',
            viewMode: "years",
        });
    });

Maintain the aspect ratio of a div with CSS

I guess just using rem or em should solve the problem of fixed ratio but wont be hard bound to the screen as vw or vh or as painfull to use with flexbox as % is. Well, none of the answers worked properly for me, and in my case this attended me:

<div class="container">
   <div>
   </div>
</div>
.container {
   height: 100vh;
   width: 100vw;
}
.container div {
   height: 4em;
   width: 3em;
}

Or using rem. But anyway, any of them should make it.
rem uses the default font-size value as em use the closest font-size.

How to loop through all elements of a form jQuery

Do one of the two jQuery serializers inside your form submit to get all inputs having a submitted value.

var criteria = $(this).find('input,select').filter(function () {
    return ((!!this.value) && (!!this.name));
}).serializeArray();

var formData = JSON.stringify(criteria);

serializeArray() will produce an array of names and values

0: {name: "OwnLast", value: "Bird"}
1: {name: "OwnFirst", value: "Bob"}
2: {name: "OutBldg[]", value: "PDG"}
3: {name: "OutBldg[]", value: "PDA"}

var criteria = $(this).find('input,select').filter(function () {
    return ((!!this.value) && (!!this.name));
}).serialize();

serialize() creates a text string in standard URL-encoded notation

"OwnLast=Bird&OwnFirst=Bob&OutBldg%5B%5D=PDG&OutBldg%5B%5D=PDA"

Method with a bool return

     public bool roomSelected()
    {
        int a = 0;
        foreach (RadioButton rb in GroupBox1.Controls)
        {
            if (rb.Checked == true)
            {
                a = 1;
            }
        }
        if (a == 1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

this how I solved my problem

Creating a daemon in Linux

Try using the daemon function:

#include <unistd.h>

int daemon(int nochdir, int noclose);

From the man page:

The daemon() function is for programs wishing to detach themselves from the controlling terminal and run in the background as system daemons.

If nochdir is zero, daemon() changes the calling process's current working directory to the root directory ("/"); otherwise, the current working directory is left unchanged.

If noclose is zero, daemon() redirects standard input, standard output and standard error to /dev/null; otherwise, no changes are made to these file descriptors.

Set EditText cursor color

Late to the party,Here's is my answer,

This is for the people who are not looking to change the colorAccent in their parent theme,but wants to change EditText attributes!

This answer demos how to change ......

  1. Bottom line color
  2. Cursor color
  3. Cursor pointer color (I used my custom image).......... of EditText using style applied to the Activity theme.

enter image description here

<android.support.v7.widget.AppCompatEditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Hey" />

Example:

<style name="AppTheme.EditText" parent="@style/Widget.AppCompat.EditText">
    <item name="android:textColor">@color/white</item>
    <item name="android:textColorHint">#8AFFFFFF</item>
    <item name="android:background">@drawable/edit_text_background</item> // background (bottom line at this case)
    <item name="android:textCursorDrawable">@color/white</item>  // Cursor
    <item name="android:textSelectHandle">@drawable/my_white_icon</item> // For pointer normal state and copy text state
    <item name="android:textSelectHandleLeft">@drawable/my_white_icon</item>
    <item name="android:textSelectHandleRight">@drawable/my_white_icon</item>
</style>

Now create a drawable(edit_text_background) add a resource xml for the background!You can customize as you want!

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:bottom="0dp"
        android:left="-3dp"   
        android:right="-3dp"
        android:top="-3dp">

        <shape android:shape="rectangle">
            <stroke
                android:width="1dp"
                android:color="@color/white"/>
        </shape>
    </item>
    </layer-list>

Now as you did set this style in your Activity theme.

Example :

In your Activity you have a theme,set this custom editText theme to that.

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Your Theme data -->
    <item name="editTextStyle">@style/AppTheme.EditText</item> // inculude this
</style>