Programs & Examples On #Listboxitem

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

Since the border is used just for visual appearance, you could put it into the ListBoxItem's ControlTemplate and modify the properties there. In the ItemTemplate, you could place only the StackPanel and the TextBlock. In this way, the code also remains clean, as in the appearance of the control will be controlled via the ControlTemplate and the data to be shown will be controlled via the DataTemplate.

C# Listbox Item Double Click Event

It depends whether you ListBox object of the System.Windows.Forms.ListBox class, which does have the ListBox.IndexFromPoint() method. But if the ListBox object is from the System.Windows.Control.Listbox class, the answer from @dark-knight (marked as correct answer) does not work.

Im running Win 10 (1903) and current versions of the .NET framework (4.8). This issue should not be version dependant though, only whether your Application is using WPF or Windows Form for the UI. See also: WPF vs Windows Form

Center HTML Input Text Field Placeholder

you can use also this way to write css for placeholder

input::placeholder{
   text-align: center;
}

What is a method group in C#?

You can cast a method group into a delegate.

The delegate signature selects 1 method out of the group.

This example picks the ToString() overload which takes a string parameter:

Func<string,string> fn = 123.ToString;
Console.WriteLine(fn("00000000"));

This example picks the ToString() overload which takes no parameters:

Func<string> fn = 123.ToString;
Console.WriteLine(fn());

How to print table using Javascript?

You can also use a jQuery plugin to do that

jQuery PrintPage plugin

Demo

How to recursively find the latest modified file in a directory?

I prefer this one, it is shorter:

find . -type f -print0|xargs -0 ls -drt|tail -n 1

How can I add a new column and data to a datatable that already contains data?

Only you want to set default value parameter. This calling third overloading method.

dt.Columns.Add("MyRow", type(System.Int32),0);

Indexes of all occurrences of character in a string

Try this

String str = "helloslkhellodjladfjhello";
String findStr = "hello";

System.out.println(StringUtils.countMatches(str, findStr));

Converting an int or String to a char array on Arduino

None of that stuff worked. Here's a much simpler way .. the label str is the pointer to what IS an array...

String str = String(yourNumber, DEC); // Obviously .. get your int or byte into the string

str = str + '\r' + '\n'; // Add the required carriage return, optional line feed

byte str_len = str.length();

// Get the length of the whole lot .. C will kindly
// place a null at the end of the string which makes
// it by default an array[].
// The [0] element is the highest digit... so we
// have a separate place counter for the array...

byte arrayPointer = 0;

while (str_len)
{
    // I was outputting the digits to the TX buffer

    if ((UCSR0A & (1<<UDRE0))) // Is the TX buffer empty?
    {
        UDR0 = str[arrayPointer];
        --str_len;
        ++arrayPointer;
    }
}

Using LINQ to group a list of objects

var groupedCustomerList = CustomerList
                         .GroupBy(u => u.GroupID, u=>{
                                                        u.Name = "User" + u.Name;
                                                        return u;
                                                     }, (key,g)=>g.ToList())
                         .ToList();

If you don't want to change the original data, you should add some method (kind of clone and modify) to your class like this:

public class Customer {
  public int ID { get; set; }
  public string Name { get; set; }
  public int GroupID { get; set; }
  public Customer CloneWithNamePrepend(string prepend){
    return new Customer(){
          ID = this.ID,
          Name = prepend + this.Name,
          GroupID = this.GroupID
     };
  }
}    
//Then
var groupedCustomerList = CustomerList
                         .GroupBy(u => u.GroupID, u=>u.CloneWithNamePrepend("User"), (key,g)=>g.ToList())
                         .ToList();

I think you may want to display the Customer differently without modifying the original data. If so you should design your class Customer differently, like this:

public class Customer {
  public int ID { get; set; }
  public string Name { get; set; }
  public int GroupID { get; set; }
  public string Prefix {get;set;}
  public string FullName {
    get { return Prefix + Name;}
  }            
}
//then to display the fullname, just get the customer.FullName; 
//You can also try adding some override of ToString() to your class

var groupedCustomerList = CustomerList
                         .GroupBy(u => {u.Prefix="User", return u.GroupID;} , (key,g)=>g.ToList())
                         .ToList();

set gvim font in .vimrc file

I had to end up doing

:set guifont=Courier:h10:cANSI

Is it possible to insert HTML content in XML document?

The purpose of BASE64 encoding is to take binary data and be able to persist that to a string. That benefit comes at a cost, an increase in the size of the result (I think it's a 4 to 3 ratio). There are two solutions. If you know the data will be well formed XML, include it directly. The other, an better option, is to include the HTML in a CDATA section within an element within the XML.

ssh script returns 255 error

If there's a problem with authentication or connection, such as not being able to read a password from the terminal, ssh will exit with 255 without being able to run your actual script. Verify to make sure you can run 'true' instead, to see if the ssh connection is established successfully.

What tools do you use to test your public REST API?

http://www.quadrillian.com/ this enables you to create an entire test suite for your API and run it from your browser and share it with others.

How to limit the maximum files chosen when using multiple file input

You could run some jQuery client-side validation to check:

$(function(){
    $("input[type='submit']").click(function(){
        var $fileUpload = $("input[type='file']");
        if (parseInt($fileUpload.get(0).files.length)>2){
         alert("You can only upload a maximum of 2 files");
        }
    });    
});?

http://jsfiddle.net/Curt/u4NuH/

But remember to check on the server side too as client-side validation can be bypassed quite easily.

pip3: command not found

I had this issue and I fixed it using the following steps You need to completely uninstall python3-p using:

sudo apt-get --purge autoremove python3-pip

Then resintall the package with:

 sudo apt install python3-pip

To confirm that everything works, run:

 pip3 -V

After this you can now use pip3 to manage any python package of your interest. Eg

pip3 install NumPy

count distinct values in spreadsheet

=iferror(counta(unique(A1:A100))) counts number of unique cells from A1 to A100

PDO with INSERT INTO through prepared statements

You should be using it like so

<?php
$dbhost = 'localhost';
$dbname = 'pdo';
$dbusername = 'root';
$dbpassword = '845625';

$link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);

$statement = $link->prepare('INSERT INTO testtable (name, lastname, age)
    VALUES (:fname, :sname, :age)');

$statement->execute([
    'fname' => 'Bob',
    'sname' => 'Desaunois',
    'age' => '18',
]);

Prepared statements are used to sanitize your input, and to do that you can use :foo without any single quotes within the SQL to bind variables, and then in the execute() function you pass in an associative array of the variables you defined in the SQL statement.

You may also use ? instead of :foo and then pass in an array of just the values to input like so;

$statement = $link->prepare('INSERT INTO testtable (name, lastname, age)
    VALUES (?, ?, ?)');

$statement->execute(['Bob', 'Desaunois', '18']);

Both ways have their advantages and disadvantages. I personally prefer to bind the parameter names as it's easier for me to read.

Get all parameters from JSP page

This should print out all Parameters that start with "Question".

<html><body>
<%@ page import = "java.util.*" %>
<b>Parameters:</b><br>
<%
  Enumeration parameterList = request.getParameterNames();
  while( parameterList.hasMoreElements() )
  {
    String sName = parameterList.nextElement().toString();
    if(sName.toLowerCase.startsWith("question")){
      String[] sMultiple = request.getParameterValues( sName );
      if( 1 >= sMultiple.length )
        // parameter has a single value. print it.
        out.println( sName + " = " + request.getParameter( sName ) + "<br>" );
      else
        for( int i=0; i<sMultiple.length; i++ )
          // if a paramater contains multiple values, print all of them
          out.println( sName + "[" + i + "] = " + sMultiple[i] + "<br>" );
    }
  }
%>
</body></html>

Find a value in DataTable

this question asked in 2009 but i want to share my codes:

    Public Function RowSearch(ByVal dttable As DataTable, ByVal searchcolumns As String()) As DataTable

    Dim x As Integer
    Dim y As Integer

    Dim bln As Boolean

    Dim dttable2 As New DataTable
    For x = 0 To dttable.Columns.Count - 1
        dttable2.Columns.Add(dttable.Columns(x).ColumnName)
    Next

    For x = 0 To dttable.Rows.Count - 1
        For y = 0 To searchcolumns.Length - 1
            If String.IsNullOrEmpty(searchcolumns(y)) = False Then
                If searchcolumns(y) = CStr(dttable.Rows(x)(y + 1) & "") & "" Then
                    bln = True
                Else
                    bln = False
                    Exit For
                End If
            End If
        Next
        If bln = True Then
            dttable2.Rows.Add(dttable.Rows(x).ItemArray)
        End If
    Next

    Return dttable2


End Function

Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

By converting the matrix to array by using

n12 = np.squeeze(np.asarray(n2))

X12 = np.squeeze(np.asarray(x1))

solved the issue.

How to sort pandas data frame using values from several columns?

Use of sort can result in warning message. See github discussion. So you might wanna use sort_values, docs here

Then your code can look like this:

df = df.sort_values(by=['c1','c2'], ascending=[False,True])

Extracting jar to specified directory

jars use zip compression so you can use any unzip utility.

Example:

$ unzip myJar.jar -d ./directoryToExtractTo

compilation error: identifier expected

You also will have to catch or throw the IOException. See below. Not always the best way, but it will get you a result:

public class details {
    public static void main( String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

Finding an element in an array in Java

With Java 8, you can do this:

int[] haystack = {1, 2, 3};
int needle = 3;

boolean found = Arrays.stream(haystack).anyMatch(x -> x == needle);

You'd need to do

boolean found = Arrays.stream(haystack).anyMatch(x -> needle.equals(x));

if you're working with objects.

AttributeError: Can only use .dt accessor with datetimelike values

When you write

df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
df['Date'] = df['Date'].dt.strftime('%m/%d')

It can fixed

How to find Google's IP address?

If all you are trying to do is find the IP address that corresponds to a domain name, like google.com, this is very easy on every machine connected to the Internet.

Simply run the ping command from any command prompt. Typing something like

ping google.com

will give you (among other things) that information.

Change background color of R plot

I use abline() with extremely wide vertical lines to fill the plot space:

abline(v = xpoints, col = "grey90", lwd = 80)

You have to create the frame, then the ablines, and then plot the points so they are visible on top. You can even use a second abline() statement to put thin white or black lines over the grey, if desired.

Example:

xpoints = 1:20
y = rnorm(20)
plot(NULL,ylim=c(-3,3),xlim=xpoints)
abline(v=xpoints,col="gray90",lwd=80)
abline(v=xpoints,col="white")
abline(h = 0, lty = 2) 
points(xpoints, y, pch = 16, cex = 1.2, col = "red")

smtpclient " failure sending mail"

Seeing your loop for sending emails and the error which you provided there is only solution.
Declare the mail object out of the loop and assign fromaddress out of the loop which you are using for sending mails. The fromaddress field is getting assigned again and again in the loop that is your problem.

PHP date() format when inserting into datetime in MySQL

Format time stamp to MySQL DATETIME column :

strftime('%Y-%m-%d %H:%M:%S',$timestamp);

MVC which submit button has been pressed

// Buttons
<input name="submit" type="submit" id="submit" value="Save" />
<input name="process" type="submit" id="process" value="Process" />

// Controller
[HttpPost]
public ActionResult index(FormCollection collection)
{
    string submitType = "unknown";

    if(collection["submit"] != null)
    {
        submitType = "submit";
    }
    else if (collection["process"] != null)
    {
        submitType = "process";
    }

} // End of the index method

How to set a timeout on a http.request() in Node?

You should pass the reference to request like below

_x000D_
_x000D_
var options = { ... }_x000D_
var req = http.request(options, function(res) {_x000D_
  // Usual stuff: on(data), on(end), chunks, etc..._x000D_
});_x000D_
_x000D_
req.setTimeout(60000, function(){_x000D_
    this.abort();_x000D_
}).bind(req);_x000D_
req.write('something');_x000D_
req.end();
_x000D_
_x000D_
_x000D_

Request error event will get triggered

_x000D_
_x000D_
req.on("error", function(e){_x000D_
       console.log("Request Error : "+JSON.stringify(e));_x000D_
  });
_x000D_
_x000D_
_x000D_

How to determine the screen width in terms of dp or dip at runtime in Android?

Try this:

Display display   = getWindowManager().getDefaultDisplay();
Point displaySize = new Point();
display.getSize(displaySize);
int width  = displaySize.x;
int height = displaySize.y;

How to copy a row from one SQL Server table to another

Jarrett's answer creates a new table.

Scott's answer inserts into an existing table with the same structure.

You can also insert into a table with different structure:

INSERT Table2
(columnX, columnY)
SELECT column1, column2 FROM Table1
WHERE [Conditions]

How do I make a WPF TextBlock show my text on multiple lines?

Nesting a stackpanel will cause the textbox to wrap properly:

<Viewbox Margin="120,0,120,0">
    <StackPanel Orientation="Vertical" Width="400">
        <TextBlock x:Name="subHeaderText" 
                   FontSize="20" 
                   TextWrapping="Wrap" 
                   Foreground="Black"
                   Text="Lorem ipsum dolor, lorem isum dolor,Lorem ipsum dolor sit amet, lorem ipsum dolor sit amet " />
    </StackPanel>
</Viewbox>

Hunk #1 FAILED at 1. What's that mean?

In my case, the patch was generated perfectly fine by IDEA, however, I edited the patch and saved it which changed CRLF to LF and then the patch stopped working. Curiously, converting it back to CRLF did not work. I noticed in VI editor, that even after setting to DOS format, the '^M' were not added to the end of lines. This forced me to only make changes in VI, so that the EOLs were preserved.

This may apply to you, if you make changes in a non-Windows environment to a patch covering changes between two versions both coming from Windows environment. You want to be careful how you edit such files.

BTW ignore-whitespace did not help.

How do you do block comments in YAML?

One way to block commenting in YAML is by using a text editor like Notepad++ to add a # (comment) tag to multiple lines at once.

In Notepad++ you can do that using the "Block Comment" right-click option for selected text.

Woo Images!

What does "export default" do in JSX?

  • Before learning about Export Default lets understand what is Export and Import is: In the general term: exports are the goods and services that can be sent to others, similarly, export in function components means you are letting your function or component to use by another script.
  • Export default means you want to export only one value the is present by default in your script so that others script can import that for use.
  • This is very much necessary for code Reusability.

Let's see the code of how we can use this

  import react from 'react'

function Header()
{
    return <p><b><h1>This is the Heading section</h1></b></p>;
}
**export default Header;**
  • Because of this export it can be imported like this-

import Header from './Header'; enter image description here

  • if any one comment the export section you will get the following error:

    enter image description here

You will get error like this:- enter image description here

$_POST Array from html form

I don't know if I understand your question, but maybe:

foreach ($_POST as $id=>$value)
    if (strncmp($id,'id[',3) $info[rtrim(ltrim($id,'id['),']')]=$_POST[$id];

would help

That is if you really want to have a different name (id[key]) on each checkbox of the html form (not very efficient). If not you can just name them all the same, i.e. 'id' and iterate on the (selected) values of the array, like: foreach ($_POST['id'] as $key=>$value)...

Keyboard shortcut to paste clipboard content into command prompt window (Win XP)

You could try using Texter and create something unlikely like:

./p , triggered by space and replacing the text with %c

I just tested it and it works fine. The only gotcha is to use a rare sequence, as Texter cannot restrict this to just cmd.

There are probably other utilities of this kind which could work, and even AutoHotKey, upon which Texter is built could do it better, but Texter is easy :-)

Amazon Interview Question: Design an OO parking lot

public class ParkingLot 
{
    Vector<ParkingSpace> vacantParkingSpaces = null;
    Vector<ParkingSpace> fullParkingSpaces = null;

    int parkingSpaceCount = 0;

    boolean isFull;
    boolean isEmpty;

    ParkingSpace findNearestVacant(ParkingType type)
    {
        Iterator<ParkingSpace> itr = vacantParkingSpaces.iterator();

        while(itr.hasNext())
        {
            ParkingSpace parkingSpace = itr.next();

            if(parkingSpace.parkingType == type)
            {
                return parkingSpace;
            }
        }
        return null;
    }

    void parkVehicle(ParkingType type, Vehicle vehicle)
    {
        if(!isFull())
        {
            ParkingSpace parkingSpace = findNearestVacant(type);

            if(parkingSpace != null)
            {
                parkingSpace.vehicle = vehicle;
                parkingSpace.isVacant = false;

                vacantParkingSpaces.remove(parkingSpace);
                fullParkingSpaces.add(parkingSpace);

                if(fullParkingSpaces.size() == parkingSpaceCount)
                    isFull = true;

                isEmpty = false;
            }
        }
    }

    void releaseVehicle(Vehicle vehicle)
    {
        if(!isEmpty())
        {
            Iterator<ParkingSpace> itr = fullParkingSpaces.iterator();

            while(itr.hasNext())
            {
                ParkingSpace parkingSpace = itr.next();

                if(parkingSpace.vehicle.equals(vehicle))
                {
                    fullParkingSpaces.remove(parkingSpace);
                    vacantParkingSpaces.add(parkingSpace);

                    parkingSpace.isVacant = true;
                    parkingSpace.vehicle = null;

                    if(vacantParkingSpaces.size() == parkingSpaceCount)
                        isEmpty = true;

                    isFull = false;
                }
            }
        }
    }

    boolean isFull()
    {
        return isFull;
    }

    boolean isEmpty()
    {
        return isEmpty;
    }
}

public class ParkingSpace 
{
    boolean isVacant;
    Vehicle vehicle;
    ParkingType parkingType;
    int distance;
}

public class Vehicle 
{
    int num;
}

public enum ParkingType
{
    REGULAR,
    HANDICAPPED,
    COMPACT,
    MAX_PARKING_TYPE,
}

SQL update statement in C#

String st = "UPDATE supplier SET supplier_id = " + textBox1.Text + ", supplier_name = " + textBox2.Text
            + "WHERE supplier_id = " + textBox1.Text;

        SqlCommand sqlcom = new SqlCommand(st, myConnection);
        try
        {
            sqlcom.ExecuteNonQuery();
            MessageBox.Show("update successful");
        }
        catch (SqlException ex)
        {
            MessageBox.Show(ex.Message);
        }

Get keys of a Typescript interface as array of strings

This should work

var IMyTable: Array<keyof IMyTable> = ["id", "title", "createdAt", "isDeleted"];

or

var IMyTable: (keyof IMyTable)[] = ["id", "title", "createdAt", "isDeleted"];

How do I create a timer in WPF?

Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.

How to write a unit test for a Spring Boot Controller endpoint

Adding @WebAppConfiguration (org.springframework.test.context.web.WebAppConfiguration) annotation to your DemoApplicationTests class will work.

What is a PDB file?

I had originally asked myself the question "Do I need a PDB file deployed to my customer's machine?", and after reading this post, decided to exclude the file.

Everything worked fine, until today, when I was trying to figure out why a message box containing an Exception.StackTrace was missing the file and line number information - necessary for troubleshooting the exception. I re-read this post and found the key nugget of information: that although the PDB is not necessary for the app to run, it is necessary for the file and line numbers to be present in the StackTrace string. I included the PDB file in the executable folder and now all is fine.

Can't connect to MySQL server error 111

It probably means that your MySQL server is only listening the localhost interface.

If you have lines like this :

bind-address = 127.0.0.1

In your my.cnf configuration file, you should comment them (add a # at the beginning of the lines), and restart MySQL.

sudo service mysql restart

Of course, to do this, you must be the administrator of the server.

How to store custom objects in NSUserDefaults

If anybody is looking for a swift version:

1) Create a custom class for your data

class customData: NSObject, NSCoding {
let name : String
let url : String
let desc : String

init(tuple : (String,String,String)){
    self.name = tuple.0
    self.url = tuple.1
    self.desc = tuple.2
}
func getName() -> String {
    return name
}
func getURL() -> String{
    return url
}
func getDescription() -> String {
    return desc
}
func getTuple() -> (String,String,String) {
    return (self.name,self.url,self.desc)
}

required init(coder aDecoder: NSCoder) {
    self.name = aDecoder.decodeObjectForKey("name") as! String
    self.url = aDecoder.decodeObjectForKey("url") as! String
    self.desc = aDecoder.decodeObjectForKey("desc") as! String
}

func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(self.name, forKey: "name")
    aCoder.encodeObject(self.url, forKey: "url")
    aCoder.encodeObject(self.desc, forKey: "desc")
} 
}

2) To save data use following function:

func saveData()
    {
        let data  = NSKeyedArchiver.archivedDataWithRootObject(custom)
        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.setObject(data, forKey:"customArray" )
    }

3) To retrieve:

if let data = NSUserDefaults.standardUserDefaults().objectForKey("customArray") as? NSData
        {
             custom = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! [customData]
        }

Note: Here I am saving and retrieving an array of the custom class objects.

How can I install a previous version of Python 3 in macOS using homebrew?

The easiest way for me was to install Anaconda: https://docs.anaconda.com/anaconda/install/

There I can create as many environments with different Python versions as I want and switch between them with a mouse click. It could not be easier.

To install different Python versions just follow these instructions https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-python.html

A new development environment with a different Python version was done within 2 minutes. And in the future I can easily switch back and forth.

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

just change the content-type to application/json when you use JSON with POST/PUT, etc...

convert a char* to std::string

I would like to mention a new method which uses the user defined literal s. This isn't new, but it will be more common because it was added in the C++14 Standard Library.

Largely superfluous in the general case:

string mystring = "your string here"s;

But it allows you to use auto, also with wide strings:

auto mystring = U"your UTF-32 string here"s;

And here is where it really shines:

string suffix;
cin >> suffix;
string mystring = "mystring"s + suffix;

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

I'm using Android Studio and as of 19th of January 2016 this did the trick for me. (This seems like something that changes every year or so)

Go to: app -> Gradle Scripts -> build.gradle (Module: app)

Then under model { ... android.ndk { ... and add a line: stl = "gnustl_shared"

Like this:

model {

    ...

    android.ndk {
        moduleName = "gl2jni"
        cppFlags.add("-Werror")
        ldLibs.addAll(["log", "GLESv2"])
        stl = "gnustl_shared"     //  <-- this is the line that I added
    }

    ...

}

Can I apply the required attribute to <select> fields in HTML5?

The <select> element does support the required attribute, as per the spec:

Which browser doesn’t honour this?

(Of course, you have to validate on the server anyway, as you can’t guarantee that users will have JavaScript enabled.)

angularjs directive call function specified in attribute and pass an argument to it

My solution:

  1. on polymer raise an event (eg. complete)
  2. define a directive linking the event to control function

Directive

/*global define */
define(['angular', './my-module'], function(angular, directives) {
    'use strict';
    directives.directive('polimerBinding', ['$compile', function($compile) {

            return {
                 restrict: 'A',
                scope: { 
                    method:'&polimerBinding'
                },
                link : function(scope, element, attrs) {
                    var el = element[0];
                    var expressionHandler = scope.method();
                    var siemEvent = attrs['polimerEvent'];
                    if (!siemEvent) {
                        siemEvent = 'complete';
                    }
                    el.addEventListener(siemEvent, function (e, options) {
                        expressionHandler(e.detail);
                    })
                }
            };
        }]);
});

Polymer component

<dom-module id="search">

<template>
<h3>Search</h3>
<div class="input-group">

    <textarea placeholder="search by expression (eg. temperature>100)"
        rows="10" cols="100" value="{{text::input}}"></textarea>
    <p>
        <button id="button" class="btn input-group__addon">Search</button>
    </p>
</div>
</template>

 <script>
  Polymer({
    is: 'search',
            properties: {
      text: {
        type: String,
        notify: true
      },

    },
    regularSearch: function(e) {
      console.log(this.range);
      this.fire('complete', {'text': this.text});
    },
    listeners: {
        'button.click': 'regularSearch',
    }
  });
</script>

</dom-module>

Page

 <search id="search" polimer-binding="searchData"
 siem-event="complete" range="{{range}}"></siem-search>

searchData is the control function

$scope.searchData = function(searchObject) {
                    alert('searchData '+ searchObject.text + ' ' + searchObject.range);

}

Setting the User-Agent header for a WebClient request

You can also use that:

client.Headers.Add(HttpRequestHeader.UserAgent, "My app.");

Incrementing a date in JavaScript

Getting the next 5 days:

var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();


for(i=0; i < 5; i++){
var curdate = new Date(y, m, d+i)
console.log(curdate)
}

Why is the Java main method static?

Before the main method is called, no objects are instantiated. Having the static keyword means the method can be called without creating any objects first.

JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

Had the same issue recently, solved by adding traditional: true,

Hide/Show Column in an HTML Table

<p><input type="checkbox" name="ch1" checked="checked" /> First Name</p>
.... 
<td class="ch1">...</td>

 <script>
       $(document).ready(function() {
            $('#demo').multiselect();
        });


        $("input:checkbox:not(:checked)").each(function() {
    var column = "table ." + $(this).attr("name");
    $(column).hide();
});

$("input:checkbox").click(function(){
    var column = "table ." + $(this).attr("name");
    $(column).toggle();
});
 </script>

React Native: How to select the next TextInput after pressing the "next" keyboard button?

I created a small library that does this, no code change needed other than replacing your wrapping view and import of TextInput:

import { Form, TextInput } from 'react-native-autofocus'

export default () => (
  <Form>
    <TextInput placeholder="test" />
    <TextInput placeholder="test 2" />
  </Form>
)

https://github.com/zackify/react-native-autofocus

Explained in detail here: https://zach.codes/autofocus-inputs-in-react-native/

How to disable PHP Error reporting in CodeIgniter?

Here is the typical structure of new Codeigniter project:

- application/
- system/
- user_guide/
- index.php <- this is the file you need to change

I usually use this code in my CI index.php. Just change local_server_name to the name of your local webserver.

With this code you can deploy your site to your production server without changing index.php each time.

// Domain-based environment
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
    define('ENVIRONMENT', 'development');
} else {
    define('ENVIRONMENT', 'production');
}

/*
 *---------------------------------------------------------------
 * ERROR REPORTING
 *---------------------------------------------------------------
 *
 * Different environments will require different levels of error reporting.
 * By default development will show errors but testing and live will hide them.
 */

if (defined('ENVIRONMENT')) {
    switch (ENVIRONMENT) {
        case 'development':
            error_reporting(E_ALL);
            break;
        case 'testing':
        case 'production':
            error_reporting(0);
            ini_set('display_errors', 0);  
            break;
        default:
            exit('The application environment is not set correctly.');
    }
}

Converting Numpy Array to OpenCV Array

This is what worked for me...

import cv2
import numpy as np

#Created an image (really an ndarray) with three channels 
new_image = np.ndarray((3, num_rows, num_cols), dtype=int)

#Did manipulations for my project where my array values went way over 255
#Eventually returned numbers to between 0 and 255

#Converted the datatype to np.uint8
new_image = new_image.astype(np.uint8)

#Separated the channels in my new image
new_image_red, new_image_green, new_image_blue = new_image

#Stacked the channels
new_rgb = np.dstack([new_image_red, new_image_green, new_image_blue])

#Displayed the image
cv2.imshow("WindowNameHere", new_rgbrgb)
cv2.waitKey(0)

How to concatenate strings in windows batch file for loop?

Try this, with strings:

set "var=string1string2string3"

and with string variables:

set "var=%string1%%string2%%string3%"

Using :focus to style outer div?

Simple use JQuery.

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $("div .FormRow").focusin(function() {_x000D_
    $(this).css("background-color", "#FFFFCC");_x000D_
    $(this).css("border", "3px solid #555");_x000D_
  });_x000D_
  $("div .FormRow").focusout(function() {_x000D_
    $(this).css("background-color", "#FFFFFF");_x000D_
    $(this).css("border", "0px solid #555");_x000D_
  });_x000D_
});
_x000D_
    .FormRow {_x000D_
      padding: 10px;_x000D_
    }
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div style="border: 0px solid black;padding:10px;">_x000D_
    <div class="FormRow">_x000D_
      First Name:_x000D_
      <input type="text">_x000D_
      <br>_x000D_
    </div>_x000D_
    <div class="FormRow">_x000D_
      Last Name:_x000D_
      <input type="text">_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <ul>_x000D_
    <li><strong><em>Click an input field to get focus.</em></strong>_x000D_
    </li>_x000D_
    <li><strong><em>Click outside an input field to lose focus.</em></strong>_x000D_
    </li>_x000D_
  </ul>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to count objects in PowerShell?

Just use parenthesis and 'count'. This applies to Powershell v3

(get-alias).count

How to initialize array to 0 in C?

If you'd like to initialize the array to values other than 0, with gcc you can do:

int array[1024] = { [ 0 ... 1023 ] = -1 };

This is a GNU extension of C99 Designated Initializers. In older GCC, you may need to use -std=gnu99 to compile your code.

How to match all occurrences of a regex

Using scan should do the trick:

string.scan(/regex/)

How do I get the function name inside a function in PHP?

You can use the magic constants __METHOD__ (includes the class name) or __FUNCTION__ (just function name) depending on if it's a method or a function... =)

Save plot to image file instead of displaying it using Matplotlib

While the question has been answered, I'd like to add some useful tips when using matplotlib.pyplot.savefig. The file format can be specified by the extension:

from matplotlib import pyplot as plt

plt.savefig('foo.png')
plt.savefig('foo.pdf')

Will give a rasterized or vectorized output respectively, both which could be useful. In addition, you'll find that pylab leaves a generous, often undesirable, whitespace around the image. You can remove the whitespace using:

plt.savefig('foo.png', bbox_inches='tight')

How can I run a html file from terminal?

python -mhtmllib test.html or curl http://www.comanyname.com/somepage.html|python -mhtmllib -

Neatest way to remove linebreaks in Perl

To extend Ted Cambron's answer above and something that hasn't been addressed here: If you remove all line breaks indiscriminately from a chunk of entered text, you will end up with paragraphs running into each other without spaces when you output that text later. This is what I use:

sub cleanLines{

    my $text = shift;

    $text =~ s/\r/ /; #replace \r with space
    $text =~ s/\n/ /; #replace \n with space
    $text =~ s/  / /g; #replace double-spaces with single space

    return $text;
}

The last substitution uses the g 'greedy' modifier so it continues to find double-spaces until it replaces them all. (Effectively substituting anything more that single space)

Git Clone - Repository not found

I'm a devops engineer and this happens with private repositories. Since I manage multiple Github organizations, I have a few different SSH keys. To overcome this ERROR: Repository not found. fatal: Could not read from remote repository. error, you can use

export GIT_SSH_COMMAND="ssh -o StrictHostKeyChecking=no -o User=git -i ~/.ssh/ssh_key_for_repo"

git clone [email protected]:user/repo.git

WCF Service Returning "Method Not Allowed"

I've been having this same problem for over a day now - finally figured it out. Thanks to @Sameh for the hint.

Your service is probably working just fine. Testing POST messages using the address bar of a browser won't work. You need to use Fiddler to test a POST message.

Fiddler instructions... http://www.ehow.com/how_8788176_do-post-using-fiddler.html

What is the difference between Builder Design pattern and Factory Design pattern?

Both patterns come for the same necessity: Hide from some client code the construction logic of a complex object. But what makes "complex" (or, sometimes, complicate) an object? Mainly, it's due to dependencies, or rather the state of an object composed by more partial states. You can inject dependencies by constructor to set the initial object state, but an object may require a lot of them, some will be in a default initial state (just because we should have learned that set a default dependency to null is not the cleanest way) and some other set to a state driven by some condition. Moreover, there are object properties that are some kind of "oblivious dependencies" but also they can assume optional states.

there are two well known ways to dominate that complexity:

  • Composition/aggregation: Construct an object, construct its dependent objects, then wire together. Here, a builder can make transparent and flexible the process that determines the rules that lead the construction of component.

  • Polymorphism: Construction rules are declared directly into subtype definition, so you have a set of rules for each subtype and some condition decides which one among these set of rules apply to construct the object. A factory fits perfectly in this scenario.

Nothing prevents to mix these two approaches. A family of product could abstract object creation done with a builder, a builder could use factories to determine which component object instantiate.

VBA Count cells in column containing specified value

This isn't exactly what you are looking for but here is how I've approached this problem in the past;

You can enter a formula like;

=COUNTIF(A1:A10,"Green")

...into a cell. This will count the Number of cells between A1 and A10 that contain the text "Green". You can then select this cell value in a VBA Macro and assign it to a variable as normal.

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

My issue was related to the use of a Filter together with the ListView.

When setting or updating the underlying data model of the ListView, I was doing something like this:

public void updateUnderlyingContacts(List<Contact> newContacts, String filter)
{
    this.allContacts = newContacts;
    this.filteredContacts = newContacts;
    getFilter().filter(filter);
}

Calling filter() in the last line will (and must) cause notifyDataSetChanged() to be called in the Filter's publishResults() method. This may work okay sometimes, specially in my fast Nexus 5. But in reality, it's hiding a bug that you will notice with slower devices or in resource intensive conditions.

The problem is that the filtering is done asynchronously, and thus between the end of the filter() statement and the call to publishResults(), both in the UI thread, some other UI thread code may execute and change the content of the adapter.

The actual fix is easy, just call notifyDataSetChanged() also before requesting the filtering to be performed:

public void updateUnderlyingContacts(List<Contact> newContacts, String filter)
{
    this.allContacts = newContacts;
    this.filteredContacts = newContacts;
    notifyDataSetChanged(); // Fix
    getFilter().filter(filter);
}

Error: 'int' object is not subscriptable - Python

You need to convert age1 into int first, so it can do the minus. After that turn the result back to string for display:

name1 = raw_input("What's your name? ")
age1 = raw_input ("how old are you? ")
twentyone = str(21 - int(age1))
print "Hi, " + name1+ " you will be 21 in: " + twentyone + " years."

Failed to install android-sdk: "java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema"

For Linux users (I'm using a Debian Distro, Kali) Here's how I resolved mine.

If you don't already have jdk-8, you want to get it at oracle's site

https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

I got the jdk-8u191-linux-x64.tar.gz

Step 1 - Installing Java Move and unpack it at a suitable location like so

$ mv jdk-8u191-linux-x64.tar.gz /suitablelocation/
$ tar -xzvf /suitablelocation/jdk-8u191-linux-x64.tar.gz

You should get an unzipped folder like jdk1.8.0_191 You can delete the tarball afterwards to conserve space

Step 2 - Setting up alternatives to the default java location

$ update-alternatives --install /usr/bin/java java /suitablelocation/jdk1.8.0_191/bin/java 1
$ update-alternatives --install /usr/bin/javac javac /suitablelocation/jdk1.8.0_191/bin/javac 1

Step 3 - Selecting your alternatives as default

$ update-alternatives --set java /suitablelocation/jdk1.8.0_191/bin/java
$ update-alternatives --set javac /suitablelocation/jdk1.8.0_191/bin/javac

Step 4 - Confirming default java version

$ java -version

Notes

  1. In the original article here: https://forums.kali.org/showthread.php?41-Installing-Java-on-Kali-Linux, the default plugin for mozilla was also set. I assume we don't really need the plugins as we're simply trying to develop for android.
  2. As in @spassvogel's answer, you should also place a @repositories.cfg file in your ~/.android directory as this is needed to update the tools repo lists
  3. Moving some things around may require root authority. Use sudo wisely.
  4. For sdkmanager usage, see official guide: https://developer.android.com/studio/command-line/sdkmanager

Understanding the Rails Authenticity Token

since Authenticity Token is so important, and in Rails 3.0+ you can use

 <%= token_tag nil %>

to create

<input name="authenticity_token" type="hidden" value="token_value">

anywhere

How to draw circle by canvas in Android?

@Override
public void onDraw(Canvas canvas){
    canvas.drawCircle(xPos, yPos,radius, paint);
}

Above is the code to render a circle. Tweak the parameters to your suiting.

Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

Apologies in advance for this lo-tech suggestion, but another option, which finally worked for me after battling NuGet for several hours, is to re-create a new empty project, Web API in my case, and just copy the guts of your old, now-broken project into the new one. Took me about 15 minutes.

pip install mysql-python fails with EnvironmentError: mysql_config not found

sometimes the error depends on the actual cause. we had a case where mysql-python was installed through the python-mysqldb debian package.

a developer who didn't know this, accidentally ran pip uninstall mysql-python and then failed to recover with pip install mysql-python giving the above error.

pip uninstall mysql-python had destroyed the debian package contents, and of course pip install mysql-python failed because the debian package didn't need any dev files.

the correct solution in that case was apt-get install --reinstall python-mysqldb which restored mysql-python to its original state.

What is the difference between UTF-8 and ISO-8859-1?

  • ASCII: 7 bits. 128 code points.

  • ISO-8859-1: 8 bits. 256 code points.

  • UTF-8: 8-32 bits (1-4 bytes). 1,112,064 code points.

Both ISO-8859-1 and UTF-8 are backwards compatible with ASCII, but UTF-8 is not backwards compatible with ISO-8859-1:

#!/usr/bin/env python3

c = chr(0xa9)
print(c)
print(c.encode('utf-8'))
print(c.encode('iso-8859-1'))

Output:

©
b'\xc2\xa9'
b'\xa9'

jQuery validation plugin: accept only alphabetical characters?

to allow letters ans spaces

jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z\s]+$/i.test(value);
}, "Only alphabetical characters");

$('#yourform').validate({
        rules: {
            name_field: {
                lettersonly: true
            }
        }
    });

Unzipping files

I wrote "Binary Tools for JavaScript", an open source project that includes the ability to unzip, unrar and untar: https://github.com/codedread/bitjs

Used in my comic book reader: https://github.com/codedread/kthoom (also open source).

HTH!

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

Cannot find reference 'xxx' in __init__.py - Python / Pycharm

Make sure you didn't by mistake changed the file type of __init__.py files. If, for example, you changed their type to "Text" (instead of "Python"), PyCharm won't analyze the file for Python code. In that case, you may notice that the file icon for __init__.py files is different from other Python files.

To fix, in Settings > Editor > File Types, in the "Recognized File Types" list click on "Text" and in the "File name patterns" list remove __init__.py.

Using AngularJS date filter with UTC date

If you do use moment.js you would use the moment().utc() function to convert a moment object to UTC. You can also handle a nice format inside the controller instead of the view by using the moment().format() function. For example:

moment(myDate).utc().format('MM/DD/YYYY')

How can I check file size in Python?

#Get file size , print it , process it...
#Os.stat will provide the file size in (.st_size) property. 
#The file size will be shown in bytes.

import os

fsize=os.stat('filepath')
print('size:' + fsize.st_size.__str__())

#check if the file size is less than 10 MB

if fsize.st_size < 10000000:
    process it ....

addClass and removeClass in jQuery - not removing class

I think that the problem is in the nesting of the elements. Once you attach an event to the outer element the clicks on the inner elements are actually firing the same click event for the outer element. So, you actually never go to the second state. What you can do is to check the clicked element. And if it is the close button then to avoid the class changing. Here is my solution:

var element = $(".clickable");
var closeButton = element.find(".close_button");
var onElementClick = function(e) {
    if(e.target !== closeButton[0]) {
        element.removeClass("spot").addClass("grown");
        element.off("click");
        closeButton.on("click", onCloseClick);
    }
}
var onCloseClick = function() {
    element.removeClass("grown").addClass("spot");
    closeButton.off("click");
    element.on("click", onElementClick);
}
element.on("click", onElementClick);

In addition I'm adding and removing event handlers.

JSFiddle -> http://jsfiddle.net/zmw9E/1/

OnItemClickListener using ArrayAdapter for ListView

you can use this way...

listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                final int position, long id) {

          String main = listView.getSelectedItem().toString();
        }
    });

How do I connect C# with Postgres?

If you want an recent copy of npgsql, then go here

http://www.npgsql.org/

This can be installed via package manager console as

PM> Install-Package Npgsql

ORACLE convert number to string

This should solve your problem:

select replace(to_char(a, '90D90'),'.00','')
from
(
select 50 a from dual
union
select 50.57 from dual
union
select 5.57 from dual
union
select 0.35 from dual
union
select 0.4 from dual
);

Give a look also as this SQL Fiddle for test.

How do I make an http request using cookies on Android?

It turns out that Google Android ships with Apache HttpClient 4.0, and I was able to figure out how to do it using the "Form based logon" example in the HttpClient docs:

https://github.com/apache/httpcomponents-client/blob/master/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientFormLogin.java


import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

/**
 * A example that demonstrates how HttpClient APIs can be used to perform
 * form-based logon.
 */
public class ClientFormLogin {

    public static void main(String[] args) throws Exception {

        DefaultHttpClient httpclient = new DefaultHttpClient();

        HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");

        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println("Login form get: " + response.getStatusLine());
        if (entity != null) {
            entity.consumeContent();
        }
        System.out.println("Initial set of cookies:");
        List<Cookie> cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("- " + cookies.get(i).toString());
            }
        }

        HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" +
                "org=self_registered_users&" +
                "goto=/portal/dt&" +
                "gotoOnFail=/portal/dt?error=true");

        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("IDToken1", "username"));
        nvps.add(new BasicNameValuePair("IDToken2", "password"));

        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        response = httpclient.execute(httpost);
        entity = response.getEntity();

        System.out.println("Login form get: " + response.getStatusLine());
        if (entity != null) {
            entity.consumeContent();
        }

        System.out.println("Post logon cookies:");
        cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("- " + cookies.get(i).toString());
            }
        }

        // When HttpClient instance is no longer needed, 
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();        
    }
}

java.io.StreamCorruptedException: invalid stream header: 54657374

You can't expect ObjectInputStream to automagically convert text into objects. The hexadecimal 54657374 is "Test" as text. You must be sending it directly as bytes.

How can I programmatically generate keypress events in C#?

To produce key events without Windows Forms Context, We can use the following method,

[DllImport("user32.dll")]
public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);

sample code is given below:

const int VK_UP = 0x26; //up key
const int VK_DOWN = 0x28;  //down key
const int VK_LEFT = 0x25;
const int VK_RIGHT = 0x27;
const uint KEYEVENTF_KEYUP = 0x0002;
const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
int press()
{
    //Press the key
    keybd_event((byte)VK_UP, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
    return 0;
}

List of Virtual Keys are defined here.

To get the complete picture, please use the below link, http://tksinghal.blogspot.in/2011/04/how-to-press-and-hold-keyboard-key.html

How to set and reference a variable in a Jenkinsfile

I can' t comment yet but, just a hint: use try/catch clauses to avoid breaking the pipeline (if you are sure the file exists, disregard)

    pipeline {
        agent any
            stages {
                stage("foo") {
                    steps {
                        script {
                            try {                    
                                env.FILENAME = readFile 'output.txt'
                                echo "${env.FILENAME}"
                            }
                            catch(Exception e) {
                                //do something, e.g. echo 'File not found'
                            }
                        }
                   }
    }

Another hint (this was commented by @hao, and think is worth to share): you may want to trim like this readFile('output.txt').trim()

How to check version of a CocoaPods framework

The highest voted answer (MishieMoo) is correct but it doesn't explain how to open Podfile.lock. Everytime I tried I kept getting:

enter image description here

You open it in terminal by going to the folder it's in and running:

vim Podfile.lock

I got the answer from here: how to open Podfile.lock

You close it by pressing the colon and typing quit or by pressing the colon and the letter q then enter

:quit // then return key
:q // then return key

Another way is in terminal, you can also cd to the folder that your Xcode project is in and enter

$ open Podfile.lock -a Xcode

Doing it the second way, after it opens just press the red X button in the upper left hand corner to close.

What are the differences between a pointer variable and a reference variable in C++?

What's a C++ reference (for C programmers)

A reference can be thought of as a constant pointer (not to be confused with a pointer to a constant value!) with automatic indirection, ie the compiler will apply the * operator for you.

All references must be initialized with a non-null value or compilation will fail. It's neither possible to get the address of a reference - the address operator will return the address of the referenced value instead - nor is it possible to do arithmetics on references.

C programmers might dislike C++ references as it will no longer be obvious when indirection happens or if an argument gets passed by value or by pointer without looking at function signatures.

C++ programmers might dislike using pointers as they are considered unsafe - although references aren't really any safer than constant pointers except in the most trivial cases - lack the convenience of automatic indirection and carry a different semantic connotation.

Consider the following statement from the C++ FAQ:

Even though a reference is often implemented using an address in the underlying assembly language, please do not think of a reference as a funny looking pointer to an object. A reference is the object. It is not a pointer to the object, nor a copy of the object. It is the object.

But if a reference really were the object, how could there be dangling references? In unmanaged languages, it's impossible for references to be any 'safer' than pointers - there generally just isn't a way to reliably alias values across scope boundaries!

Why I consider C++ references useful

Coming from a C background, C++ references may look like a somewhat silly concept, but one should still use them instead of pointers where possible: Automatic indirection is convenient, and references become especially useful when dealing with RAII - but not because of any perceived safety advantage, but rather because they make writing idiomatic code less awkward.

RAII is one of the central concepts of C++, but it interacts non-trivially with copying semantics. Passing objects by reference avoids these issues as no copying is involved. If references were not present in the language, you'd have to use pointers instead, which are more cumbersome to use, thus violating the language design principle that the best-practice solution should be easier than the alternatives.

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

I have encountered this problem as well. Here is my solution:

Below is the error while running a small Spring Application:-

*HTTP Status 500 - 
--------------------------------------------------------------------------------
type Exception report
message 
description The server encountered an internal error () that prevented it from fulfilling this request.
exception 
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsp/employe.jsp at line 12
9: <form:form method="POST" commandName="command"  action="/SpringWeb/addEmploye">
10:    <table>
11:     <tr>
12:         <td><form:label path="name">Name</form:label></td>
13:         <td><form:input path="name" /></td>
14:     </tr>
15:     <tr>
Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:465)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause 
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute
    org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:194)
    org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:129)
    org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:119)
    org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:89)
    org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)
    org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:79)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspx_meth_form_005flabel_005f0(employe_jsp.java:185)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspx_meth_form_005fform_005f0(employe_jsp.java:120)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspService(employe_jsp.java:80)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.26 logs.*

In order to resolve this issue you need to do the following in the controller class:-

  1. Change the import package from "import org.springframework.web.portlet.ModelAndView;" to "import org.springframework.web.servlet.ModelAndView;"...
  2. Recompile and run the code... the problem should get resolved.

Send Email to multiple Recipients with MailMessage?

Easy!

Just split the incoming address list on the ";" character, and add them to the mail message:

foreach (var address in addresses.Split(new [] {";"}, StringSplitOptions.RemoveEmptyEntries))
{
    mailMessage.To.Add(address);    
}

In this example, addresses contains "[email protected];[email protected]".

Html.BeginForm and adding properties

As part of htmlAttributes,e.g.

Html.BeginForm(
    action, controller, FormMethod.Post, new { enctype="multipart/form-data"})

Or you can pass null for action and controller to get the same default target as for BeginForm() without any parameters:

Html.BeginForm(
    null, null, FormMethod.Post, new { enctype="multipart/form-data"})

C# Foreach statement does not contain public definition for GetEnumerator

You don't show us the declaration of carBootSaleList. However from the exception message I can see that it is of type CarBootSaleList. This type doesn't implement the IEnumerable interface and therefore cannot be used in a foreach.

Your CarBootSaleList class should implement IEnumerable<CarBootSale>:

public class CarBootSaleList : IEnumerable<CarBootSale>
{
    private List<CarBootSale> carbootsales;

    ...

    public IEnumerator<CarBootSale> GetEnumerator()
    {
        return carbootsales.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return carbootsales.GetEnumerator();
    }
}

How to restart a node.js server

To say "nodemon" would answer the question.

But on how only to kill (all) node demon(s), the following works for me:

pkill -HUP node

Try-Catch-End Try in VBScript doesn't seem to work

Handling Errors

A sort of an "older style" of error handling is available to us in VBScript, that does make use of On Error Resume Next. First we enable that (often at the top of a file; but you may use it in place of the first Err.Clear below for their combined effect), then before running our possibly-error-generating code, clear any errors that have already occurred, run the possibly-error-generating code, and then explicitly check for errors:

On Error Resume Next
' ...
' Other Code Here (that may have raised an Error)
' ...
Err.Clear      ' Clear any possible Error that previous code raised
Set myObj = CreateObject("SomeKindOfClassThatDoesNotExist")
If Err.Number <> 0 Then
    WScript.Echo "Error: " & Err.Number
    WScript.Echo "Error (Hex): " & Hex(Err.Number)
    WScript.Echo "Source: " &  Err.Source
    WScript.Echo "Description: " &  Err.Description
    Err.Clear             ' Clear the Error
End If
On Error Goto 0           ' Don't resume on Error
WScript.Echo "This text will always print."

Above, we're just printing out the error if it occurred. If the error was fatal to the script, you could replace the second Err.clear with WScript.Quit(Err.Number).

Also note the On Error Goto 0 which turns off resuming execution at the next statement when an error occurs.

If you want to test behavior for when the Set succeeds, go ahead and comment that line out, or create an object that will succeed, such as vbscript.regexp.

The On Error directive only affects the current running scope (current Sub or Function) and does not affect calling or called scopes.


Raising Errors

If you want to check some sort of state and then raise an error to be handled by code that calls your function, you would use Err.Raise. Err.Raise takes up to five arguments, Number, Source, Description, HelpFile, and HelpContext. Using help files and contexts is beyond the scope of this text. Number is an error number you choose, Source is the name of your application/class/object/property that is raising the error, and Description is a short description of the error that occurred.

If MyValue <> 42 Then
    Err.Raise(42, "HitchhikerMatrix", "There is no spoon!")
End If

You could then handle the raised error as discussed above.


Change Log

  • Edit #1: Added an Err.Clear before the possibly error causing line to clear any previous errors that may have been ignored.
  • Edit #2: Clarified.
  • Edit #3: Added comments in code block. Clarified that there was expected to be more code between On Error Resume Next and Err.Clear. Fixed some grammar to be less awkward. Added info on Err.Raise. Formatting.
  • How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?

    Based on the property names it looks like you are trying to convert a string to a date by assignment:

    claimantAuxillaryRecord.TPOCDate2 = tpoc2[0].ToString();
    

    It is probably due to the current UI culture and therefore it cannot interpret the date string correctly when assigned.

    How to start color picker on Mac OS?

    Take a look into NSColorWell class reference.

    How to do SVN Update on my project using the command line

    If you want to update your project using SVN then first of all:

    1. Go to the path on which your project is stored through command prompt.

    2. Use the command SVN update

    That's it.

    Sorting a set of values

    From a comment:

    I want to sort each set.

    That's easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

    >>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
    >>> sorted(s)
    ['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']
    

    Note that sorted is giving you a list, not a set. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2} and {2, 1} are the same set.


    You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

    The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

    >>> sorted(s, key=float)
    ['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']
    

    For more information, see the Sorting HOWTO in the official docs.


    * See the comments for exceptions.

    Can Google Chrome open local links?

    I've just came across the same problem and found the chrome extension Open IE.
    That's the only one what works for me (Chrome V46 & V52). The only disadvantefge is, that you need to install an additional program, means you need admin rights.

    Bootstrap 3 Multi-column within a single ul not floating properly

    Thanks, Varun Rathore. It works perfectly!

    For those who want graceful collapse from 4 items per row to 2 items per row depending on the screen width:

    <ul class="list-group row">
        <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_1</li>
        <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_2</li>
        <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_3</li>
        <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_4</li>
        <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_5</li>
        <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_6</li>
        <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_7</li>
    </ul>
    

    Replace a value if null or undefined in JavaScript

    Logical nullish assignment, 2020+ solution

    A new operator has been added, ??=. This is equivalent to value = value ?? defaultValue.

    ||= and &&= are similar, links below.

    This checks if left side is undefined or null, short-circuiting if already defined. If not, the left side is assigned the right-side value.

    Basic Examples

    let a          // undefined
    let b = null
    let c = false
    
    a ??= true  // true
    b ??= true  // true
    c ??= true  // false
    
    // Equivalent to
    a = a ?? true
    

    Object/Array Examples

    let x = ["foo"]
    let y = { foo: "fizz" }
    
    x[0] ??= "bar"  // "foo"
    x[1] ??= "bar"  // "bar"
    
    y.foo ??= "buzz"  // "fizz"
    y.bar ??= "buzz"  // "buzz"
    
    x  // Array [ "foo", "bar" ]
    y  // Object { foo: "fizz", bar: "buzz" }
    

    Functional Example

    function config(options) {
        options.duration ??= 100
        options.speed ??= 25
        return options
    }
    
    config({ duration: 555 })   // { duration: 555, speed: 25 }
    config({})                  // { duration: 100, speed: 25 }
    config({ duration: null })  // { duration: 100, speed: 25 }
    

    ??= Browser Support Nov 2020 - 77%

    ??= Mozilla Documentation

    ||= Mozilla Documentation

    &&= Mozilla Documentation

    JavaScript private methods

    I prefer to store private data in an associated WeakMap. This allows you to keep your public methods on the prototype where they belong. This seems to be the most efficient way to handle this problem for large numbers of objects.

    const data = new WeakMap();
    
    function Foo(value) {
        data.set(this, {value});
    }
    
    // public method accessing private value
    Foo.prototype.accessValue = function() {
        return data.get(this).value;
    }
    
    // private 'method' accessing private value
    function accessValue(foo) {
        return data.get(foo).value;
    }
    
    export {Foo};
    

    How to install a gem or update RubyGems if it fails with a permissions error

    You don't have write permissions into the /Library/Ruby/Gems/1.8 directory.

    means exactly that, you don't have permission to write there.

    That is the version of Ruby installed by Apple, for their own use. While it's OK to make minor modifications to that if you know what you're doing, because you are not sure about the permissions problem, I'd say it's not a good idea to continue along that track.

    Instead, I'll strongly suggest you look into using either rbenv or RVM to manage a separate Ruby, installed into a sandbox in your home directory, that you can modify/fold/spindle/change without worrying about messing up the system Ruby.

    Between the two, I use rbenv, though I used RVM a lot in the past. rbenv takes a more "hands-off" approach to managing your Ruby installation. RVM has a lot of features and is very powerful, but, as a result is more intrusive. In either case, READ the installation documentation for them a couple times before starting to install whichever you pick.

    How to map and remove nil values in Ruby

    One more way to accomplish it will be as shown below. Here, we use Enumerable#each_with_object to collect values, and make use of Object#tap to get rid of temporary variable that is otherwise needed for nil check on result of process_x method.

    items.each_with_object([]) {|x, obj| (process x).tap {|r| obj << r unless r.nil?}}
    

    Complete example for illustration:

    items = [1,2,3,4,5]
    def process x
        rand(10) > 5 ? nil : x
    end
    
    items.each_with_object([]) {|x, obj| (process x).tap {|r| obj << r unless r.nil?}}
    

    Alternate approach:

    By looking at the method you are calling process_x url, it is not clear what is the purpose of input x in that method. If I assume that you are going to process the value of x by passing it some url and determine which of the xs really get processed into valid non-nil results - then, may be Enumerabble.group_by is a better option than Enumerable#map.

    h = items.group_by {|x| (process x).nil? ? "Bad" : "Good"}
    #=> {"Bad"=>[1, 2], "Good"=>[3, 4, 5]}
    
    h["Good"]
    #=> [3,4,5]
    

    Disable automatic sorting on the first column when using jQuery DataTables

    Add

    "aaSorting": []
    

    And check if default value is not null only set sortable column then

    if ($('#table').DataTable().order().length == 1) {
        d.SortColumn = $('#table').DataTable().order()[0][0];
        d.SortOrder = $('#table').DataTable().order()[0][1];
    }
    

    How to Select Top 100 rows in Oracle?

    As Moneer Kamal said, you can do that simply:

    SELECT id, client_id FROM order 
    WHERE rownum <= 100
    ORDER BY create_time DESC;
    

    Notice that the ordering is done after getting the 100 row. This might be useful for who does not want ordering.

    What is an .axd file?

    Those are not files (they don't exist on disk) - they are just names under which some HTTP handlers are registered. Take a look at the web.config in .NET Framework's directory (e.g. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config):

    <configuration>
      <system.web>
        <httpHandlers>
          <add path="eurl.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
          <add path="trace.axd" verb="*" type="System.Web.Handlers.TraceHandler" validate="True" />
          <add path="WebResource.axd" verb="GET" type="System.Web.Handlers.AssemblyResourceLoader" validate="True" />
          <add verb="*" path="*_AppService.axd" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False" />
          <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False"/>
          <add path="*.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
        </httpHandlers>
      </system.web>
    <configuration>
    

    You can register your own handlers with a whatever.axd name in your application's web.config. While you can bind your handlers to whatever names you like, .axd has the upside of working on IIS6 out of the box by default (IIS6 passes requests for *.axd to the ASP.NET runtime by default). Using an arbitrary path for the handler, like Document.pdf (or really anything except ASP.NET-specific extensions), requires more configuration work. In IIS7 in integrated pipeline mode this is no longer a problem, as all requests are processed by the ASP.NET stack.

    Comparing two input values in a form validation with AngularJS

    Mine is similar to your solution but I got it to work. Only difference is my model. I have the following models in my html input:

    ng-model="new.Participant.email"
    ng-model="new.Participant.confirmEmail"
    

    and in my controller, I have this in $scope:

     $scope.new = {
            Participant: {}
        };
    

    and this validation line worked:

    <label class="help-block" ng-show="new.Participant.email !== new.Participant.confirmEmail">Emails must match! </label>
    

    Java Swing revalidate() vs repaint()

    yes you need to call repaint(); revalidate(); when you call removeAll() then you have to call repaint() and revalidate()

    How to load external webpage in WebView

    Thanks to this post, I finally found the solution. Here is the code:

    import android.app.Activity;
    import android.os.Bundle;
    import android.webkit.WebResourceError;
    import android.webkit.WebResourceRequest;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;
    import android.widget.Toast;
    import android.annotation.TargetApi;
    
    public class Main extends Activity {
    
        private WebView mWebview ;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
    
            super.onCreate(savedInstanceState);
    
            mWebview  = new WebView(this);
    
            mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
    
            final Activity activity = this;
    
            mWebview.setWebViewClient(new WebViewClient() {
                @SuppressWarnings("deprecation")
                @Override
                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                    Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
                }
                @TargetApi(android.os.Build.VERSION_CODES.M)
                @Override
                public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
                    // Redirect to deprecated method, so you can use it in all SDK versions
                    onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
                }
            });
    
            mWebview .loadUrl("http://www.google.com");
            setContentView(mWebview );
    
        }
    
    }
    

    how to kill the tty in unix

    You can run:

    ps -ft pts/6 -t pts/9 -t pts/10
    

    This would produce an output similar to:

    UID        PID  PPID  C STIME TTY          TIME CMD
    Vidya      772  2701  0 15:26 pts/6    00:00:00 bash
    Vidya      773  2701  0 16:26 pts/9    00:00:00 bash
    Vidya      774  2701  0 17:26 pts/10   00:00:00 bash
    

    Grab the PID from the result.

    Use the PIDs to kill the processes:

    kill <PID1> <PID2> <PID3> ...
    

    For the above example:

    kill 772 773 774
    

    If the process doesn't gracefully terminate, just as a last option you can forcefully kill by sending a SIGKILL

    kill -9 <PID>
    

    What is JAVA_HOME? How does the JVM find the javac path stored in JAVA_HOME?

    The command prompt wouldn't use JAVA_HOME to find javac.exe, it would use PATH.

    What is a callback?

    Dedication to LightStriker:
    Sample Code:

    class CallBackExample
    {
        public delegate void MyNumber();
        public static void CallMeBack()
        {
            Console.WriteLine("He/She is calling you.  Pick your phone!:)");
            Console.Read();
        }
        public static void MetYourCrush(MyNumber number)
        {
            int j;
            Console.WriteLine("is she/he interested 0/1?:");
            var i = Console.ReadLine();
            if (int.TryParse(i, out j))
            {
                var interested = (j == 0) ? false : true;
                if (interested)//event
                {
                    //call his/her number
                    number();
                }
                else
                {
                    Console.WriteLine("Nothing happened! :(");
                    Console.Read();
                }
            }
        }
        static void Main(string[] args)
        {
            MyNumber number = Program.CallMeBack;
            Console.WriteLine("You have just met your crush and given your number");
            MetYourCrush(number);
            Console.Read();
            Console.Read();
        }       
    }
    

    Code Explanation:

    I created the code to implement the funny explanation provided by LightStriker in the above one of the replies. We are passing delegate (number) to a method (MetYourCrush). If the Interested (event) occurs in the method (MetYourCrush) then it will call the delegate (number) which was holding the reference of CallMeBack method. So, the CallMeBack method will be called. Basically, we are passing delegate to call the callback method.

    Please let me know if you have any questions.

    How do I URl encode something in Node.js?

    Use the escape function of querystring. It generates a URL safe string.

    var escaped_str = require('querystring').escape('Photo on 30-11-12 at 8.09 AM #2.jpg');
    console.log(escaped_str);
    // prints 'Photo%20on%2030-11-12%20at%208.09%20AM%20%232.jpg'
    

    I get a "An attempt was made to load a program with an incorrect format" error on a SQL Server replication project

    Change the value for Platform Target on your web project's property page to Any CPU.

    enter image description here

    Draw Circle using css alone

    border radius is good option, if struggling with old IE versions then try HTML codes

    &#8226;
    

    and use css to change color. Output:

    Excel VBA - read cell value from code

    I think you need this ..

    Dim n as Integer   
    
    For n = 5 to 17
      msgbox cells(n,3) '--> sched waste
      msgbox cells(n,4) '--> type of treatm
      msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
      msgbox cells(n,6) '--> email col
    Next
    

    How to convert data.frame column from Factor to numeric

    As an alternative to $dollarsign notation, use a within block:

    breast <- within(breast, {
      class <- as.numeric(as.character(class))
    })
    

    Note that you want to convert your vector to a character before converting it to a numeric. Simply calling as.numeric(class) will not the ids corresponding to each factor level (1, 2) rather than the levels themselves.

    Synchronous XMLHttpRequest warning and <script>

    I was plagued by this error message despite using async: true. It turns out the actual problem was using the success method. I changed this to done and warning is gone.

    success: function(response) { ... }

    replaced with:

    done: function(response) { ... }

    Delete specific line from a text file?

    You can actually use C# generics for this to make it real easy:

            var file = new List<string>(System.IO.File.ReadAllLines("C:\\path"));
            file.RemoveAt(12);
            File.WriteAllLines("C:\\path", file.ToArray());
    

    Count items in a folder with PowerShell

    Recursively count files in directories in PowerShell 2.0

    ls -rec | ? {$_.mode -match 'd'} | select FullName,  @{N='Count';E={(ls $_.FullName | measure).Count}}
    

    How can I check the size of a file in a Windows batch script?

    I like @Anders answer because the explanation of the %~z1 secret sauce. However, as pointed out, that only works when the filename is passed as the first parameter to the batch file.

    @Anders worked around this by using FOR, which, is a great 1-liner fix to the problem, but, it's somewhat harder to read.

    Instead, we can go back to a simpler answer with %~z1 by using CALL. If you have a filename stored in an environment variable it will become %1 if you use it as a parameter to a routine in your batch file:

    @echo off
    setlocal
    set file=test.cmd
    set maxbytesize=1000
    
    call :setsize %file%
    
    if %size% lss %maxbytesize% (
        echo File is less than %maxbytesize% bytes
    ) else (
        echo File is greater than or equal %maxbytesize% bytes
    )
    goto :eof
    
    :setsize
    set size=%~z1
    goto :eof
    

    I've been curious about J. Bouvrie's concern regarding 32-bit limitations. It appears he is talking about an issue with using LSS not on the filesize logic itself. To deal with J. Bouvrie's concern, I've rewritten the solution to use a padded string comparison:

    @echo on
    setlocal
    set file=test.cmd
    set maxbytesize=1000
    
    call :setsize %file%
    
    set checksize=00000000000000000000%size%
    set checkmaxbytesize=00000000000000000000%maxbytesize%
    if "%checksize:~-20%" lss "%checkmaxbytesize:~-20%" (
        echo File is less than %maxbytesize% bytes
    ) else (
        echo File is greater than or equal %maxbytesize% bytes
    )
    goto :eof
    
    :setsize
    set size=%~z1
    goto :eof
    

    What does `set -x` do?

    set -x

    Prints a trace of simple commands, for commands, case commands, select commands, and arithmetic for commands and their arguments or associated word lists after they are expanded and before they are executed. The value of the PS4 variable is expanded and the resultant value is printed before the command and its expanded arguments.

    [source]

    Example

    set -x
    echo `expr 10 + 20 `
    + expr 10 + 20
    + echo 30
    30
    

    set +x
    echo `expr 10 + 20 `
    30
    

    Above example illustrates the usage of set -x. When it is used, above arithmetic expression has been expanded. We could see how a singe line has been evaluated step by step.

    • First step expr has been evaluated.
    • Second step echo has been evaluated.

    To know more about set ? visit this link

    when it comes to your shell script,

    [ "$DEBUG" == 'true' ] && set -x
    

    Your script might have been printing some additional lines of information when the execution mode selected as DEBUG. Traditionally people used to enable debug mode when a script called with optional argument such as -d

    CSS hide scroll bar, but have element scrollable

    Hope this helps

    /* Hide scrollbar for Chrome, Safari and Opera */
    ::-webkit-scrollbar {
      display: none;
    }
    
    /* Hide scrollbar for IE, Edge and Firefox */
    html {
      -ms-overflow-style: none;  /* IE and Edge */
      scrollbar-width: none;  /* Firefox */
    }
    

    How do I get the SelectedItem or SelectedIndex of ListView in vb.net?

    ListView returns collections of selected items and indices through the SelectedItems and SelectedIndices properties. Note that these collections are empty, if no item is currently selected (lst.SelectedItems.Count = 0). The first item that is selected is lst.SelectedItems(0). The index of this item in the Items collection is lst.SelectedIndices(0). So basically

    lst.SelectedItems(0)
    

    is the same as

    lst.Items(lst.SelectedIndices(0))
    

    You can also use check boxes. Set CheckBoxes to True for this. Through the CheckedItems and CheckedIndices properties you can see which items are checked.

    How to bind multiple values to a single WPF TextBlock?

    Use a ValueConverter

    [ValueConversion(typeof(string), typeof(String))]
    public class MyConverter: IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return string.Format("{0}:{1}", (string) value, (string) parameter);
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
    
            return DependencyProperty.UnsetValue;
        }
    }
    

    and in the markup

    <src:MyConverter x:Key="MyConverter"/>
    

    . . .

    <TextBlock Text="{Binding Name, Converter={StaticResource MyConverter Parameter=ID}}" />
    

    How does cellForRowAtIndexPath work?

    1) The function returns a cell for a table view yes? So, the returned object is of type UITableViewCell. These are the objects that you see in the table's rows. This function basically returns a cell, for a table view. But you might ask, how the function would know what cell to return for what row, which is answered in the 2nd question

    2)NSIndexPath is essentially two things-

    • Your Section
    • Your row

    Because your table might be divided to many sections and each with its own rows, this NSIndexPath will help you identify precisely which section and which row. They are both integers. If you're a beginner, I would say try with just one section.

    It is called if you implement the UITableViewDataSource protocol in your view controller. A simpler way would be to add a UITableViewController class. I strongly recommend this because it Apple has some code written for you to easily implement the functions that can describe a table. Anyway, if you choose to implement this protocol yourself, you need to create a UITableViewCell object and return it for whatever row. Have a look at its class reference to understand re-usablity because the cells that are displayed in the table view are reused again and again(this is a very efficient design btw).

    As for when you have two table views, look at the method. The table view is passed to it, so you should not have a problem with respect to that.

    How to append output to the end of a text file

    Using tee with option -a (--append) allows you to append to multiple files at once and also to use sudo (very useful when appending to protected files). Besides that, it is interesting if you need to use other shells besides bash, as not all shells support the > and >> operators

    echo "hello world" | sudo tee -a output.txt
    

    This thread has good answers about tee

    How to change button text or link text in JavaScript?

    Change .text to .textContent to get/set the text content.

    Or since you're dealing with a single text node, use .firstChild.data in the same manner.

    Also, let's make sensible use of a variable, and enjoy some code reduction and eliminate redundant DOM selection by caching the result of getElementById.

    function toggleText(button_id) 
    {
       var el = document.getElementById(button_id);
       if (el.firstChild.data == "Lock") 
       {
           el.firstChild.data = "Unlock";
       }
       else 
       {
         el.firstChild.data = "Lock";
       }
    }
    

    Or even more compact like this:

    function toggleText(button_id)  {
       var text = document.getElementById(button_id).firstChild;
       text.data = text.data == "Lock" ? "Unlock" : "Lock";
    }
    

    How to check if a std::string is set or not?

    The default constructor for std::string always returns an object that is set to a null string.

    Jupyter/IPython Notebooks: Shortcut for "run all"?

    Easiest solution:

    Esc, Ctrl-A, Shift-Enter.

    regex with space and letters only?

    $('#input').on('keyup', function() {
         var RegExpression = /^[a-zA-Z\s]*$/;  
         ...
    
    });
    

    \s will allow the space

    SQL Server: how to select records with specific date from datetime column

    SELECT *
    FROM LogRequests
    WHERE cast(dateX as date) between '2014-05-09' and '2014-05-10';
    

    This will select all the data between the 2 dates

    How can one print a size_t variable portably using the printf family?

    std::size_t s = 1024;
    std::cout << s; // or any other kind of stream like stringstream!
    

    How to add header to a dataset in R?

    You can also use colnames instead of names if you have data.frame or matrix

    Postgres: SQL to list table foreign keys

    Here is a solution by Andreas Joseph Krogh from the PostgreSQL mailing list: http://www.postgresql.org/message-id/[email protected]

    SELECT source_table::regclass, source_attr.attname AS source_column,
        target_table::regclass, target_attr.attname AS target_column
    FROM pg_attribute target_attr, pg_attribute source_attr,
      (SELECT source_table, target_table, source_constraints[i] source_constraints, target_constraints[i] AS target_constraints
       FROM
         (SELECT conrelid as source_table, confrelid AS target_table, conkey AS source_constraints, confkey AS target_constraints,
           generate_series(1, array_upper(conkey, 1)) AS i
          FROM pg_constraint
          WHERE contype = 'f'
         ) query1
      ) query2
    WHERE target_attr.attnum = target_constraints AND target_attr.attrelid = target_table AND
          source_attr.attnum = source_constraints AND source_attr.attrelid = source_table;
    

    This solution handles foreign keys that reference multiple columns, and avoids duplicates (which some of the other answers fail to do). The only thing I changed were the variable names.

    Here is an example that returns all employee columns that reference the permission table:

    SELECT source_column
    FROM foreign_keys
    WHERE source_table = 'employee'::regclass AND target_table = 'permission'::regclass;
    

    Convert varchar into datetime in SQL Server

    Convert would be the normal answer, but the format is not a recognised format for the converter, mm/dd/yyyy could be converted using convert(datetime,yourdatestring,101) but you do not have that format so it fails.

    The problem is the format being non-standard, you will have to manipulate it to a standard the convert can understand from those available.

    Hacked together, if you can guarentee the format

    declare @date char(8)
    set @date = '12312009'
    select convert(datetime, substring(@date,5,4) + substring(@date,1,2) + substring(@date,3,2),112)
    

    git repo says it's up-to-date after pull but files are not updated

    Try this:

     git fetch --all
     git reset --hard origin/master
    

    Explanation:

    git fetch downloads the latest from remote without trying to merge or rebase anything.

    Please let me know if you have any questions!

    Python - How to convert JSON File to Dataframe

    import pandas as pd
    print(pd.json_normalize(your_json))
    

    This will Normalize semi-structured JSON data into a flat table

    Output

      FirstName LastName MiddleName password    username
          John     Mark      Lewis     2910  johnlewis2
    

    Reverting single file in SVN to a particular revision

    sudo svn revert filename
    

    this is the better way to revert a single file

    Removing elements from array Ruby

    You may do:

    a= [1,1,1,2,2,3]
    delete_list = [1,3]
    delete_list.each do |del|
        a.delete_at(a.index(del))
    end
    

    result : [1, 1, 2, 2]

    Forbidden You don't have permission to access / on this server

    Found my solution on Apache/2.2.15 (Unix).

    And Thanks for answer from @QuantumHive:

    First: I finded all

    Order allow,deny
    Deny from all
    

    instead of

    Order allow,deny
    
    Allow from all
    

    and then:

    I setted

    #
    # Control access to UserDir directories.  The following is an example
    # for a site where these directories are restricted to read-only.
    #
    #<Directory /var/www/html>
    #    AllowOverride FileInfo AuthConfig Limit
    #    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
    #    <Limit GET POST OPTIONS>
    #        Order allow,deny
    #        Allow from all
    #    </Limit>
    #    <LimitExcept GET POST OPTIONS>
    #        Order deny,allow
    #        Deny from all
    #    </LimitExcept>
    #</Directory>
    

    Remove the previous "#" annotation to

    #
    # Control access to UserDir directories.  The following is an example
    # for a site where these directories are restricted to read-only.
    #
    <Directory /var/www/html>
        AllowOverride FileInfo AuthConfig Limit
        Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
        <Limit GET POST OPTIONS>
            Order allow,deny
            Allow from all
        </Limit>
        <LimitExcept GET POST OPTIONS>
            Order deny,allow
            Deny from all
        </LimitExcept>
    </Directory>
    

    ps. my WebDir is: /var/www/html

    Send HTTP POST message in ASP.NET Core using HttpClient PostAsJsonAsync

    I use this class:

    public class JsonContent : StringContent
    {
        public JsonContent(object obj) :
            base(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json")
        { }
    }
    

    Sample of usage:

    new HttpClient().PostAsync("http://...", new JsonContent(new { x = 1, y = 2 }));
    

    ERROR in ./node_modules/css-loader?

    Run this command:

    npm install --save node-sass
    

    This does the same as above. Similarly to the answer above.

    Removing certain characters from a string in R

    try: gsub('\\$', '', '$5.00$')

    How can I restart a Java application?

    Of course it is possible to restart a Java application.

    The following method shows a way to restart a Java application:

    public void restartApplication()
    {
      final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
      final File currentJar = new File(MyClassInTheJar.class.getProtectionDomain().getCodeSource().getLocation().toURI());
    
      /* is it a jar file? */
      if(!currentJar.getName().endsWith(".jar"))
        return;
    
      /* Build command: java -jar application.jar */
      final ArrayList<String> command = new ArrayList<String>();
      command.add(javaBin);
      command.add("-jar");
      command.add(currentJar.getPath());
    
      final ProcessBuilder builder = new ProcessBuilder(command);
      builder.start();
      System.exit(0);
    }
    

    Basically it does the following:

    1. Find the java executable (I used the java binary here, but that depends on your requirements)
    2. Find the application (a jar in my case, using the MyClassInTheJar class to find the jar location itself)
    3. Build a command to restart the jar (using the java binary in this case)
    4. Execute it! (and thus terminating the current application and starting it again)

    How to calculate age in T-SQL with years, months, and days

    For the ones that want to create a calculated column in a table to store the age:

    CASE WHEN DateOfBirth< DATEADD(YEAR, (DATEPART(YEAR, GETDATE()) - DATEPART(YEAR, DateOfBirth))*-1, GETDATE()) 
         THEN DATEPART(YEAR, GETDATE()) - DATEPART(YEAR, DateOfBirth)
         ELSE DATEPART(YEAR, GETDATE()) - DATEPART(YEAR, DateOfBirth) -1 END
    

    How to run a subprocess with Python, wait for it to exit and get the full stdout as a string?

    If your process gives a huge stdout and no stderr, communicate() might be the wrong way to go due to memory restrictions.

    Instead,

    process = subprocess.Popen(cmd, shell=True,
                               stdout=subprocess.PIPE, 
                               stderr=subprocess.PIPE)
    
    # wait for the process to terminate
    for line in process.stdout: do_something(line)
    errcode = process.returncode
    

    might be the way to go.

    process.stdout is a file-like object which you can treat as any other such object, mainly:

    • you can read() from it
    • you can readline() from it and
    • you can iterate over it.

    The latter is what I do above in order to get its contents line by line.

    Pipenv: Command Not Found

    I don't know what happened, but the following did the work (under mac os catalina)

    $ brew install pipenv
    
    $ brew update pipenv
    

    after doing this i am able to use

    $ pipenv install [package_name]
    

    If Else in LINQ

    This might work...

    from p in db.products
        select new
        {
            Owner = (p.price > 0 ?
                from q in db.Users select q.Name :
                from r in db.ExternalUsers select r.Name)
        }
    

    How do I choose grid and block dimensions for CUDA kernels?

    The blocksize is usually selected to maximize the "occupancy". Search on CUDA Occupancy for more information. In particular, see the CUDA Occupancy Calculator spreadsheet.

    Getting data from selected datagridview row and which event?

    First take a label. set its visibility to false, then on the DataGridView_CellClick event write this

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        label.Text=dataGridView1.Rows[e.RowIndex].Cells["Your Coloumn name"].Value.ToString();
        // then perform your select statement according to that label.
    }
    //try it it might work for you
    

    In Python, how do I read the exif data for an image?

    For Python3.x and starting Pillow==6.0.0, Image objects now provide a getexif() method that returns a <class 'PIL.Image.Exif'> instance or None if the image has no EXIF data.

    From Pillow 6.0.0 release notes:

    getexif() has been added, which returns an Exif instance. Values can be retrieved and set like a dictionary. When saving JPEG, PNG or WEBP, the instance can be passed as an exif argument to include any changes in the output image.

    As stated, you can iterate over the key-value pairs of the Exif instance like a regular dictionary. The keys are 16-bit integers that can be mapped to their string names using the ExifTags.TAGS module.

    from PIL import Image, ExifTags
    
    img = Image.open("sample.jpg")
    img_exif = img.getexif()
    print(type(img_exif))
    # <class 'PIL.Image.Exif'>
    
    if img_exif is None:
        print('Sorry, image has no exif data.')
    else:
        for key, val in img_exif.items():
            if key in ExifTags.TAGS:
                print(f'{ExifTags.TAGS[key]}:{val}')
                # ExifVersion:b'0230'
                # ...
                # FocalLength:(2300, 100)
                # ColorSpace:1
                # ...
                # Model:'X-T2'
                # Make:'FUJIFILM'
                # LensSpecification:(18.0, 55.0, 2.8, 4.0)
                # ...
                # DateTime:'2019:12:01 21:30:07'
                # ...
    

    Tested with Python 3.8.8 and Pillow==8.1.0.

    IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7

    [For IntelliJ IDEA 2016.2]

    I would like to expand upon part of Peter Gromov's answer with an up-to-date screenshot. Specifically this particular part:

    You might also want to take a look at Settings | Compiler | Java Compiler | Per-module bytecode version.

    I believe that (at least in 2016.2): checking out different commits in git resets these to 1.5.

    Per-module bytecode version

    WCF Error "This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case"

    I had this issue when running older XP SP3 boxes against both IIS and glassfish on Amazon AWS. Amazon changed their default load balancer settings to NOT enable the DES-CBC3-SHA cipher. You have to enable that on amazon ELB if you want to allow older XP TLS 1.0 to work against ELB for HTTPS otherwise you get this error. Ciphers can be changed on ELB by going to the listener tab in the console and clicking on cipher next to the particular listener you are trying to make work.

    How to make the tab character 4 spaces instead of 8 spaces in nano?

    If you use nano with a language like python (as in your example) it's also a good idea to convert tabs to spaces.

    Edit your ~/.nanorc file (or create it) and add:

    set tabsize 4
    set tabstospaces
    

    If you already got a file with tabs and want to convert them to spaces i recommend the expandcommand (shell):

    expand -4 input.py > output.py
    

    Control flow in T-SQL SP using IF..ELSE IF - are there other ways?

    CASE expression
          WHEN value1 THEN result1
          WHEN value2 THEN result2
          ...
          WHEN valueN THEN resultN
    
          [
            ELSE elseResult
          ]
    END
    

    http://www.4guysfromrolla.com/webtech/102704-1.shtml For more information.

    What's the best way to test SQL Server connection programmatically?

    Similar to the answer offered by Andrew, but I use:

    Select GetDate() as CurrentDate

    This allows me to see if the SQL Server and the client have any time zone difference issues, in the same action.

    node.js string.replace doesn't work?

    Isn't string.replace returning a value, rather than modifying the source string?

    So if you wanted to modify variableABC, you'd need to do this:

    var variableABC = "A B C";
    
    variableABC = variableABC.replace('B', 'D') //output: 'A D C'
    

    SQL Query to concatenate column values from multiple rows in Oracle

    There's also an XMLAGG function, which works on versions prior to 11.2. Because WM_CONCAT is undocumented and unsupported by Oracle, it's recommended not to use it in production system.

    With XMLAGG you can do the following:

    SELECT XMLAGG(XMLELEMENT(E,ename||',')).EXTRACT('//text()') "Result" 
    FROM employee_names
    

    What this does is

    • put the values of the ename column (concatenated with a comma) from the employee_names table in an xml element (with tag E)
    • extract the text of this
    • aggregate the xml (concatenate it)
    • call the resulting column "Result"

    What do the return values of Comparable.compareTo mean in Java?

    take example if we want to compare "a" and "b", i.e ("a" == this)

    1. negative int if a < b
    2. if a == b
    3. Positive int if a > b

    SELECT CONVERT(VARCHAR(10), GETDATE(), 110) what is the meaning of 110 here?

    That number indicates Date and Time Styles

    You need to look at CAST and CONVERT (Transact-SQL). Here you can find the meaning of all these Date and Time Styles.

    Styles with century (e.g. 100, 101 etc) means year will come in yyyy format. While styles without century (e.g. 1,7,10) means year will come in yy format.

    You can also refer to SQL Server Date Formats. Here you can find all date formats with examples.

    How to set specific Java version to Maven

    Adding my two cents and explicitly providing the solution.

    I have two JDKs installed on my Windows Machine - JDK 1.5 and JDK 1.6.

    My default (and set to windows system environment variable) JAVA_HOME is set to JDK 1.5.

    However, I have a maven project that I need to build (i.e., JBehave Tutorial's Etsy.com) using JDK 1.6.

    My solution in this scenario (which worked!), is as suggested by @DanielBarbarian to set it in mvn.bat.

    For some not familiar with window's batch file, I just basically added the set JAVA_HOME=<path_to_other_jdk> line after @REM ==== START VALIDATION ==== in mvn.bat (i.e., %MAVEN_HOME%\bin\mvn.bat):

    @REM ==== START VALIDATION ====
    set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_45\jre
    if not "%JAVA_HOME%" == "" goto OkJHome
    

    highlight the navigation menu for the current page

    Please Look at the following:

    Here is what's working:

    1.) top menu buttons are visible and highlight correctly

    2.) sub menu buttons are not visible until top menu is clicked

    Here is what needs work:

    1.) when sub menu is clicked, looking for new page to keep the selected sub menu open (i will highlight the selected sub menu button for further clarification on navigation)

    Please see code here: http://jsbin.com/ePawaju/1/edit

    or here: http://www.ceramictilepro.com/_6testingonly.php#

    <head>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    

    Do I need to put this script in the head section? Where is the best place?

    <div class="left">
    <nav class="vmenu">
        <ul class="vnavmenu">
            <li data-ref="Top1"><a class="hiLite navBarButton2" href="#">Home</a>
            </li>
        </ul>
        <ul class="Top1 navBarTextSize">
            <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub1</a>
            </li>
            <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub2</a>
            </li>
            <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub3</a>
            </li>
            <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub4</a>
            </li>
        </ul>
        <ul class="vnavmenu">
            <li data-ref="Top2"><a class="hiLite navBarButton2" href="#">Repairs</a>
            </li>
        </ul>
        <ul class="Top2 navBarTextSize">
            <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">1sub1</a>
            </li>
            <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">2sub2</a>
            </li>
            <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">3sub3</a>
            </li>
            <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">4sub4</a>
            </li>
        </ul>
    </nav>
    

    JQuery is new to me, any help would greatly be appreciated :) var submenu;

    $('.vnavmenu li').click(function () {
    var elems = $('.vmenu ul:not(.vnavmenu)').length;
    var $refClass = $('.' + $(this).attr('data-ref'));
    var visible = $refClass.is(':visible');
    
    $('.vmenu ul:not(.vnavmenu)').slideUp(100, function () {
    
        if (elems == 1) {
            if (!visible) $refClass.slideDown('fast');
        }
    
        elems--;
    });
    
    if (visible) $('#breadcrumbs-pc').animate({
        'margin-top': '0rem'
    }, 100);
    else $('#breadcrumbs-pc').animate({
        'margin-top': '5rem'
    }, 100);
    });
    

    How to fix this Error: #include <gl/glut.h> "Cannot open source file gl/glut.h"

    You probably haven't installed GLUT:

    1. Install GLUT If you do not have GLUT installed on your machine you can download it from: http://www.xmission.com/~nate/glut/glut-3.7.6-bin.zip (or whatever version) GLUT Libraries and header files are • glut32.lib • glut.h

    Source: http://cacs.usc.edu/education/cs596/OGL_Setup.pdf

    EDIT:

    The quickest way is to download the latest header, and compiled DLLs for it, place it in your system32 folder or reference it in your project. Version 3.7 (latest as of this post) is here: http://www.opengl.org/resources/libraries/glut/glutdlls37beta.zip

    Folder references:
    
    glut.h: 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\GL\'
    glut32.lib: 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib\'
    glut32.dll: 'C:\Windows\System32\'
    
    For 64-bit machines, you will want to do this.
    glut32.dll: 'C:\Windows\SysWOW64\'
    
    Same pattern applies to freeglut and GLEW files with the header files in the GL folder, lib in the lib folder, and dll in the System32 (and SysWOW64) folder.
    1. Under Visual C++, select Empty Project.
    2. Go to Project -> Properties. Select Linker -> Input then add the following to the Additional Dependencies field:
    opengl32.lib
    glu32.lib
    glut32.lib
    

    Reprinted from here

    NameError: global name is not defined

    Importing the namespace is somewhat cleaner. Imagine you have two different modules you import, both of them with the same method/class. Some bad stuff might happen. I'd dare say it is usually good practice to use:

    import module
    

    over

    from module import function/class
    

    How do you check whether a number is divisible by another number (Python)?

    You can simply use % Modulus operator to check divisibility.
    For example: n % 2 == 0 means n is exactly divisible by 2 and n % 2 != 0 means n is not exactly divisible by 2.

    Horizontal scroll css?

    I figured it this way:

    * { padding: 0; margin: 0 }
    body { height: 100%; white-space: nowrap }
    html { height: 100% }
    
    .red { background: red }
    .blue { background: blue }
    .yellow { background: yellow }
    
    .header { width: 100%; height: 10%; position: fixed }
    .wrapper { width: 1000%; height: 100%; background: green }
    .page { width: 10%; height: 100%; float: left }
    
    <div class="header red"></div>
    <div class="wrapper">
        <div class="page yellow"></div>
        <div class="page blue"></div>
        <div class="page yellow"></div>
        <div class="page blue"></div>
        <div class="page yellow"></div>
        <div class="page blue"></div>
        <div class="page yellow"></div>
        <div class="page blue"></div>
        <div class="page yellow"></div>
        <div class="page blue"></div>
    </div>
    

    I have the wrapper at 1000% and ten pages at 10% each. I set mine up to still have "pages" with each being 100% of the window (color coded). You can do eight pages with an 800% wrapper. I guess you can leave out the colors and have on continues page. I also set up a fixed header, but that's not necessary. Hope this helps.

    Visually managing MongoDB documents and collections

    I use MongoVUE, it's good for viewing data, but there is almost no editing abilities.

    Android - Pulling SQlite database android device

    I give the complete solution to "save" and "restore" the app database to/from the internal storage (not to the PC with adb).

    I have done two methods one for save and other for restore the database. Use these methods at the end of the onCreate() in MainActivity (one or the other if you want to saver or restore the database).

    save database to internal storage:

    void copyDatabase (){
            try {
                final String inFileName = "/data/data/<pakage.name>/databases/database.db";
                final String outFileName = Environment.getExternalStorageDirectory() + "database_backup.db";
                File dbFile = new File(inFileName);
                FileInputStream fis = new FileInputStream(dbFile);
    
    
                Log.d(TAG, "copyDatabase: outFile = " + outFileName);
    
                // Open the empty db as the output stream
                OutputStream output = new FileOutputStream(outFileName);
    
                // Transfer bytes from the inputfile to the outputfile
                byte[] buffer = new byte[1024];
                int length;
                while ((length = fis.read(buffer)) > 0) {
                    output.write(buffer, 0, length);
                }
    
                // Close the streams
                output.flush();
                output.close();
                fis.close();
            }catch (Exception e){
                Log.d(TAG, "copyDatabase: backup error");
            }
        }
    

    restore database from internal storage:

    void restoreDatabase (){
            try {
                final String inFileName = Environment.getExternalStorageDirectory() + "database_backup.db";
                final String outFileName = "/data/data/<package.name>/databases/database.db";
                File dbFile = new File(inFileName);
                FileInputStream fis = new FileInputStream(dbFile);
    
                Log.d(TAG, "copyDatabase: outFile = " + outFileName);
    
                // Open the empty db as the output stream
                OutputStream output = new FileOutputStream(outFileName);
    
                // Transfer bytes from the inputfile to the outputfile
                byte[] buffer = new byte[1024];
                int length;
                while ((length = fis.read(buffer)) > 0) {
                    output.write(buffer, 0, length);
                }
    
                // Close the streams
                output.flush();
                output.close();
                fis.close();
            }catch (Exception e){
                Log.d(TAG, "copyDatabase: backup error");
            }
        }
    

    What are the correct version numbers for C#?

    C# Version History:

    C# is a simple and powerful object-oriented programming language developed by Microsoft.

    C# has evolved much since its first release in 2002. C# was introduced with .NET Framework 1.0.

    The following table lists important features introduced in each version of C#.

    And the latest version of C# is available in C# Versions.

    1: enter image description here

    Python creating a dictionary of lists

    You can use setdefault:

    d = dict()
    a = ['1', '2']
    for i in a:
        for j in range(int(i), int(i) + 2): 
            d.setdefault(j, []).append(i)
    
    print d  # prints {1: ['1'], 2: ['1', '2'], 3: ['2']}
    

    The rather oddly-named setdefault function says "Get the value with this key, or if that key isn't there, add this value and then return it."

    As others have rightly pointed out, defaultdict is a better and more modern choice. setdefault is still useful in older versions of Python (prior to 2.5).

    What's the difference between next() and nextLine() methods from Scanner class?

    The key point is to find where the method will stop and where the cursor will be after calling the methods.

    All methods will read information which does not include whitespace between the cursor position and the next default delimiters(whitespace, tab, \n--created by pressing Enter). The cursor stops before the delimiters except for nextLine(), which reads information (including whitespace created by delimiters) between the cursor position and \n, and the cursor stops behind \n.


    For example, consider the following illustration:

    |23_24_25_26_27\n
    

    | -> the current cursor position

    _ -> whitespace

    stream -> Bold (the information got by the calling method)

    See what happens when you call these methods:

    nextInt()    
    

    read 23|_24_25_26_27\n

    nextDouble()
    

    read 23_24|_25_26_27\n

    next()
    

    read 23_24_25|_26_27\n

    nextLine()
    

    read 23_24_25_26_27\n|


    After this, the method should be called depending on your requirement.

    Python, TypeError: unhashable type: 'list'

    The problem is that you can't use a list as the key in a dict, since dict keys need to be immutable. Use a tuple instead.

    This is a list:

    [x, y]
    

    This is a tuple:

    (x, y)
    

    Note that in most cases, the ( and ) are optional, since , is what actually defines a tuple (as long as it's not surrounded by [] or {}, or used as a function argument).

    You might find the section on tuples in the Python tutorial useful:

    Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

    And in the section on dictionaries:

    Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().


    In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.

    Get a Windows Forms control by name in C#

    A simple solution would be to iterate through the Controls list in a foreach loop. Something like this:

    foreach (Control child in Controls)
    {
        // Code that executes for each control.
    }
    

    So now you have your iterator, child, which is of type Control. Now do what you will with that, personally I found this in a project I did a while ago in which it added an event for this control, like this:

    child.MouseDown += new MouseEventHandler(dragDown);
    

    What's the equivalent of Java's Thread.sleep() in JavaScript?

    Or maybe you can use the setInterval function, to call a particular function, after the specified number of milliseconds. Just do a google for the setInterval prototype.I don't quite recollect it.

    Login to Microsoft SQL Server Error: 18456

    Just happened to me, and turned out to be different than all other cases listed here.

    I happen to have two virtual servers hosted in the same cluster, each with it own IP address. The host configured one of the servers to be the SQL Server, and the other to be the Web server. However, SQL Server is installed and running on both. The host forgot to mention which of the servers is the SQL and which is the Web, so I just assumed the first is Web, second is SQL.

    When I connected to the (what I thought is) SQL Server and tried to connect via SSMS, choosing Windows Authentication, I got the error mentioned in this question. After pulling lots of hairs, I went over all the setting, including SQL Server Network Configuration, Protocols for MSSQLSERVER:

    screenshot of TCP/IP configuration

    Double clicking the TCP/IP gave me this:

    TCP/IP properties, showing wrong IP address

    The IP address was of the other virtual server! This finally made me realize I simply confused between the servers, and all worked well on the second server.

    How to make phpstorm display line numbers by default?

    Just now found where is it on Windows. Its View -> Active Editor -> Show Line Numbers (changes only for current document) and File -> Settings -> Editor -> Appearance -> Show Line Numbers (for all documents)

    For Mac Version go to PhpStorm -> Preferences in menu. In the preference window go to IDE settings -> Editor -> Appearance -> Show Line Numbers (To change setting for all documents)

    OR if you want to quickly set show line number PER CURRENT WINDOW even easier - right click on the long white column (where breakpoints are set) then select Show Line Numbers.

    enter image description here

    Red dot on the screenshot is a place where you have to click

    Change default timeout for mocha

    In current versions of Mocha, the timeout can be changed globally like this:

    mocha.timeout(5000);
    

    Just add the line above anywhere in your test suite, preferably at the top of your spec or in a separate test helper.


    In older versions, and only in a browser, you could change the global configuration using mocha.setup.

    mocha.setup({ timeout: 5000 });
    

    The documentation does not cover the global timeout setting, but offers a few examples on how to change the timeout in other common scenarios.

    How to do a join in linq to sql with method syntax?

    To add on to the other answers here, if you would like to create a new object of a third different type with a where clause (e.g. one that is not your Entity Framework object) you can do this:

    public IEnumerable<ThirdNonEntityClass> demoMethod(IEnumerable<int> property1Values)
    {
        using(var entityFrameworkObjectContext = new EntityFrameworkObjectContext )
        {
            var result = entityFrameworkObjectContext.SomeClass
                .Join(entityFrameworkObjectContext.SomeOtherClass,
                    sc => sc.property1,
                    soc => soc.property2,
                    (sc, soc) => new {sc, soc})
                .Where(s => propertyValues.Any(pvals => pvals == es.sc.property1)
                .Select(s => new ThirdNonEntityClass 
                {
                    dataValue1 = s.sc.dataValueA,
                    dataValue2 = s.soc.dataValueB
                })
                .ToList();
        }
    
        return result;
    
    }    
    

    Pay special attention to the intermediate object that is created in the Where and Select clauses.

    Note that here we also look for any joined objects that have a property1 that matches one of the ones in the input list.

    I know this is a bit more complex than what the original asker was looking for, but hopefully it will help someone.

    How to check whether a Button is clicked by using JavaScript

    Try adding an event listener for clicks:

    document.getElementById('button').addEventListener("click", function() {
       alert("You clicked me");
    }?);?
    

    Using addEventListener is probably a better idea then setting onclick - onclick can easily be overwritten by another piece of code.

    You can use a variable to store whether or not the button has been clicked before:

    var clicked = false
    document.getElementById('button').addEventListener("click", function() {
       clicked = true
    }?);?
    

    addEventListener on MDN

    Integer value comparison

    One more thing to watch out for is if the second value was another Integer object instead of a literal '0', the '==' operator compares the object pointers and will not auto-unbox.

    ie:

    Integer a = new Integer(0);   
    Integer b = new Integer(0);   
    int c = 0;
    
    boolean isSame_EqOperator = (a==b); //false!
    boolean isSame_EqMethod = (a.equals(b)); //true
    boolean isSame_EqAutoUnbox = ((a==c) && (a.equals(c)); //also true, because of auto-unbox
    
    //Note: for initializing a and b, the Integer constructor 
    // is called explicitly to avoid integer object caching 
    // for the purpose of the example.
    // Calling it explicitly ensures each integer is created 
    // as a separate object as intended.
    // Edited in response to comment by @nolith
    

    Resizing an image in an HTML5 canvas

    Fast and simple Javascript image resizer:

    https://github.com/calvintwr/blitz-hermite-resize

    const blitz = Blitz.create()
    
    /* Promise */
    blitz({
        source: DOM Image/DOM Canvas/jQuery/DataURL/File,
        width: 400,
        height: 600
    }).then(output => {
        // handle output
    })catch(error => {
        // handle error
    })
    
    /* Await */
    let resized = await blizt({...})
    
    /* Old school callback */
    const blitz = Blitz.create('callback')
    blitz({...}, function(output) {
        // run your callback.
    })
    

    History

    This is really after many rounds of research, reading and trying.

    The resizer algorithm uses @ViliusL's Hermite script (Hermite resizer is really the fastest and gives reasonably good output). Extended with features you need.

    Forks 1 worker to do the resizing so that it doesn't freeze your browser when resizing, unlike all other JS resizers out there.

    How to have a drop down <select> field in a rails form?

    Rails drop down using has_many association for article and category:

    has_many :articles
    
    belongs_to :category
    
    <%= form.select :category_id,Category.all.pluck(:name,:id),{prompt:'select'},{class: "form-control"}%>
    

    What does %~d0 mean in a Windows batch file?

    It displays the current location of the file or directory that you are currently in. for example; if your batch file was in the desktop directory, then "%~dp0" would display the desktop directory. if you wanted it to display the current directory with the current file name you could type "%~dp0%~n0%~x0".

    char initial value in Java

    Typically for local variables I initialize them as late as I can. It's rare that I need a "dummy" value. However, if you do, you can use any value you like - it won't make any difference, if you're sure you're going to assign a value before reading it.

    If you want the char equivalent of 0, it's just Unicode 0, which can be written as

    char c = '\0';
    

    That's also the default value for an instance (or static) variable of type char.

    const to Non-const Conversion in C++

    Changing a constant type will lead to an Undefined Behavior.

    However, if you have an originally non-const object which is pointed to by a pointer-to-const or referenced by a reference-to-const then you can use const_cast to get rid of that const-ness.

    Casting away constness is considered evil and should not be avoided. You should consider changing the type of the pointers you use in vector to non-const if you want to modify the data through it.