Programs & Examples On #Stretching

How do I keep CSS floats in one line?

Wrap your floating <div>s in a container <div> that uses this cross-browser min-width hack:

.minwidth { min-width:100px; width: auto !important; width: 100px; }

You may also need to set "overflow" but probably not.

This works because:

  • The !important declaration, combined with min-width cause everything to stay on the same line in IE7+
  • IE6 does not implement min-width, but it has a bug such that width: 100px overrides the !important declaration, causing the container width to be 100px.

Generating random whole numbers in JavaScript in a specific range?

I know this question is already answered but my answer could help someone.

I found this simple method on W3Schools:

Math.floor((Math.random() * max) + min);

Hope this would help someone.

jQuery table sort

This is a nice way of sorting a table:

_x000D_
_x000D_
$(document).ready(function () {_x000D_
                $('th').each(function (col) {_x000D_
                    $(this).hover(_x000D_
                            function () {_x000D_
                                $(this).addClass('focus');_x000D_
                            },_x000D_
                            function () {_x000D_
                                $(this).removeClass('focus');_x000D_
                            }_x000D_
                    );_x000D_
                    $(this).click(function () {_x000D_
                        if ($(this).is('.asc')) {_x000D_
                            $(this).removeClass('asc');_x000D_
                            $(this).addClass('desc selected');_x000D_
                            sortOrder = -1;_x000D_
                        } else {_x000D_
                            $(this).addClass('asc selected');_x000D_
                            $(this).removeClass('desc');_x000D_
                            sortOrder = 1;_x000D_
                        }_x000D_
                        $(this).siblings().removeClass('asc selected');_x000D_
                        $(this).siblings().removeClass('desc selected');_x000D_
                        var arrData = $('table').find('tbody >tr:has(td)').get();_x000D_
                        arrData.sort(function (a, b) {_x000D_
                            var val1 = $(a).children('td').eq(col).text().toUpperCase();_x000D_
                            var val2 = $(b).children('td').eq(col).text().toUpperCase();_x000D_
                            if ($.isNumeric(val1) && $.isNumeric(val2))_x000D_
                                return sortOrder == 1 ? val1 - val2 : val2 - val1;_x000D_
                            else_x000D_
                                return (val1 < val2) ? -sortOrder : (val1 > val2) ? sortOrder : 0;_x000D_
                        });_x000D_
                        $.each(arrData, function (index, row) {_x000D_
                            $('tbody').append(row);_x000D_
                        });_x000D_
                    });_x000D_
                });_x000D_
            });
_x000D_
            table, th, td {_x000D_
            border: 1px solid black;_x000D_
        }_x000D_
        th {_x000D_
            cursor: pointer;_x000D_
        }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<table>_x000D_
        <tr><th>id</th><th>name</th><th>age</th></tr>_x000D_
        <tr><td>1</td><td>Julian</td><td>31</td></tr>_x000D_
        <tr><td>2</td><td>Bert</td><td>12</td></tr>_x000D_
        <tr><td>3</td><td>Xavier</td><td>25</td></tr>_x000D_
        <tr><td>4</td><td>Mindy</td><td>32</td></tr>_x000D_
        <tr><td>5</td><td>David</td><td>40</td></tr>_x000D_
    </table>
_x000D_
_x000D_
_x000D_

The fiddle can be found here:
https://jsfiddle.net/e3s84Luw/

The explanation can be found here: https://www.learningjquery.com/2017/03/how-to-sort-html-table-using-jquery-code

PHP exec() vs system() vs passthru()

The previous answers seem all to be a little confusing or incomplete, so here is a table of the differences...

+----------------+-----------------+----------------+----------------+
|    Command     | Displays Output | Can Get Output | Gets Exit Code |
+----------------+-----------------+----------------+----------------+
| system()       | Yes (as text)   | Last line only | Yes            |
| passthru()     | Yes (raw)       | No             | Yes            |
| exec()         | No              | Yes (array)    | Yes            |
| shell_exec()   | No              | Yes (string)   | No             |
| backticks (``) | No              | Yes (string)   | No             |
+----------------+-----------------+----------------+----------------+
  • "Displays Output" means it streams the output to the browser (or command line output if running from a command line).
  • "Can Get Output" means you can get the output of the command and assign it to a PHP variable.
  • The "exit code" is a special value returned by the command (also called the "return status"). Zero usually means it was successful, other values are usually error codes.

Other misc things to be aware of:

  • The shell_exec() and the backticks operator do the same thing.
  • There are also proc_open() and popen() which allow you to interactively read/write streams with an executing command.
  • Add "2>&1" to the command string if you also want to capture/display error messages.
  • Use escapeshellcmd() to escape command arguments that may contain problem characters.
  • If passing an $output variable to exec() to store the output, if $output isn't empty, it will append the new output to it. So you may need to unset($output) first.

Count immediate child div elements using jQuery

$("div", "#superpics").size();

Java JTable setting Column Width

No need for the option, just make the preferred width of the last column the maximum and it will take all the extra space.

table.getColumnModel().getColumn(0).setPreferredWidth(27);
table.getColumnModel().getColumn(1).setPreferredWidth(120);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(90);
table.getColumnModel().getColumn(4).setPreferredWidth(90);
table.getColumnModel().getColumn(6).setPreferredWidth(120);
table.getColumnModel().getColumn(7).setPreferredWidth(100);
table.getColumnModel().getColumn(8).setPreferredWidth(95);
table.getColumnModel().getColumn(9).setPreferredWidth(40);
table.getColumnModel().getColumn(10).setPreferredWidth(Integer.MAX_INT);

Save base64 string as PDF at client side with JavaScript

You will do not need any library for this. JavaScript support this already. Here is my end-to-end solution.

const xhr = new XMLHttpRequest();
xhr.open('GET', 'your-end-point', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.responseType = 'blob';
xhr.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
       if (window.navigator.msSaveOrOpenBlob) {
           window.navigator.msSaveBlob(this.response, "fileName.pdf");
        } else {
           const downloadLink = window.document.createElement('a');
           const contentTypeHeader = xhr.getResponseHeader("Content-Type");
           downloadLink.href = window.URL.createObjectURL(new Blob([this.response], { type: contentTypeHeader }));
           downloadLink.download = "fileName.pdf";
           document.body.appendChild(downloadLink);
           downloadLink.click();
           document.body.removeChild(downloadLink);
        }
    }
};
xhr.send(null);

This also work for .xls or .zip file. You just need to change file name to fileName.xls or fileName.zip. This depends on your case.

How do I get the key at a specific index from a Dictionary in Swift?

Here is an example, using Swift 1.2

var person = ["name":"Sean", "gender":"male"]
person.keys.array[1] // "gender", get a dictionary key at specific index 
person.values.array[1] // "male", get a dictionary value at specific index

Ansible: create a user with sudo privileges

Sometimes it's knowing what to ask. I didn't know as I am a developer who has taken on some DevOps work.

Apparently 'passwordless' or NOPASSWD login is a thing which you need to put in the /etc/sudoers file.

The answer to my question is at Ansible: best practice for maintaining list of sudoers.

The Ansible playbook code fragment looks like this from my problem:

- name: Make sure we have a 'wheel' group
  group:
    name: wheel
    state: present

- name: Allow 'wheel' group to have passwordless sudo
  lineinfile:
    dest: /etc/sudoers
    state: present
    regexp: '^%wheel'
    line: '%wheel ALL=(ALL) NOPASSWD: ALL'
    validate: 'visudo -cf %s'

- name: Add sudoers users to wheel group
  user:
    name=deployer
    groups=wheel
    append=yes
    state=present
    createhome=yes

- name: Set up authorized keys for the deployer user
  authorized_key: user=deployer key="{{item}}"
  with_file:
    - /home/railsdev/.ssh/id_rsa.pub

And the best part is that the solution is idempotent. It doesn't add the line

%wheel ALL=(ALL) NOPASSWD: ALL

to /etc/sudoers when the playbook is run a subsequent time. And yes...I was able to ssh into the server as "deployer" and run sudo commands without having to give a password.

Installing the Android USB Driver in Windows 7

Just download and install "Samsung Kies" from this link. and everything would work as required.

Before installing, uninstall the drivers you have installed for your device.

Update:

Two possible solutions:

  1. Try with the Google USB driver which comes with the SDK.
  2. Download and install the Samsung USB driver from this link as suggested by Mauricio Gracia Gutierrez

No grammar constraints (DTD or XML schema) detected for the document

I used a relative path in the xsi:noNamespaceSchemaLocation to provide the local xsd file (because I could not use a namespace in the instance xml).

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="../project/schema.xsd">
</root>

Validation works and the warning is fixed (not ignored).

https://www.w3schools.com/xml/schema_example.asp

Deleting an object in C++

Isn't this the normal way to free the memory associated with an object?

This is a common way of managing dynamically allocated memory, but it's not a good way to do so. This sort of code is brittle because it is not exception-safe: if an exception is thrown between when you create the object and when you delete it, you will leak that object.

It is far better to use a smart pointer container, which you can use to get scope-bound resource management (it's more commonly called resource acquisition is initialization, or RAII).

As an example of automatic resource management:

void test()
{
    std::auto_ptr<Object1> obj1(new Object1);

} // The object is automatically deleted when the scope ends.

Depending on your use case, auto_ptr might not provide the semantics you need. In that case, you can consider using shared_ptr.

As for why your program crashes when you delete the object, you have not given sufficient code for anyone to be able to answer that question with any certainty.

PYTHONPATH vs. sys.path

Neither hacking PYTHONPATH nor sys.path is a good idea due to the before mentioned reasons. And for linking the current project into the site-packages folder there is actually a better way than python setup.py develop, as explained here:

pip install --editable path/to/project

If you don't already have a setup.py in your project's root folder, this one is good enough to start with:

from setuptools import setup
setup('project')

How to read input with multiple lines in Java

package pac001;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Entry_box{



    public static final String[] relationship = {"Marrid", "Unmarried"};


    public static void main(String[] args)
    {
         //TAKING USER ID NUMBER
            int a = Integer.parseInt(JOptionPane.showInputDialog("Enter ID no: "));
        // TAKING INPUT FOR RELATIONSHIP
        JFrame frame = new JFrame("Input Dialog Example #3");
        String Relationship =   (String) JOptionPane.showInputDialog(frame,"Select Your Relationship","Married",
                                JOptionPane.QUESTION_MESSAGE, null, relationship,relationship[0]);



        //PRINTING THE ID NUMBER
        System.out.println("ID no: "+a);
        // PRINTING RESULT FOR RELATIONSHIP INPUT
          System.out.printf("Mariitual Status: %s\n", Relationship);

        }
}

How to add java plugin for Firefox on Linux?

Do you want the JDK or the JRE? Anyways, I had this problem too, a few weeks ago. I followed the instructions here and it worked:

http://www.backtrack-linux.org/wiki/index.php/Java_Install

NOTE: Before installing Java make sure you kill Firefox.

root@bt:~# killall -9 /opt/firefox/firefox-bin

You can download java from the official website. (Download tar.gz version)

We first create the directory and place java there:

root@bt:~# mkdir /opt/java

root@bt:~# mv -f jre1.7.0_05/ /opt/java/

Final changes.

root@bt:~# update-alternatives --install /usr/bin/java java /opt/java/jre1.7.0_05/bin/java 1

root@bt:~# update-alternatives --set java /opt/java/jre1.7.0_05/bin/java

root@bt:~# export JAVA_HOME="/opt/java/jre1.7.0_05"

Adding the plugin to Firefox.

For Java 7 (32 bit)

root@bt:~# ln -sf $JAVA_HOME/lib/i386/libnpjp2.so /usr/lib/mozilla/plugins/

For Java 8 (64 bit)

root@bt:~# ln -sf $JAVA_HOME/jre/lib/amd64/libnpjp2.so /usr/lib/mozilla/plugins/

Testing the plugin.

root@bt:~# firefox http://java.com/en/download/testjava.jsp

How to plot a 2D FFT in Matlab?

Assuming that I is your input image and F is its Fourier Transform (i.e. F = fft2(I))

You can use this code:

F = fftshift(F); % Center FFT

F = abs(F); % Get the magnitude
F = log(F+1); % Use log, for perceptual scaling, and +1 since log(0) is undefined
F = mat2gray(F); % Use mat2gray to scale the image between 0 and 1

imshow(F,[]); % Display the result

Compare every item to every other item in ArrayList

The following code will compare each item with other list of items using contains() method.Length of for loop must be bigger size() of bigger list then only it will compare all the values of both list.

List<String> str = new ArrayList<String>();
str.add("first");
str.add("second");
str.add("third");
List<String> str1 = new ArrayList<String>();
str1.add("first");
str1.add("second");
str1.add("third1");
for (int i = 0; i<str1.size(); i++)
{
System.out.println(str.contains(str1.get(i)));
}

Output is true true false

Batch file to delete folders older than 10 days in Windows 7

FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"

I could not get Blorgbeard's suggestion to work, but I was able to get it to work with RMDIR instead of RD:

FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"

Since RMDIR won't delete folders that aren't empty so I also ended up using this code to delete the files that were over 10 days and then the folders that were over 10 days old.

FOR /d %%K in ("n:\test*") DO (

FOR /d %%J in ("%%K*") DO (

FORFILES /P %%J /S /M . /D -10 /C "cmd /c del @file"

)

)

FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"

I used this code to purge out the sub folders in the folders within test (example n:\test\abc\123 would get purged when empty, but n:\test\abc would not get purged

Is there a Python Library that contains a list of all the ascii characters?

You can do this without a module:

    characters = list(map(chr, range(97,123)))

Type characters and it should print ["a","b","c", ... ,"x","y","z"]. For uppercase use:

    characters=list(map(chr,range(65,91)))

Any range (including the use of range steps) can be used for this, because it makes use of Unicode. Therefore, increase the range() to add more characters to the list.
map() calls chr() every iteration of the range().

How many spaces will Java String.trim() remove?

From java docs(String class source),

/**
 * Returns a copy of the string, with leading and trailing whitespace
 * omitted.
 * <p>
 * If this <code>String</code> object represents an empty character
 * sequence, or the first and last characters of character sequence
 * represented by this <code>String</code> object both have codes
 * greater than <code>'&#92;u0020'</code> (the space character), then a
 * reference to this <code>String</code> object is returned.
 * <p>
 * Otherwise, if there is no character with a code greater than
 * <code>'&#92;u0020'</code> in the string, then a new
 * <code>String</code> object representing an empty string is created
 * and returned.
 * <p>
 * Otherwise, let <i>k</i> be the index of the first character in the
 * string whose code is greater than <code>'&#92;u0020'</code>, and let
 * <i>m</i> be the index of the last character in the string whose code
 * is greater than <code>'&#92;u0020'</code>. A new <code>String</code>
 * object is created, representing the substring of this string that
 * begins with the character at index <i>k</i> and ends with the
 * character at index <i>m</i>-that is, the result of
 * <code>this.substring(<i>k</i>,&nbsp;<i>m</i>+1)</code>.
 * <p>
 * This method may be used to trim whitespace (as defined above) from
 * the beginning and end of a string.
 *
 * @return  A copy of this string with leading and trailing white
 *          space removed, or this string if it has no leading or
 *          trailing white space.
 */
public String trim() {
int len = count;
int st = 0;
int off = offset;      /* avoid getfield opcode */
char[] val = value;    /* avoid getfield opcode */

while ((st < len) && (val[off + st] <= ' ')) {
    st++;
}
while ((st < len) && (val[off + len - 1] <= ' ')) {
    len--;
}
return ((st > 0) || (len < count)) ? substring(st, len) : this;
}

Note that after getting start and length it calls the substring method of String class.

How to pass a value from one jsp to another jsp page?

Using Query parameter

<a href="edit.jsp?userId=${user.id}" />  

Using Hidden variable .

<form method="post" action="update.jsp">  
...  
   <input type="hidden" name="userId" value="${user.id}">  

you can send Using Session object.

   session.setAttribute("userId", userid);

These values will now be available from any jsp as long as your session is still active.

   int userid = session.getAttribute("userId"); 

How to move or copy files listed by 'find' command in unix?

Adding to Eric Jablow's answer, here is a possible solution (it worked for me - linux mint 14 /nadia)

find /path/to/search/ -type f -name "glob-to-find-files" | xargs cp -t /target/path/

You can refer to "How can I use xargs to copy files that have spaces and quotes in their names?" as well.

SQL Query to search schema of all tables

Use this query :

SELECT 
    t.name AS table_name,
    SCHEMA_NAME(schema_id) AS schema_name,
    c.name AS column_name , *
FROM sys.tables AS t
    INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID 
Where 
    ( c.name LIKE '%' + '<ColumnName>' + '%' )
    AND 
    ( t.type = 'U' ) -- Use This To Prevent Selecting System Tables

In Java, how to find if first character in a string is upper case without regex

Make sure you first check for null and empty and ten converts existing string to upper. Use S.O.P if want to see outputs otherwise boolean like Rabiz did.

 public static void main(String[] args)
 {
     System.out.println("Enter name");
     Scanner kb = new Scanner (System.in);
     String text =  kb.next();

     if ( null == text || text.isEmpty())
     {
         System.out.println("Text empty");
     }
     else if (text.charAt(0) == (text.toUpperCase().charAt(0)))
     {
         System.out.println("First letter in word "+ text + " is upper case");
     }
  }

Vertically align text to top within a UILabel

Like the answer above, but it wasn't quite right, or easy to slap into code so I cleaned it up a bit. Add this extension either to it's own .h and .m file or just paste right above the implementation you intend to use it:

#pragma mark VerticalAlign
@interface UILabel (VerticalAlign)
- (void)alignTop;
- (void)alignBottom;
@end


@implementation UILabel (VerticalAlign)
- (void)alignTop
{
    CGSize fontSize = [self.text sizeWithFont:self.font];

    double finalHeight = fontSize.height * self.numberOfLines;
    double finalWidth = self.frame.size.width;    //expected width of label


    CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];


    int newLinesToPad = (finalHeight  - theStringSize.height) / fontSize.height;

    for(int i=0; i<= newLinesToPad; i++)
    {
        self.text = [self.text stringByAppendingString:@" \n"];
    }
}

- (void)alignBottom
{
    CGSize fontSize = [self.text sizeWithFont:self.font];

    double finalHeight = fontSize.height * self.numberOfLines;
    double finalWidth = self.frame.size.width;    //expected width of label


    CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];


    int newLinesToPad = (finalHeight  - theStringSize.height) / fontSize.height;

    for(int i=0; i< newLinesToPad; i++)
    {
        self.text = [NSString stringWithFormat:@" \n%@",self.text];
    }
}
@end

And then to use, put your text into the label, and then call the appropriate method to align it:

[myLabel alignTop];

or

[myLabel alignBottom];

How to write and read a file with a HashMap?

You can write an object to a file using writeObject in ObjectOutputStream

ObjectOutputStream

Check variable equality against a list of values

If you have access to Underscore, you can use the following:

if (_.contains([1, 3, 12], foo)) {
  // ...
}

contains used to work in Lodash as well (prior to V4), now you have to use includes

if (_.includes([1, 3, 12], foo)) {
  handleYellowFruit();
}

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

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

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

How to properly -filter multiple strings in a PowerShell copy script

-Filter only accepts a single string. -Include accepts multiple values, but qualifies the -Path argument. The trick is to append \* to the end of the path, and then use -Include to select multiple extensions. BTW, quoting strings is unnecessary in cmdlet arguments unless they contain spaces or shell special characters.

Get-ChildItem $originalPath\* -Include *.gif, *.jpg, *.xls*, *.doc*, *.pdf*, *.wav*, .ppt*

Note that this will work regardless of whether $originalPath ends in a backslash, because multiple consecutive backslashes are interpreted as a single path separator. For example, try:

Get-ChildItem C:\\\\\Windows

How to replace a character from a String in SQL?

Use the REPLACE function.

eg: SELECT REPLACE ('t?es?t', '?', 'w');

Source

Android basics: running code in the UI thread

There is a fourth way using Handler

new Handler().post(new Runnable() {
    @Override
    public void run() {
        // Code here will run in UI thread
    }
});

What is difference between Lightsail and EC2?

Testing¹ reveals that Lightsail instances in fact are EC2 instances, from the t2 class of burstable instances.

EC2, of course, has many more instance families and classes other than the t2, almost all of which are more "powerful" (or better equipped for certain tasks) than these, but also much more expensive. But for meaningful comparisons, the 512 MiB Lightsail instance appears to be completely equivalent in specifications to the similarly-priced t2.nano, the 1GiB is a t2.micro, the 2 GiB is a t2.small, etc.

Lightsail is a lightweight, simplified product offering -- hard disks are fixed size EBS SSD volumes, instances are still billable when stopped, security group rules are much less flexible, and only a very limited subset of EC2 features and options are accessible.

It also has a dramatically simplified console, and even though the machines run in EC2, you can't see them in the EC2 section of the AWS console. The instances run in a special VPC, but this aspect is also provisioned automatically, and invisible in the console. Lightsail supports optionally peering this hidden VPC with your default VPC in the same AWS region, allowing Lightsail instances to access services like EC2 and RDS in the default VPC within the same AWS account.²

Bandwidth is unlimited, but of course free bandwidth is not -- however, Lightsail instances do include a significant monthly bandwidth allowance before any bandwidth-related charges apply.³ Lightsail also has a simplified interface to Route 53 with limited functionality.

But if those sound like drawbacks, they aren't. The point of Lightsail seems to be simplicity. The flexibility of EC2 (and much of AWS) leads inevitably to complexity. The target market for Lightsail appears to be those who "just want a simple VPS" without having to navigate the myriad options available in AWS services like EC2, EBS, VPC, and Route 53. There is virtually no learning curve, here. You don't even technically need to know how to use SSH with a private key -- the Lightsail console even has a built-in SSH client -- but there is no requirement that you use it. You can access these instances normally, with a standard SSH client.


¹Lightsail instances, just like "regular" EC2 (VPC and Classic) instances, have access to the instance metadata service, which allows an instance to discover things about itself, such as its instance type and availability zone. Lightsail instances are identified in the instance metadata as t2 machines.

²The Lightsail docs are not explicit about the fact that peering only works with your Default VPC, but this appears to be the case. If your AWS account was created in 2013 or before, then you may not actually have a VPC with the "Default VPC" designation. This can be resolved by submitting a support request, as I explained in Can't establish VPC peering connection from Amazon Lightsail (at Server Fault).

³The bandwidth allowance applies to both inbound and outbound traffic; after this total amount of traffic is exceeded, inbound traffic continues to be free, but outbound traffic becomes billable. See "What does data transfer cost?" in the Lightsail FAQ.

How do I check whether a checkbox is checked in jQuery?

Toggle: 0/1 or else

<input type="checkbox" id="nolunch" />
<input id="checklunch />"

    $('#nolunch').change(function () {
    if ($(this).is(':checked')) {
        $('#checklunch').val('1');
    };
    if ($(this).is(':checked') == false) {
        $('#checklunch').val('0');
    };
});

Getting random numbers in Java

The first solution is to use the java.util.Random class:

import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;

Another solution is using Math.random():

double random = Math.random() * 49 + 1;

or

int random = (int)(Math.random() * 50 + 1);

Select query to remove non-numeric characters

Here is an elegant solution if your server supports the TRANSLATE function (on sql server it's available on sql server 2017+ and also sql azure).

First, it replaces any non numeric characters with a @ character. Then, it removes all @ characters. You may need to add additional characters that you know may be present in the second parameter of the TRANSLATE call.

select REPLACE(TRANSLATE([Col], 'abcdefghijklmnopqrstuvwxyz+()- ,#+', '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@'), '@', '')

Javascript: Fetch DELETE and PUT requests

Ok, here is a fetch DELETE example too:

fetch('https://example.com/delete-item/' + id, {
  method: 'DELETE',
})
.then(res => res.text()) // or res.json()
.then(res => console.log(res))

Beginner Python: AttributeError: 'list' object has no attribute

Consider:

class Bike(object):
    def __init__(self, name, weight, cost):
        self.name = name
        self.weight = weight
        self.cost = cost

bikes = {
    # Bike designed for children"
    "Trike": Bike("Trike", 20, 100),      # <--
    # Bike designed for everyone"
    "Kruzer": Bike("Kruzer", 50, 165),    # <--
    }

# Markup of 20% on all sales
margin = .2
# Revenue minus cost after sale
for bike in bikes.values():
    profit = bike.cost * margin
    print(profit)

Output:

33.0
20.0

The difference is that in your bikes dictionary, you're initializing the values as lists [...]. Instead, it looks like the rest of your code wants Bike instances. So create Bike instances: Bike(...).

As for your error

AttributeError: 'list' object has no attribute 'cost'

this will occur when you try to call .cost on a list object. Pretty straightforward, but we can figure out what happened by looking at where you call .cost -- in this line:

profit = bike.cost * margin

This indicates that at least one bike (that is, a member of bikes.values() is a list). If you look at where you defined bikes you can see that the values were, in fact, lists. So this error makes sense.

But since your class has a cost attribute, it looked like you were trying to use Bike instances as values, so I made that little change:

[...] -> Bike(...)

and you're all set.

Convert from ASCII string encoded in Hex to plain ASCII?

Alternatively, you can also do this ...

Python 2 Interpreter

print "\x70 \x61 \x75 \x6c"

Example

user@linux:~# python
Python 2.7.14+ (default, Mar 13 2018, 15:23:44) 
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> print "\x70 \x61 \x75 \x6c"
p a u l
>>> exit()
user@linux:~# 

or

Python 2 One-Liner

python -c 'print "\x70 \x61 \x75 \x6c"'

Example

user@linux:~# python -c 'print "\x70 \x61 \x75 \x6c"'
p a u l
user@linux:~# 

Python 3 Interpreter

user@linux:~$ python3
Python 3.6.9 (default, Apr 18 2020, 01:56:04) 
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> print("\x70 \x61 \x75 \x6c")
p a u l

>>> print("\x70\x61\x75\x6c")
paul

Python 3 One-Liner

python -c 'print("\x70 \x61 \x75 \x6c")'

Example

user@linux:~$ python -c 'print("\x70 \x61 \x75 \x6c")'
p a u l

user@linux:~$ python -c 'print("\x70\x61\x75\x6c")'
paul

How to check if anonymous object has a method?

One way to do it must be if (typeof myObj.prop1 != "undefined") {...}

Generating a PDF file from React Components

I used jsPDF and html-to-image.

You can check out the code on the below git repo.

Link

If you like, you can drop a star there??

How do I get the application exit code from a Windows command line?

A pseudo environment variable named errorlevel stores the exit code:

echo Exit Code is %errorlevel%

Also, the if command has a special syntax:

if errorlevel

See if /? for details.

Example

@echo off
my_nify_exe.exe
if errorlevel 1 (
   echo Failure Reason Given is %errorlevel%
   exit /b %errorlevel%
)

Warning: If you set an environment variable name errorlevel, %errorlevel% will return that value and not the exit code. Use (set errorlevel=) to clear the environment variable, allowing access to the true value of errorlevel via the %errorlevel% environment variable.

How can I create a dropdown menu from a List in Tkinter?

To create a "drop down menu" you can use OptionMenu in tkinter

Example of a basic OptionMenu:

from Tkinter import *

master = Tk()

variable = StringVar(master)
variable.set("one") # default value

w = OptionMenu(master, variable, "one", "two", "three")
w.pack()

mainloop()

More information (including the script above) can be found here.


Creating an OptionMenu of the months from a list would be as simple as:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

mainloop()

In order to retrieve the value the user has selected you can simply use a .get() on the variable that we assigned to the widget, in the below case this is variable:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

def ok():
    print ("value is:" + variable.get())

button = Button(master, text="OK", command=ok)
button.pack()

mainloop()

I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.

How to make 'submit' button disabled?

Form validation is very much straight forward in Angular 2

Here is an example,

<form (ngSubmit)="onSubmit()" #myForm="ngForm">

 <div class="form-group">
  <label for="firstname">First Name</label>
  <input type="text" class="form-control" id="firstname" 
   required [(ngModel)]="firstname" name="firstname">
 </div>

 <div class="form-group">
  <label for="middlename">Middle Name</label>
  <input type="text"  class="form-control" id="middlename" 
   [(ngModel)]="middlename" name="middlename">
 </div>

 <div class="form-group">
  <label for="lastname">Last Name</label>
  <input type="text"  class="form-control" id="lastname" 
   required minlength = '2' maxlength="6" [(ngModel)] = "lastname" name="lastname">
 </div>

 <div class="form-group">
  <label for="mobnumber">Mob Number</label>
  <input type="text"  class="form-control" id="mobnumber"  
   minlength = '2' maxlength="10" pattern="^[0-9()\-+\s]+$" 
   [(ngModel)] = "mobnumber" name="mobnumber">
 </div>

 <button type="submit" [disabled]="!myForm.form.valid">Submit</button>

</form>

Check this plunker for demo

More info

What is best way to start and stop hadoop ecosystem, with command line?

Starting

start-dfs.sh (starts the namenode and the datanode)
start-mapred.sh (starts the jobtracker and the tasktracker)

Stopping

stop-dfs.sh
stop-mapred.sh

Get Context in a Service

Since Service is a Context, the variable context must be this:

DataBaseManager dbm = Utils.getDataManager(this);   

ArrayList of int array in java

In java, an array is an object. Therefore the call to arl.get(0) returns a primitive int[] object which appears as ascii in your call to System.out.

The answer to your first question is therefore

System.out.println("Arraylist contains:"+Arrays.toString( arl.get( 0 ) ) );

If you're looking for particular elements, the returned int[] object must be referenced as such. The answer to your second question would be something like

    int[] contentFromList = arl.get(0);
    for (int i = 0; i < contentFromList.length; i++) {
        int j = contentFromList[i];
        System.out.println("Value at index - "+i+" is :"+j);
    }

What size should apple-touch-icon.png be for iPad and iPhone?

I think this question is about web icons. I've tried giving an icon at 512x512, and on the iPhone 4 simulator it looks great (in the preview) however, when added to the home-screen it's badly pixelated.

On the good side, if you use a larger icon on the iPad (still with my 512x512 test) it does seem to come out in better quality on the iPad. Hopefully the iPhone 4 rendering is a bug.

I've opened a bug about this on radar.

EDIT:

I'm currently using a 114x114 icon in hopes that it'll look good on the iPhone 4 when it is released. If the iPhone 4 still has a bug when it comes out, I'm going to optimize the icon for the iPad (crisp and no resize at 72x72), and then let it scale down for old iPhones.

How to check if String value is Boolean type in Java?

See oracle docs

public static boolean parseBoolean(String s) {
        return ((s != null) && s.equalsIgnoreCase("true"));
    }

How to print Boolean flag in NSLog?

In Swift, you can simply print a boolean value and it will be displayed as true or false.

let flag = true
print(flag) //true

Insert/Update/Delete with function in SQL Server

Just another alternative using sp_executesql (tested only in SQL 2016). As previous posts noticed, atomicity must be handled elsewhere.

CREATE FUNCTION [dbo].[fn_get_service_version_checksum2]
(
    @ServiceId INT
)
RETURNS INT
AS
BEGIN
DECLARE @Checksum INT;
SELECT @Checksum = dbo.fn_get_service_version(@ServiceId);
DECLARE @LatestVersion INT = (SELECT MAX(ServiceVersion) FROM [ServiceVersion] WHERE ServiceId = @ServiceId);
-- Check whether the current version already exists and that it's the latest version.
IF EXISTS(SELECT TOP 1 1 FROM [ServiceVersion] WHERE ServiceId = @ServiceId AND [Checksum] = @Checksum AND ServiceVersion = @LatestVersion)
    RETURN @LatestVersion;
-- Insert the new version to the table.
EXEC sp_executesql N'
INSERT INTO [ServiceVersion] (ServiceId, ServiceVersion, [Checksum], [Timestamp])
VALUES (@ServiceId, @LatestVersion + 1, @Checksum, GETUTCDATE());',
N'@ServiceId INT = NULL, @LatestVersion INT = NULL, @Checksum INT = NULL',
@ServiceId = @ServiceId,
@LatestVersion = @LatestVersion,
@Checksum = @Checksum
;
RETURN @LatestVersion + 1;
END;

Converting float to char*

In Arduino:

//temporarily holds data from vals
char charVal[10];                

//4 is mininum width, 3 is precision; float value is copied onto buff
dtostrf(123.234, 4, 3, charVal);

monitor.print("charVal: ");
monitor.println(charVal);

Creating a textarea with auto-resize

The best solution (works and is short) for me is:

    $(document).on('input', 'textarea', function () {
        $(this).outerHeight(38).outerHeight(this.scrollHeight); // 38 or '1em' -min-height
    }); 

It works like a charm without any blinking with paste (with mouse also), cut, entering and it shrinks to the right size.

Please take a look at jsFiddle.

Is there a C++ gdb GUI for Linux?

As someone familiar with Visual Studio, I've looked at several open source IDE's to replace it, and KDevelop comes the closest IMO to being something that a Visual C++ person can just sit down and start using. When you run the project in debugging mode, it uses gdb but kdevelop pretty much handles the whole thing so that you don't have to know it's gdb; you're just single stepping or assigning watches to variables.

It still isn't as good as the Visual Studio Debugger, unfortunately.

Get custom product attributes in Woocommerce

Use below code to get all attributes with details

    global $wpdb;

    $attribute_taxonomies = $wpdb->get_results( "SELECT * FROM " . $wpdb->prefix . "woocommerce_attribute_taxonomies WHERE attribute_name != '' ORDER BY attribute_name ASC;" );
    set_transient( 'wc_attribute_taxonomies', $attribute_taxonomies );

    $attribute_taxonomies = array_filter( $attribute_taxonomies  ) ;

    prin_r($attribute_taxonomies);

Reverse for '*' with arguments '()' and keyword arguments '{}' not found

There are 3 things I can think of off the top of my head:

  1. Just used named urls, it's more robust and maintainable anyway
  2. Try using django.core.urlresolvers.reverse at the command line for a (possibly) better error

    >>> from django.core.urlresolvers import reverse
    >>> reverse('products.views.filter_by_led')
    
  3. Check to see if you have more than one url that points to that view

What is the use of a cursor in SQL Server?

Cursor might used for retrieving data row by row basis.its act like a looping statement(ie while or for loop). To use cursors in SQL procedures, you need to do the following: 1.Declare a cursor that defines a result set. 2.Open the cursor to establish the result set. 3.Fetch the data into local variables as needed from the cursor, one row at a time. 4.Close the cursor when done.

for ex:

declare @tab table
(
Game varchar(15),
Rollno varchar(15)
)
insert into @tab values('Cricket','R11')
insert into @tab values('VollyBall','R12')

declare @game  varchar(20)
declare @Rollno varchar(20)

declare cur2 cursor for select game,rollno from @tab 

open cur2

fetch next from cur2 into @game,@rollno

WHILE   @@FETCH_STATUS = 0   
begin

print @game

print @rollno

FETCH NEXT FROM cur2 into @game,@rollno

end

close cur2

deallocate cur2

How to select data of a table from another database in SQL Server?

To do a cross server query, check out the system stored procedure: sp_addlinkedserver in the help files.

Once the server is linked you can run a query against it.

How to use SVN, Branch? Tag? Trunk?

The subversion book is an excellent source of information on strategies for laying out your repository, branching and tagging.

See also:

Do you continue development in a branch or in the trunk

Branching strategies

How to easily initialize a list of Tuples?

Super Duper Old I know but I would add my piece on using Linq and continuation lambdas on methods with using C# 7. I try to use named tuples as replacements for DTOs and anonymous projections when reused in a class. Yes for mocking and testing you still need classes but doing things inline and passing around in a class is nice to have this newer option IMHO. You can instantiate them from

  1. Direct Instantiation
var items = new List<(int Id, string Name)> { (1, "Me"), (2, "You")};
  1. Off of an existing collection, and now you can return well typed tuples similar to how anonymous projections used to be done.
public class Hold
{
    public int Id { get; set; }
    public string Name { get; set; }
}

//In some method or main console app:
var holds = new List<Hold> { new Hold { Id = 1, Name = "Me" }, new Hold { Id = 2, Name = "You" } };
var anonymousProjections = holds.Select(x => new { SomeNewId = x.Id, SomeNewName = x.Name });
var namedTuples = holds.Select(x => (TupleId: x.Id, TupleName: x.Name));
  1. Reuse the tuples later with grouping methods or use a method to construct them inline in other logic:
//Assuming holder class above making 'holds' object
public (int Id, string Name) ReturnNamedTuple(int id, string name) => (id, name);
public static List<(int Id, string Name)> ReturnNamedTuplesFromHolder(List<Hold> holds) => holds.Select(x => (x.Id, x.Name)).ToList();
public static void DoSomethingWithNamedTuplesInput(List<(int id, string name)> inputs) => inputs.ForEach(x => Console.WriteLine($"Doing work with {x.id} for {x.name}"));

var namedTuples2 = holds.Select(x => ReturnNamedTuple(x.Id, x.Name));
var namedTuples3 = ReturnNamedTuplesFromHolder(holds);
DoSomethingWithNamedTuplesInput(namedTuples.ToList());

Entity Framework Query for inner join

In case anyone's interested in the Method syntax, if you have a navigation property, it's way easy:

db.Services.Where(s=>s.ServiceAssignment.LocationId == 1);

If you don't, unless there's some Join() override I'm unaware of, I think it looks pretty gnarly (and I'm a Method syntax purist):

db.Services.Join(db.ServiceAssignments, 
     s => s.Id,
     sa => sa.ServiceId, 
     (s, sa) => new {service = s, asgnmt = sa})
.Where(ssa => ssa.asgnmt.LocationId == 1)
.Select(ssa => ssa.service);

How to count string occurrence in string?

No one will ever see this, but it's good to bring back recursion and arrow functions once in a while (pun gloriously intended)

String.prototype.occurrencesOf = function(s, i) {
 return (n => (n === -1) ? 0 : 1 + this.occurrencesOf(s, n + 1))(this.indexOf(s, (i || 0)));
};

2D cross-platform game engine for Android and iOS?

Here is just a reply from Richard Pickup on LinkedIn to a similar question of mine:

I've used cocos 2dx marmalade and unity on both iOS and android. For 2d games cocos2dx is the way to go every time. Unity is just too much overkill for 2d games and as already stated marmalade is just a thin abstraction layer not really a game engine. You can even run cocos2d on top of marmalade. My approach would be to use cocos2dx on iOS and android then in future run cocosd2dx code on top of marmalade as an easy way to port to bb10 and win phone 7

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

This can be done in one line with lodash _.tail:

_x000D_
_x000D_
var arr = ["item 1", "item 2", "item 3", "item 4"];_x000D_
console.log(_.tail(arr));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

How to fix C++ error: expected unqualified-id

For anyone with this situation: I saw this error when I accidentally used my_first_scope::my_second_scope::true in place of simply true, like this:

bool my_var = my_first_scope::my_second_scope::true;

instead of:

bool my_var = true;

This is because I had a macro which caused MY_MACRO(true) to expand into my_first_scope::my_second_scope::true, by mistake, and I was actually calling bool my_var = MY_MACRO(true);.

Here's a quick demo of this type of scoping error:

Program (you can run it online here: https://onlinegdb.com/BkhFBoqUw):

#include <iostream>
#include <cstdio>

namespace my_first_scope 
{
namespace my_second_scope
{
} // namespace my_second_scope
} // namespace my_first_scope

int main()
{
    printf("Hello World\n");
    
    bool my_var = my_first_scope::my_second_scope::true;
    
    std::cout << my_var << std::endl;

    return 0;
}

Output (build error):

main.cpp: In function ‘int main()’:
main.cpp:27:52: error: expected unqualified-id before ‘true’
     bool my_var = my_first_scope::my_second_scope::true;
                                                    ^~~~

Notice the error: error: expected unqualified-id before ‘true’, and where the arrow under the error is pointing. Apparently the "unqualified-id" in my case is the double colon (::) scope operator I have just before true.

When I add in the macro and use it (run this new code here: https://onlinegdb.com/H1eevs58D):

#define MY_MACRO(input) my_first_scope::my_second_scope::input

...

bool my_var = MY_MACRO(true);

I get this new error instead:

main.cpp: In function ‘int main()’:
main.cpp:29:28: error: expected unqualified-id before ‘true’
     bool my_var = MY_MACRO(true);
                            ^
main.cpp:16:58: note: in definition of macro ‘MY_MACRO’
 #define MY_MACRO(input) my_first_scope::my_second_scope::input
                                                          ^~~~~

SQL NVARCHAR and VARCHAR Limits

Okay, so if later on down the line the issue is that you have a query that's greater than the allowable size (which may happen if it keeps growing) you're going to have to break it into chunks and execute the string values. So, let's say you have a stored procedure like the following:

CREATE PROCEDURE ExecuteMyHugeQuery
    @SQL VARCHAR(MAX) -- 2GB size limit as stated by Martin Smith
AS
BEGIN
    -- Now, if the length is greater than some arbitrary value
    -- Let's say 2000 for this example
    -- Let's chunk it
    -- Let's also assume we won't allow anything larger than 8000 total
    DECLARE @len INT
    SELECT @len = LEN(@SQL)

    IF (@len > 8000)
    BEGIN
        RAISERROR ('The query cannot be larger than 8000 characters total.',
                   16,
                   1);
    END

    -- Let's declare our possible chunks
    DECLARE @Chunk1 VARCHAR(2000),
            @Chunk2 VARCHAR(2000),
            @Chunk3 VARCHAR(2000),
            @Chunk4 VARCHAR(2000)

    SELECT @Chunk1 = '',
           @Chunk2 = '',
           @Chunk3 = '',
           @Chunk4 = ''

    IF (@len > 2000)
    BEGIN
        -- Let's set the right chunks
        -- We already know we need two chunks so let's set the first
        SELECT @Chunk1 = SUBSTRING(@SQL, 1, 2000)

        -- Let's see if we need three chunks
        IF (@len > 4000)
        BEGIN
            SELECT @Chunk2 = SUBSTRING(@SQL, 2001, 2000)

            -- Let's see if we need four chunks
            IF (@len > 6000)
            BEGIN
                SELECT @Chunk3 = SUBSTRING(@SQL, 4001, 2000)
                SELECT @Chunk4 = SUBSTRING(@SQL, 6001, (@len - 6001))
            END
              ELSE
            BEGIN
                SELECT @Chunk3 = SUBSTRING(@SQL, 4001, (@len - 4001))
            END
        END
          ELSE
        BEGIN
            SELECT @Chunk2 = SUBSTRING(@SQL, 2001, (@len - 2001))
        END
    END

    -- Alright, now that we've broken it down, let's execute it
    EXEC (@Chunk1 + @Chunk2 + @Chunk3 + @Chunk4)
END

Change route params without reloading in Angular 2

Using location.go(url) is the way to go, but instead of hardcoding the url , consider generating it using router.createUrlTree().

Given that you want to do the following router call: this.router.navigate([{param: 1}], {relativeTo: this.activatedRoute}) but without reloading the component, it can be rewritten as:

const url = this.router.createUrlTree([], {relativeTo: this.activatedRoute, queryParams: {param: 1}}).toString()

 this.location.go(url);

Start script missing error when running npm start

In my case, if it's a react project, you can try to upgrade npm, and then upgrade react-cli

npm -g install npm@version
npm install -g create-react-app

Could not find module "@angular-devkit/build-angular"

Delete package-lock.json and do npm install again. It should fix the issue.

** This fix is more suitable when you have created Angular 6 app using ng new and after installing other dependencies you find this error.

How can I display a list view in an Android Alert Dialog?

final CharSequence[] items = {"A", "B", "C"};

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Make your selection");
builder.setItems(items, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int item) {
        // Do something with the selection
        mDoneButton.setText(items[item]);
    }
});
AlertDialog alert = builder.create();
alert.show();

Positioning background image, adding padding

first off, to be a bit of a henpeck, its best NOT to use just the <background> tag. rather, use the proper, more specific, <background-image> tag.

the only way that i'm aware of to do such a thing is to build the padding into the image by extending the matte. since the empty pixels aren't stripped, you have your padding right there. so if you need a 10px border, create 10px of empty pixels all around your image. this is mui simple in Photoshop, Fireworks, GIMP, &c.

i'd also recommend trying out the PNG8 format instead of the dying GIF... much better.

there may be an alternate solution to your problem if we knew a bit more of how you're using it. :) it LOOKS like you're trying to add an accordion button. this would be best placed in the HTML because then you can target it with JavaScript/PHP; something you cannot do if it's in the background (at least not simply). in such a case, you can style the heck out of the image you currently have in CSS by using the following:

#hello img { padding: 10px; }

WR!

Predicate in Java

You can view the java doc examples or the example of usage of Predicate here

Basically it is used to filter rows in the resultset based on any specific criteria that you may have and return true for those rows that are meeting your criteria:

 // the age column to be between 7 and 10
    AgeFilter filter = new AgeFilter(7, 10, 3);

    // set the filter.
    resultset.beforeFirst();
    resultset.setFilter(filter);

How to increase executionTimeout for a long-running query?

You can set executionTimeout in web.config to support the longer execution time.

executionTimeout specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET. MSDN

<httpRuntime  executionTimeout = "300" />

This make execution timeout to five minutes.

Optional Int32 attribute.

Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.

This time-out applies only if the debug attribute in the compilation element is False. Therefore, if the debug attribute is True, you do not have to set this attribute to a large value in order to avoid application shutdown while you are debugging. The default is 110 seconds, Reference.

How do I find the PublicKeyToken for a particular dll?

sn -T <assembly> in Visual Studio command line. If an assembly is installed in the global assembly cache, it's easier to go to C:\Windows\assembly and find it in the list of GAC assemblies.

On your specific case, you might be mixing type full name with assembly reference, you might want to take a look at MSDN.

Calling onclick on a radiobutton list using javascript

I agree with @annakata that this question needs some more clarification, but here is a very, very basic example of how to setup an onclick event handler for the radio buttons:

<html>
 <head>
  <script type="text/javascript">
    window.onload = function() {

        var ex1 = document.getElementById('example1');
        var ex2 = document.getElementById('example2');
        var ex3 = document.getElementById('example3');

        ex1.onclick = handler;
        ex2.onclick = handler;
        ex3.onclick = handler;

    }

    function handler() {
        alert('clicked');
    }
  </script>
 </head>
 <body>
  <input type="radio" name="example1" id="example1" value="Example 1" />
  <label for="example1">Example 1</label>
  <input type="radio" name="example2" id="example2" value="Example 2" />
  <label for="example1">Example 2</label>
  <input type="radio" name="example3" id="example3" value="Example 3" />
  <label for="example1">Example 3</label>
 </body>
</html>

An attempt was made to access a socket in a way forbidden by its access permissions

My windows firewall was blocking port 8080 so i changed it to 5000 and it worked!

What does the "static" modifier after "import" mean?

There is no difference between those two imports you state. You can, however, use the static import to allow unqualified access to static members of other classes. Where I used to have to do this:

import org.apache.commons.lang.StringUtils;
      .
      .
      .
if (StringUtils.isBlank(aString)) {
      .
      .
      .

I can do this:

import static org.apache.commons.lang.StringUtils.isBlank;
      .
      .
      .
if (isBlank(aString)) {
      .
      .
      .

You can see more in the documentation.

java.net.ConnectException: Connection refused

I had same problem and the problem was that I was not closing socket object.After using socket.close(); problem solved. This code works for me.

ClientDemo.java

public class ClientDemo {
    public static void main(String[] args) throws UnknownHostException,
            IOException {
        Socket socket = new Socket("127.0.0.1", 55286);
        OutputStreamWriter os = new OutputStreamWriter(socket.getOutputStream());
        os.write("Santosh Karna");
        os.flush();
        socket.close();
    }
}

and ServerDemo.java

public class ServerDemo {
    public static void main(String[] args) throws IOException {
        System.out.println("server is started");
        ServerSocket serverSocket= new ServerSocket(55286);
        System.out.println("server is waiting");
        Socket socket=serverSocket.accept();
        System.out.println("Client connected");
        BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String str=reader.readLine();
        System.out.println("Client data: "+str);
        socket.close();
        serverSocket.close();

    }
}

Choosing the best concurrency list in Java

had better be List

The only List implementation in java.util.concurrent is CopyOnWriteArrayList. There's also the option of a synchronized list as Travis Webb mentions.

That said, are you sure you need it to be a List? There are a lot more options for concurrent Queues and Maps (and you can make Sets from Maps), and those structures tend to make the most sense for many of the types of things you want to do with a shared data structure.

For queues, you have a huge number of options and which is most appropriate depends on how you need to use it:

How can I find out the current route in Rails?

I find that the the approved answer, request.env['PATH_INFO'], works for getting the base URL, but this does not always contain the full path if you have nested routes. You can use request.env['HTTP_REFERER'] to get the full path and then see if it matches a given route:

request.env['HTTP_REFERER'].match?(my_cool_path)

Drawable image on a canvas

Drawable d = ContextCompat.getDrawable(context, R.drawable.***)
d.setBounds(left, top, right, bottom);
d.draw(canvas);

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’

In my case I substitute it with utf8_general_ci with sed like this:

sed -i 's/utf8_0900_ai_ci/utf8_general_ci/g' MY_DB.sql 
sed -i 's/utf8mb4_unicode_520_ci/utf8_general_ci/g' MY_DB.sql 

After that, I can import it without any issue.

How to read a string one letter at a time in python

# Retain a map of the Morse code
conversion = {}

# Read map from file, add it to the datastructure
morseCodeFile = file('morseCode.txt')
for line in moreCodeFile:
    conversion[line[0]] = line[2:]
morseCodeFile.close()

# Ask for input from the user
s = raw_input("Please enter string to translate")
# Go over each character, and print it the translation.
# Defensive programming: do something sane if the user 
# inputs non-Morse compatible strings.    
for c in s:
    print conversion.get(c, "No translation for "+c)

Unable to call the built in mb_internal_encoding method?

mbstring is a "non-default" extension, that is not enabled by default ; see this page of the manual :

Installation

mbstring is a non-default extension. This means it is not enabled by default. You must explicitly enable the module with the configure option. See the Install section for details

So, you might have to enable that extension, modifying the php.ini file (and restarting Apache, so your modification is taken into account)


I don't use CentOS, but you may have to install the extension first, using something like this (see this page, for instance, which seems to give a solution) :

yum install php-mbstring

(The package name might be a bit different ; so, use yum search to get it :-) )

Selenium WebDriver: Wait for complex page with JavaScript to load

Don't know how to do that but in my case, end of page load & rendering match with FAVICON displayed in Firefox tab.

So if we can get the favicon image in the webbrowser, the web page is fully loaded.

But how perform this ....

Circular gradient in android

<gradient
    android:centerColor="#c1c1c1"
    android:endColor="#4f4f4f"
    android:gradientRadius="400"
    android:startColor="#c1c1c1"
    android:type="radial" >
</gradient>

how to count length of the JSON array element

First if the object you're dealing with is a string then you need to parse it then figure out the length of the keys :

obj = JSON.parse(jsonString);
shareInfoLen = Object.keys(obj.shareInfo[0]).length;

Removing NA in dplyr pipe

I don't think desc takes an na.rm argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NAs, use na.omit (base) or tidyr::drop_na:

outcome.df %>%
  na.omit() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

library(tidyr)
outcome.df %>%
  drop_na() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

If you only want to remove NAs from the HeartAttackDeath column, filter with is.na, or use tidyr::drop_na:

outcome.df %>%
  filter(!is.na(HeartAttackDeath)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

outcome.df %>%
  drop_na(HeartAttackDeath) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

As pointed out at the dupe, complete.cases can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:

outcome.df %>%
  filter(complete.cases(.)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

How to bind 'touchstart' and 'click' events but not respond to both?

Usually this works as well:

$('#buttonId').on('touchstart click', function(e){
    e.stopPropagation(); e.preventDefault();
    //your code here

});

MySQL Alter Table Add Field Before or After a field already present

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark` 
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";

I believe you need to have ADD COLUMN and use AFTER, not BEFORE.

In case you want to place column at the beginning of a table, use the FIRST statement:

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          FIRST";

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

libxml/tree.h no such file or directory

Xcode 4.5 I have used The CW's solution entirely. The only exception is that $(SDKROOT)/usr/include/libxml2 didn't work for me, and I had to add "$(SDK_DIR)"/usr/include/libxml2 to my Projects Header Search Paths and User Header Search Paths. After that project builds successfully.

EDIT: I have Google GData project inside my project (called MyProject) (my project uses). GData requires libxml. To build project MyProject successfully, I add "$(SDK_DIR)"/usr/include/libxml2 to Header Search Paths of MyProject and no to Header Search Paths of GData . If I didnt add it to MyProject, project did not build).

How to execute a bash command stored as a string with quotes and asterisk

You don't need the "eval" even. Just put a dollar sign in front of the string:

cmd="ls"
$cmd

jQuery - select the associated label element of a input field

You shouldn't rely on the order of elements by using prev or next. Just use the for attribute of the label, as it should correspond to the ID of the element you're currently manipulating:

var label = $("label[for='" + $(this).attr('id') + "']");

However, there are some cases where the label will not have for set, in which case the label will be the parent of its associated control. To find it in both cases, you can use a variation of the following:

var label = $('label[for="' + $(this).attr('id') + '"]');

if(label.length <= 0) {
    var parentElem = $(this).parent(),
        parentTagName = parentElem.get(0).tagName.toLowerCase();

    if(parentTagName == "label") {
        label = parentElem;
    }
}

I hope this helps!

How to detect when a UIScrollView has finished scrolling

To recap (and for newbies). It's not that painful. Just add the protocol, then add the functions you need for detection.

In the view (class) that contains the UIScrolView, add the protocol, then added any the functions from here to your view (class).

// --------------------------------
// In the "h" file:
// --------------------------------
@interface myViewClass : UIViewController  <UIScrollViewDelegate> // <-- Adding the protocol here

// Scroll view
@property (nonatomic, retain) UIScrollView *myScrollView;
@property (nonatomic, assign) BOOL isScrolling;

// Protocol functions
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView;
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView;


// --------------------------------
// In the "m" file:
// --------------------------------
@implementation BlockerViewController

- (void)viewDidLoad {
    CGRect scrollRect = self.view.frame; // Same size as this view
    self.myScrollView = [[UIScrollView alloc] initWithFrame:scrollRect];
    self.myScrollView.delegate = self;
    self.myScrollView.contentSize = CGSizeMake(scrollRect.size.width, scrollRect.size.height);
    self.myScrollView.contentInset = UIEdgeInsetsMake(0.0,22.0,0.0,22.0);
    // Allow dragging button to display outside the boundaries
    self.myScrollView.clipsToBounds = NO;
    // Prevent buttons from activating scroller:
    self.myScrollView.canCancelContentTouches = NO;
    self.myScrollView.delaysContentTouches = NO;
    [self.myScrollView setBackgroundColor:[UIColor darkGrayColor]];
    [self.view addSubview:self.myScrollView];

    // Add stuff to scrollview
    UIImage *myImage = [UIImage imageNamed:@"foo.png"];
    [self.myScrollView addSubview:myImage];
}

// Protocol functions
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    NSLog(@"start drag");
    _isScrolling = YES;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSLog(@"end decel");
    _isScrolling = NO;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    NSLog(@"end dragging");
    if (!decelerate) {
       _isScrolling = NO;
    }
}

// All of the available functions are here:
// https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIScrollViewDelegate_Protocol/Reference/UIScrollViewDelegate.html

check / uncheck checkbox using jquery?

You can set the state of the checkbox based on the value:

$('#your-checkbox').prop('checked', value == 1);

How to embed a YouTube channel into a webpage

In order to embed your channel, all you need to do is copy then paste the following code in another web-page.

<script src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/youtube.xml&up_channel=YourChannelName&synd=open&w=320&h=390&title=&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>

Make sure to replace the YourChannelName with your actual channel name.

For example: if your channel name were CaliChick94066 your channel embed code would be:

<script src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/youtube.xml&up_channel=CaliChick94066&synd=open&w=320&h=390&title=&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>

Please look at the following links:

YouTube on your site

Embed YouTube Channel

You just have to name the URL to your channel name. Also you can play with the height and the border color and size. Hope it helps

How can I split a string into segments of n characters?

function chunk(er){
return er.match(/.{1,75}/g).join('\n');
}

Above function is what I use for Base64 chunking. It will create a line break ever 75 characters.

jQuery vs. javascript?

Jquery VS javascript, I am completely against the OP in this question. Comparison happens with two similar things, not in such case.

Jquery is Javascript. A javascript library to reduce vague coding, collection commonly used javascript functions which has proven to help in efficient and fast coding.

Javascript is the source, the actual scripts that browser responds to.

How do I set bold and italic on UILabel of iPhone/iPad?

Example Bold text:

UILabel *titleBold = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 30)];
UIFont* myBoldFont = [UIFont boldSystemFontOfSize:[UIFont systemFontSize]];
[titleBold setFont:myBoldFont];

Example Italic text:

UILabel *subTitleItalic = [[UILabel alloc] initWithFrame:CGRectMake(10, 35, 200, 30)];
UIFont* myItalicFont = [UIFont italicSystemFontOfSize:[UIFont systemFontSize]];
[subTitleItalic setFont:myItalicFont];

mysql update query with sub query

Thanks, I didn't have the idea of an UPDATE with INNER JOIN.

In the original query, the mistake was to name the subquery, which must return a value and can't therefore be aliased.

UPDATE Competition
SET Competition.NumberOfTeams =
(SELECT count(*) -- no column alias
  FROM PicksPoints
  WHERE UserCompetitionID is not NULL
  -- put the join condition INSIDE the subquery :
  AND CompetitionID =  Competition.CompetitionID
  group by CompetitionID
) -- no table alias

should do the trick for every record of Competition.

To be noticed :

The effect is NOT EXACTLY the same as the query proposed by mellamokb, which won't update Competition records with no corresponding PickPoints.

Since SELECT id, COUNT(*) GROUP BY id will only count for existing values of ids,

whereas a SELECT COUNT(*) will always return a value, being 0 if no records are selected.

This may, or may not, be a problem for you.

0-aware version of mellamokb query would be :

Update Competition as C
LEFT join (
  select CompetitionId, count(*) as NumberOfTeams
  from PicksPoints as p
  where UserCompetitionID is not NULL
  group by CompetitionID
) as A on C.CompetitionID = A.CompetitionID
set C.NumberOfTeams = IFNULL(A.NumberOfTeams, 0)

In other words, if no corresponding PickPoints are found, set Competition.NumberOfTeams to zero.

getaddrinfo: nodename nor servname provided, or not known

I fixed this problem simply by closing and reopening the Terminal.

Installing Java 7 (Oracle) in Debian via apt-get

Managed to get answer after do some google..

echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer

How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?

Since people seem to keep running into this thread (comment date ranges from 1.5 year) isn't this much simpler:

SELECT * FROM (SELECT * FROM topten ORDER BY datetime DESC) tmp GROUP BY home

No aggregation functions needed...

Cheers.

Reverse Contents in Array

void reverse(int [], int);
void printarray(int [], int );
int main ()
{
    const int SIZE = 10;
    int arr [SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    cout<<"Before reverse\n";
    printarray(arr, SIZE);
    reverse(arr, SIZE);
    cout<<"After reverse\n";
    printarray(arr, SIZE);

    return 0;
}

void printarray(int arr[], int count)
{
    for(int i = 0; i < count; ++i)
        cout<<arr[i]<<' ';

    cout<<'\n';
}

void reverse(int arr[], int count)
{
   int temp;
   for (int i = 0; i < count/2; ++i)
   {
      temp = arr[i];
      arr[i] = arr[count-i-1];
      arr[count-i-1] = temp;
   }
}

SQL SELECT multi-columns INTO multi-variable

SELECT @var = col1,
       @var2 = col2
FROM   Table

Here is some interesting information about SET / SELECT

  • SET is the ANSI standard for variable assignment, SELECT is not.
  • SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  • If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  • When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it's previous value)
  • As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

Disable dragging an image from an HTML page

This code does exactly what you want. It prevents the image from dragging while allowing any other actions that depend on the event.

$("img").mousedown(function(e){
    e.preventDefault()
});

How to write "not in ()" sql query using join

I would opt for NOT EXISTS in this case.

SELECT D1.ShortCode
FROM Domain1 D1
WHERE NOT EXISTS
    (SELECT 'X'
     FROM Domain2 D2
     WHERE D2.ShortCode = D1.ShortCode
    )

Query an XDocument for elements by name at any depth

We know the above is true. Jon is never wrong; real life wishes can go a little further.

<ota:OTA_AirAvailRQ
    xmlns:ota="http://www.opentravel.org/OTA/2003/05" EchoToken="740" Target=" Test" TimeStamp="2012-07-19T14:42:55.198Z" Version="1.1">
    <ota:OriginDestinationInformation>
        <ota:DepartureDateTime>2012-07-20T00:00:00Z</ota:DepartureDateTime>
    </ota:OriginDestinationInformation>
</ota:OTA_AirAvailRQ>

For example, usually the problem is, how can we get EchoToken in the above XML document? Or how to blur the element with the name attribute.

  1. You can find them by accessing with the namespace and the name like below

     doc.Descendants().Where(p => p.Name.LocalName == "OTA_AirAvailRQ").Attributes("EchoToken").FirstOrDefault().Value
    
  2. You can find it by the attribute content value, like this one.

How to format background color using twitter bootstrap?

Move your row before <div class="container marketing"> and wrap it with a new container, because current container width is 1170px (not 100%):

<div class='hero'>
  <div class="row">
   ...
  </div>
</div>

CSS:

.hero {
  background-color: #2ba6cb;
  padding: 0 90px;
}

MySQL "Or" Condition

Use brackets to group the OR statements.

mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND (date='$Date_Today' OR date='$Date_Yesterday' OR date='$Date_TwoDaysAgo' OR date='$Date_ThreeDaysAgo' OR date='$Date_FourDaysAgo' OR date='$Date_FiveDaysAgo' OR date='$Date_SixDaysAgo' OR date='$Date_SevenDaysAgo')");

You can also use IN

mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND date IN ('$Date_Today','$Date_Yesterday','$Date_TwoDaysAgo','$Date_ThreeDaysAgo','$Date_FourDaysAgo','$Date_FiveDaysAgo','$Date_SixDaysAgo','$Date_SevenDaysAgo')");

How do files get into the External Dependencies in Visual Studio C++?

To resolve external dependencies within project. below things are important..
1. The compiler should know that where are header '.h' files located in workspace.
2. The linker able to find all specified  all '.lib' files & there names for current project.

So, Developer has to specify external dependencies for Project as below..

1. Select Project in Solution explorer.

2 . Project Properties -> Configuration Properties -> C/C++ -> General
specify all header files in "Additional Include Directories".

3.  Project Properties -> Configuration Properties -> Linker -> General
specify relative path for all lib files in "Additional Library Directories".

enter image description here enter image description here

How can I change the font-size of a select option?

We need a trick here...

Normal select-dropdown things won't accept styles. BUT. If there's a "size" parameter in the tag, almost any CSS will apply. With this in mind, I've created a fiddle that's practically equivalent to a normal select tag, plus the value can be edited manually like a ComboBox in visual languages (unless you put readonly in the input tag).

A simplified example:

<style>

    /* only these 2 lines are truly required */
    .stylish span {position:relative;}
    .stylish select {position:absolute;left:0px;display:none}

    /* now you can style the hell out of them */
    .stylish input    { ... }
    .stylish select   { ... }
    .stylish option   { ... }
    .stylish optgroup { ... }

</style>
...
<div class="stylish">
    <label> Choose your superhero: </label>
    <span>
        <input onclick="$(this).closest('div').find('select').slideToggle(110)">
        <br>
        <select size=15 onclick="$(this).hide().closest('div').find('input').val($(this).find('option:selected').text());">

            <optgroup label="Fantasy"></optgroup>
            <option value="gandalf">Gandalf</option>
            <option value="harry">Harry Potter</option>
            <option value="jon">Jon Snow</option>

            <optgroup label="Comics"></optgroup>
            <option value="tony">Tony Stark</option>
            <option value="steve">Steven Rogers</option>
            <option value="natasha">Natasha Romanova</option>

        </select>
    </span>
    <!--

        For the sake of simplicity, I used jQuery here.
        Today it's easy to do the same without it, now
        that we have querySelector(), closest(), etc.

    -->
</div>

A live example:

https://jsfiddle.net/7ac9us70/1052/

Note 1: Sorry for the gradients & all fancy stuff, no they're not necessary, yes I'm showing off, I know, hashtag onlyhuman, hashtag notproud.

Note 2: Those <optgroup> tags don't encapsulate the options belonging under them as they normally should; this is intentional. It's better for the styling (the well-mannered way would be a lot less stylable), and yes this is painless and works in every browser.

JavaScript, get date of the next day

Copy-pasted from here: Incrementing a date in JavaScript

Three options for you:

Using just JavaScript's Date object (no libraries):

var today = new Date();
var tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000));

Or if you don't mind changing the date in place (rather than creating a new date):

var dt = new Date();
dt.setTime(dt.getTime() + (24 * 60 * 60 * 1000));

Edit: See also Jigar's answer and David's comment below: var tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1);

Using MomentJS:

var today = moment();
var tomorrow = moment(today).add(1, 'days');

(Beware that add modifies the instance you call it on, rather than returning a new instance, so today.add(1, 'days') would modify today. That's why we start with a cloning op on var tomorrow = ....)

Using DateJS, but it hasn't been updated in a long time:

var today = new Date(); // Or Date.today()
var tomorrow = today.add(1).day();

Finding first and last index of some value in a list in Python

Sequences have a method index(value) which returns index of first occurrence - in your case this would be verts.index(value).

You can run it on verts[::-1] to find out the last index. Here, this would be len(verts) - 1 - verts[::-1].index(value)

Autocompletion of @author in Intellij

For Intellij IDEA Community 2019.1 you will need to follow these steps :

File -> New -> Edit File Templates.. -> Class -> /* Created by ${USER} on ${DATE} */

Is it not possible to define multiple constructors in Python?

For the example you gave, use default values:

class City:
    def __init__(self, name="Default City Name"):
        ...
    ...

In general, you have two options:

1) Do if-elif blocks based on the type:

def __init__(self, name):
    if isinstance(name, str):
        ...
    elif isinstance(name, City):
        ...
    ...

2) Use duck typing --- that is, assume the user of your class is intelligent enough to use it correctly. This is typically the preferred option.

Convert Python program to C/C++ code?

Yes. Look at Cython. It does just that: Converts Python to C for speedups.

Tkinter: "Python may not be configured for Tk"

To anyone using Windows and Windows Subsystem for Linux, make sure that when you run the python command from the command line, it's not accidentally running the python installation from WSL! This gave me quite a headache just now. A quick check you can do for this is just
which <python command you're using>
If that prints something like /usr/bin/python2 even though you're in powershell, that's probably what's going on.

AttributeError: 'dict' object has no attribute 'predictors'

#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29

Making TextView scrollable on Android

I struggled with this for over a week and finally figured out how to make this work!

My issue was that everything would scroll as a 'block'. The text itself was scrolling, but as a chunk rather than line by line. This obviously didn't work for me, because it would cut off lines at the bottom. All of the previous solutions did not work for me, so I crafted my own.

Here is the easiest solution by far:

Make a class file called: 'PerfectScrollableTextView' inside a package, then copy and paste this code in:

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.TextView;

public class PerfectScrollableTextView extends TextView {

    public PerfectScrollableTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setVerticalScrollBarEnabled(true);
        setHorizontallyScrolling(false);
    }

    public PerfectScrollableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setVerticalScrollBarEnabled(true);
        setHorizontallyScrolling(false);
    }

    public PerfectScrollableTextView(Context context) {
        super(context);
        setVerticalScrollBarEnabled(true);
        setHorizontallyScrolling(false);
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        if(focused)
            super.onFocusChanged(focused, direction, previouslyFocusedRect);
    }

    @Override
    public void onWindowFocusChanged(boolean focused) {
        if(focused)
            super.onWindowFocusChanged(focused);
    }

    @Override
    public boolean isFocused() {
        return true;
    }
}

Finally change your 'TextView' in XML:

From: <TextView

To: <com.your_app_goes_here.PerfectScrollableTextView

Angular2 http.get() ,map(), subscribe() and observable pattern - basic understanding

import { HttpClientModule } from '@angular/common/http';

The HttpClient API was introduced in the version 4.3.0. It is an evolution of the existing HTTP API and has it's own package @angular/common/http. One of the most notable changes is that now the response object is a JSON by default, so there's no need to parse it with map method anymore .Straight away we can use like below

http.get('friends.json').subscribe(result => this.result =result);

CSS display:table-row does not expand when width is set to 100%

Tested answer:

In the .view-row css, change:

display:table-row;

to:

display:table

and get rid of "float". Everything will work as expected.

As it has been suggested in the comments, there is no need for a wrapping table. CSS allows for omitting levels of the tree structure (in this case rows) that are implicit. The reason your code doesn't work is that "width" can only be interpreted at the table level, not at the table-row level. When you have a "table" and then "table-cell"s directly underneath, they're implicitly interpreted as sitting in a row.

Working example:

<div class="view">
    <div>Type</div>
    <div>Name</div>                
</div>

with css:

.view {
  width:100%;
  display:table;
}

.view > div {
  width:50%;
  display: table-cell;
}

React Native Change Default iOS Simulator Device

Specify a simulator using the --simulator flag.

These are the available devices for iOS 14.0 onwards:

npx react-native run-ios --simulator="iPhone 8"
npx react-native run-ios --simulator="iPhone 8 Plus"
npx react-native run-ios --simulator="iPhone 11"
npx react-native run-ios --simulator="iPhone 11 Pro"
npx react-native run-ios --simulator="iPhone 11 Pro Max"
npx react-native run-ios --simulator="iPhone SE (2nd generation)"
npx react-native run-ios --simulator="iPhone 12 mini"
npx react-native run-ios --simulator="iPhone 12"
npx react-native run-ios --simulator="iPhone 12 Pro"
npx react-native run-ios --simulator="iPhone 12 Pro Max"
npx react-native run-ios --simulator="iPod touch (7th generation)"
npx react-native run-ios --simulator="iPad Pro (9.7-inch)"
npx react-native run-ios --simulator="iPad Pro (11-inch) (2nd generation)"
npx react-native run-ios --simulator="iPad Pro (12.9-inch) (4th generation)"
npx react-native run-ios --simulator="iPad (8th generation)"
npx react-native run-ios --simulator="iPad Air (4th generation)"

List all available iOS devices:

xcrun simctl list devices

There is currently no way to set a default.

React Native Docs: Running On Simulator

Javascript to open popup window and disable parent window

The key term is modal-dialog.

As such there is no built in modal-dialog offered.

But you can use many others available e.g. this

What does auto do in margin:0 auto?

margin:0 auto;

0 is for top-bottom and auto for left-right. It means that left and right margin will take auto margin according to the width of the element and the width of the container.

Generally if you want to put any element at center position then margin:auto works perfectly. But it only works in block elements.

What is "String args[]"? parameter in main method Java

The following answer is based my understanding & some test.

What is String[] args?

Ans- >

String[] -> As We know this is a simple String array.

args -> is the name of an array it can be anything (e.g. a, ar, argument, param, parameter) no issues with compiler & executed & I tested as well.

E.g.
1)public static void main(String[] argument)

2)public static void main(String[] parameter)

When would you use these args?

Ans->

The main function is designed very intelligently by developers. Actual thinking is very deep. Which is basically developed under consideration of C & C++ based on Command line argument but nowadays nobody uses it more.

Thing 1- User can enter any type of data from the command line can be Number or String & necessary to accept it by the compiler which datatype we should have to use? see the thing 2

Thing 2- String is the datatype which supports all of the primitive datatypes like int, long, float, double, byte, shot, char in Java. You can easily parse it in any primitive datatype.

E.g The following program is compiled & executed & I tested as well.

If input is -> 1 1

// one class needs to have a main() method
public class HelloWorld
{
  // arguments are passed using the text field below this editor
  public static void main(String[] parameter)
  {    
System.out.println(parameter[0] + parameter[1]); // Output is 11

//Comment out below code in case of String
    System.out.println(Integer.parseInt(parameter[0]) + Integer.parseInt(parameter[1])); //Output is 2
    System.out.println(Float.parseFloat(parameter[0]) + Float.parseFloat(parameter[1])); //Output is 2.0    
    System.out.println(Long.parseLong(parameter[0]) + Long.parseLong(parameter[1])); //Output is 2    
    System.out.println(Double.parseDouble(parameter[0]) + Double.parseDouble(parameter[1])); //Output is 2.0    

  }
}

OS X: equivalent of Linux's wget

Here's the Mac OS X equivalent of Linux's wget.

For Linux, for instance Ubuntu on an AWS instance, use:

wget http://example.com/textfile.txt

On a Mac, i.e. for local development, use this:

curl http://example.com/textfile.txt -o textfile.txt

The -o parameter is required on a Mac for output into a file instead of on screen. Specify a different target name for renaming the downloaded file.

Use capital -O for renaming with wget. Lowercase -o will specify output file for transfer log.

Compiling C++11 with g++

If you want to keep the GNU compiler extensions, use -std=gnu++0x rather than -std=c++0x. Here's a quote from the man page:

The compiler can accept several base standards, such as c89 or c++98, and GNU dialects of those standards, such as gnu89 or gnu++98. By specifying a base standard, the compiler will accept all programs following that standard and those using GNU extensions that do not contradict it. For example, -std=c89 turns off certain features of GCC that are incompatible with ISO C90, such as the "asm" and "typeof" keywords, but not other GNU extensions that do not have a meaning in ISO C90, such as omitting the middle term of a "?:" expression. On the other hand, by specifying a GNU dialect of a standard, all features the compiler support are enabled, even when those features change the meaning of the base standard and some strict-conforming programs may be rejected. The particular standard is used by -pedantic to identify which features are GNU extensions given that version of the standard. For example-std=gnu89 -pedantic would warn about C++ style // comments, while -std=gnu99 -pedantic would not.

How to create a GUID / UUID

UUIDs (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDentifier), according to RFC 4122, are identifiers designed to provide certain uniqueness guarantees.

While it is possible to implement RFC-compliant UUIDs in a few lines of JavaScript code (e.g., see @broofa's answer, below) there are several common pitfalls:

  • Invalid id format (UUIDs must be of the form "xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx", where x is one of [0-9, a-f] M is one of [1-5], and N is [8, 9, a, or b]
  • Use of a low-quality source of randomness (such as Math.random)

Thus, developers writing code for production environments are encouraged to use a rigorous, well-maintained implementation such as the uuid module.

What is the proper way to check and uncheck a checkbox in HTML5?

According to HTML5 drafts, the checked attribute is a “boolean attribute”, and “The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.” It is the name of the attribute that matters, and suffices. Thus, to make a checkbox initially checked, you use

<input type=checkbox checked>

By default, in the absence of the checked attribute, a checkbox is initially unchecked:

<input type=checkbox>

Keeping things this way keeps them simple, but if you need to conform to XML syntax (i.e. to use HTML5 in XHTML linearization), you cannot use an attribute name alone. Then the allowed (as per HTML5 drafts) values are the empty string and the string checked, case insensitively. Example:

<input type="checkbox" checked="checked" />

converting list to json format - quick and easy way

I prefer using linq-to-json feature of JSON.NET framework. Here's how you can serialize a list of your objects to json.

List<MyObject> list = new List<MyObject>();

Func<MyObject, JObject> objToJson =
    o => new JObject(
            new JProperty("ObjectId", o.ObjectId), 
            new JProperty("ObjectString", o.ObjectString));

string result = new JObject(new JArray(list.Select(objToJson))).ToString();

You fully control what will be in the result json string and you clearly see it just looking at the code. Surely, you can get rid of Func<T1, T2> declaration and specify this code directly in the new JArray() invocation but with this code extracted to Func<> it looks much more clearer what is going on and how you actually transform your object to json. You can even store your Func<> outside this method in some sort of setup method (i.e. in constructor).

How to Maximize a firefox browser window using Selenium WebDriver with node.js

Call window as a function.

driver.manage().window().maximize();

How to perform case-insensitive sorting in JavaScript?

In support of the accepted answer I would like to add that the function below seems to change the values in the original array to be sorted so that not only will it sort lower case but upper case values will also be changed to lower case. This is a problem for me because even though I wish to see Mary next to mary, I do not wish that the case of the first value Mary be changed to lower case.

myArray.sort(
  function(a, b) {
    if (a.toLowerCase() < b.toLowerCase()) return -1;
    if (a.toLowerCase() > b.toLowerCase()) return 1;
    return 0;
  }
);

In my experiments, the following function from the accepted answer sorts correctly but does not change the values.

["Foo", "bar"].sort(function (a, b) {
    return a.toLowerCase().localeCompare(b.toLowerCase());
});

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

GCC -fPIC option

Code that is built into shared libraries should normally be position-independent code, so that the shared library can readily be loaded at (more or less) any address in memory. The -fPIC option ensures that GCC produces such code.

Update value of a nested dictionary of varying depth

@Alex's answer is good, but doesn't work when replacing an element such as an integer with a dictionary, such as update({'foo':0},{'foo':{'bar':1}}). This update addresses it:

import collections
def update(d, u):
    for k, v in u.iteritems():
        if isinstance(d, collections.Mapping):
            if isinstance(v, collections.Mapping):
                r = update(d.get(k, {}), v)
                d[k] = r
            else:
                d[k] = u[k]
        else:
            d = {k: u[k]}
    return d

update({'k1': 1}, {'k1': {'k2': {'k3': 3}}})

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

Try ISDATE() function in SQL Server. If 1, select valid date. If 0 selects invalid dates.

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail 
WHERE ISDATE(LoginTime) = 1

EDIT :

As per your update i need to extract the date only and remove the time, then you could simply use the inner CONVERT

SELECT CONVERT(VARCHAR, LoginTime, 101) FROM AuditTrail 

or

SELECT LEFT(LoginTime,10) FROM AuditTrail

EDIT 2 :

The major reason for the error will be in your date in WHERE clause.ie,

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <= 
CAST('06/18/2012' AS DATE)

will be different from

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <= 
CAST('18/06/2012' AS DATE)

CONCLUSION

In EDIT 2 the first query tries to filter in mm/dd/yyyy format, while the second query tries to filter in dd/mm/yyyy format. Either of them will fail and throws error

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

So please make sure to filter date either with mm/dd/yyyy or with dd/mm/yyyy format, whichever works in your db.

How to horizontally align ul to center of div?

Make the left and right margins of your UL auto and assign it a width:

#headermenu ul {
    margin: 0 auto;
    width: 620px;
}

Edit: As kleinfreund has suggested, you can also center align the container and give the ul an inline-block display, but you then also have to give the LIs either a left float or an inline display.

#headermenu { 
    text-align: center;
}
#headermenu ul { 
    display: inline-block;
}
#headermenu ul li {
    float: left; /* or display: inline; */
}

How to crop an image using C#?

You can use Graphics.DrawImage to draw a cropped image onto the graphics object from a bitmap.

Rectangle cropRect = new Rectangle(...);
Bitmap src = Image.FromFile(fileName) as Bitmap;
Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);

using(Graphics g = Graphics.FromImage(target))
{
   g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height), 
                    cropRect,                        
                    GraphicsUnit.Pixel);
}

syntax for creating a dictionary into another dictionary in python

Do you want to insert one dictionary into the other, as one of its elements, or do you want to reference the values of one dictionary from the keys of another?

Previous answers have already covered the first case, where you are creating a dictionary within another dictionary.

To re-reference the values of one dictionary into another, you can use dict.update:

>>> d1 = {1: [1]}
>>> d2 = {2: [2]}
>>> d1.update(d2)
>>> d1
{1: [1], 2: [2]}

A change to a value that's present in both dictionaries will be visible in both:

>>> d1[2].append('appended')
>>> d1
{1: [1], 2: [2, 'appended']}
>>> d2
{2: [2, 'appended']}

This is the same as copying the value over or making a new dictionary with it, i.e.

>>> d3 = {1: d1[1]}
>>> d3[1].append('appended from d3')
>>> d1[1]
[1, 'appended from d3']

How to convert hashmap to JSON object in Java

I'm using Alibaba fastjson, easy and simple:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>VERSION_CODE</version>
</dependency>

and import:

import com.alibaba.fastjson.JSON;

Then:

String text = JSON.toJSONString(obj); // serialize
VO vo = JSON.parseObject("{...}", VO.class); //unserialize

Everything is ok.

How to select an item in a ListView programmatically?

Most likely, the item is being selected, you just can't tell because a different control has the focus. There are a couple of different ways that you can solve this, depending on the design of your application.

  1. The simple solution is to set the focus to the ListView first whenever your form is displayed. The user typically sets focus to controls by clicking on them. However, you can also specify which controls gets the focus programmatically. One way of doing this is by setting the tab index of the control to 0 (the lowest value indicates the control that will have the initial focus). A second possibility is to use the following line of code in your form's Load event, or immediately after you set the Selected property:

    myListView.Select();
    

    The problem with this solution is that the selected item will no longer appear highlighted when the user sets focus to a different control on your form (such as a textbox or a button).

  2. To fix that, you will need to set the HideSelection property of the ListView control to False. That will cause the selected item to remain highlighted, even when the control loses the focus.

    When the control has the focus, the selected item's background will be painted with the system highlight color. When the control does not have the focus, the selected item's background will be painted in the system color used for grayed (or disabled) text.

    You can set this property either at design time, or through code:

    myListView.HideSelection = false;
    

What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

The short answer: there is no difference.

The long answer: CHARACTER VARYING is the official type name from the ANSI SQL standard, which all compliant databases are required to support. VARCHAR is a shorter alias which all modern databases also support. I prefer VARCHAR because it's shorter and because the longer name feels pedantic. However, postgres tools like pg_dump and \d will output character varying.

How to upload files to server using JSP/Servlet?

you can upload file using jsp /servlet.

<form action="UploadFileServlet" method="post">
  <input type="text" name="description" />
  <input type="file" name="file" />
  <input type="submit" />
</form>

on the other hand server side. use following code.

     package com.abc..servlet;

import java.io.File;
---------
--------


/**
 * Servlet implementation class UploadFileServlet
 */
public class UploadFileServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public UploadFileServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.sendRedirect("../jsp/ErrorPage.jsp");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

            PrintWriter out = response.getWriter();
            HttpSession httpSession = request.getSession();
            String filePathUpload = (String) httpSession.getAttribute("path")!=null ? httpSession.getAttribute("path").toString() : "" ;

            String path1 =  filePathUpload;
            String filename = null;
            File path = null;
            FileItem item=null;


            boolean isMultipart = ServletFileUpload.isMultipartContent(request);

            if (isMultipart) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                String FieldName = "";
                try {
                    List items = upload.parseRequest(request);
                    Iterator iterator = items.iterator();
                    while (iterator.hasNext()) {
                         item = (FileItem) iterator.next();

                            if (fieldname.equals("description")) {
                                description = item.getString();
                            }
                        }
                        if (!item.isFormField()) {
                            filename = item.getName();
                            path = new File(path1 + File.separator);
                            if (!path.exists()) {
                                boolean status = path.mkdirs();
                            }
                            /* START OF CODE FRO PRIVILEDGE*/

                            File uploadedFile = new File(path + Filename);  // for copy file
                            item.write(uploadedFile);
                            }
                        } else {
                            f1 = item.getName();
                        }

                    } // END OF WHILE 
                    response.sendRedirect("welcome.jsp");
                } catch (FileUploadException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                } 
            }   
    }

}

Example to use shared_ptr?

Using a vector of shared_ptr removes the possibility of leaking memory because you forgot to walk the vector and call delete on each element. Let's walk through a slightly modified version of the example line-by-line.

typedef boost::shared_ptr<gate> gate_ptr;

Create an alias for the shared pointer type. This avoids the ugliness in the C++ language that results from typing std::vector<boost::shared_ptr<gate> > and forgetting the space between the closing greater-than signs.

    std::vector<gate_ptr> vec;

Creates an empty vector of boost::shared_ptr<gate> objects.

    gate_ptr ptr(new ANDgate);

Allocate a new ANDgate instance and store it into a shared_ptr. The reason for doing this separately is to prevent a problem that can occur if an operation throws. This isn't possible in this example. The Boost shared_ptr "Best Practices" explain why it is a best practice to allocate into a free-standing object instead of a temporary.

    vec.push_back(ptr);

This creates a new shared pointer in the vector and copies ptr into it. The reference counting in the guts of shared_ptr ensures that the allocated object inside of ptr is safely transferred into the vector.

What is not explained is that the destructor for shared_ptr<gate> ensures that the allocated memory is deleted. This is where the memory leak is avoided. The destructor for std::vector<T> ensures that the destructor for T is called for every element stored in the vector. However, the destructor for a pointer (e.g., gate*) does not delete the memory that you had allocated. That is what you are trying to avoid by using shared_ptr or ptr_vector.

How can I lookup a Java enum from its String value?

public enum EnumRole {

ROLE_ANONYMOUS_USER_ROLE ("anonymous user role"),
ROLE_INTERNAL ("internal role");

private String roleName;

public String getRoleName() {
    return roleName;
}

EnumRole(String roleName) {
    this.roleName = roleName;
}

public static final EnumRole getByValue(String value){
    return Arrays.stream(EnumRole.values()).filter(enumRole -> enumRole.roleName.equals(value)).findFirst().orElse(ROLE_ANONYMOUS_USER_ROLE);
}

public static void main(String[] args) {
    System.out.println(getByValue("internal role").roleName);
}

}

Port 443 in use by "Unable to open process" with PID 4

Below steps by sztupy worked for me

I went to Control Panel\Network and Internet\Network and Sharing Center and clicked on Change adapter settings

I clicked on Incoming Connections and right clicked on properties

The VPN click box at the bottom of the General tab was on, so I unchecked it

Under Users, I also unchecked a previous user I had allowed to copy some data weeks before

Then I clicked okay

Closed the control panel and restarted the XAMPP control panel

SLF4J: Class path contains multiple SLF4J bindings

... org.codehaus.mojo cobertura-maven-plugin 2.7 test ch.qos.logback logback-classic tools com.sun ...

## I fixed with this

... org.codehaus.mojo cobertura-maven-plugin 2.7 test ch.qos.logback logback-classic tools com.sun ...

How to use a link to call JavaScript?

And, why not unobtrusive with jQuery:

  $(function() {
    $("#unobtrusive").click(function(e) {
      e.preventDefault(); // if desired...
      // other methods to call...
    });
  });

HTML

<a id="unobtrusive" href="http://jquery.com">jquery</a>

Add x and y labels to a pandas plot

In Pandas version 1.10 and above you can use parameters xlabel and ylabel in the method plot:

df.plot(xlabel='X Label', ylabel='Y Label', title='Plot Title')

enter image description here

Cordova app not displaying correctly on iPhone X (Simulator)

Fix for iPhone X/XS screen rotation issue

On iPhone X/XS, a screen rotation will cause the header bar height to use an incorrect value, because the calculation of safe-area-inset-* was not reflecting the new values in time for UI refresh. This bug exists in UIWebView even in the latest iOS 12. A workaround is inserting a 1px top margin and then quickly reversing it, which will trigger safe-area-inset-* to be re-calculated immediately. A somewhat ugly fix but it works if you have to stay with UIWebView for one reason or another.

_x000D_
_x000D_
window.addEventListener("orientationchange", function() {_x000D_
    var originalMarginTop = document.body.style.marginTop;_x000D_
    document.body.style.marginTop = "1px";_x000D_
    setTimeout(function () {_x000D_
        document.body.style.marginTop = originalMarginTop;_x000D_
    }, 100);_x000D_
}, false);
_x000D_
_x000D_
_x000D_

The purpose of the code is to cause the document.body.style.marginTop to change slightly and then reverse it. It doesn't necessarily have to be "1px". You can pick a value that doesn't cause your UI to flicker but achieves its purpose.

PreparedStatement setNull(..)

but watch out for this....

Long nullLong = null;

preparedStatement.setLong( nullLong );

-thows null pointer exception-

because the protype is

setLong( long )   

NOT

setLong( Long )

nice one to catch you out eh.

Terminating a Java Program

Calling System.exit(0) (or any other value for that matter) causes the Java virtual machine to exit, terminating the current process. The parameter you pass will be the return value that the java process will return to the operating system. You can make this call from anywhere in your program - and the result will always be the same - JVM terminates. As this is simply calling a static method in System class, the compiler does not know what it will do - and hence does not complain about unreachable code.

return statement simply aborts execution of the current method. It literally means return the control to the calling method. If the method is declared as void (as in your example), then you do not need to specify a value, as you'd need to return void. If the method is declared to return a particular type, then you must specify the value to return - and this value must be of the specified type.

return would cause the program to exit only if it's inside the main method of the main class being execute. If you try to put code after it, the compiler will complain about unreachable code, for example:

public static void main(String... str) {
    System.out.println(1);
    return;
    System.out.println(2);
    System.exit(0);
}

will not compile with most compiler - producing unreachable code error pointing to the second System.out.println call.

ReactJS - Add custom event listener to component

I recommend using React.createRef() and ref=this.elementRef to get the DOM element reference instead of ReactDOM.findDOMNode(this). This way you can get the reference to the DOM element as an instance variable.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class MenuItem extends Component {

  constructor(props) {
    super(props);

    this.elementRef = React.createRef();
  }

  handleNVFocus = event => {
      console.log('Focused: ' + this.props.menuItem.caption.toUpperCase());
  }
    
  componentDidMount() {
    this.elementRef.addEventListener('nv-focus', this.handleNVFocus);
  }

  componentWillUnmount() {
    this.elementRef.removeEventListener('nv-focus', this.handleNVFocus);
  }

  render() {
    return (
      <element ref={this.elementRef} />
    )
  }

}

export default MenuItem;

Why SpringMVC Request method 'GET' not supported?

Change

@RequestMapping(value = "/test", method = RequestMethod.POST)

To

@RequestMapping(value = "/test", method = RequestMethod.GET)

How large is a DWORD with 32- and 64-bit code?

It is defined as:

typedef unsigned long       DWORD;

However, according to the MSDN:

On 32-bit platforms, long is synonymous with int.

Therefore, DWORD is 32bit on a 32bit operating system. There is a separate define for a 64bit DWORD:

typdef unsigned _int64 DWORD64;

Hope that helps.

How to Set Active Tab in jQuery Ui

If you want to set the active tab by ID instead of index, you can also use the following:

$('#tabs').tabs({ active: $('#tabs ul').index($('#tab-101')) });

Converting milliseconds to minutes and seconds with Javascript

Best is this!

function msToTime(duration) {
var milliseconds = parseInt((duration%1000))
    , seconds = parseInt((duration/1000)%60)
    , minutes = parseInt((duration/(1000*60))%60)
    , hours = parseInt((duration/(1000*60*60))%24);

hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;

return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}

It will return 00:04:21.223 You can format this string then as you wish.

Calling a JSON API with Node.js

The res argument in the http.get() callback is not the body, but rather an http.ClientResponse object. You need to assemble the body:

var url = 'http://graph.facebook.com/517267866/?fields=picture';

http.get(url, function(res){
    var body = '';

    res.on('data', function(chunk){
        body += chunk;
    });

    res.on('end', function(){
        var fbResponse = JSON.parse(body);
        console.log("Got a response: ", fbResponse.picture);
    });
}).on('error', function(e){
      console.log("Got an error: ", e);
});

Converting a date in MySQL from string field

SELECT STR_TO_DATE(dateString, '%d/%m/%y') FROM yourTable...

The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security

It could also be because, it might not be able to found the .dll file required. Either the file is not in the folder or is renamed. I faced the same issue and found that .dll file was missing in my bin folder some how.

TypeError: only length-1 arrays can be converted to Python scalars while plot showing

dataframe['column'].squeeze() should solve this. It basically changes the dataframe column to a list.

Getting the application's directory from a WPF application

Here is another:

System.Reflection.Assembly.GetExecutingAssembly().Location

Is there a way to make Firefox ignore invalid ssl-certificates?

Using a free certificate is a better idea if your developers use Firefox 3. Firefox 3 complains loudly about self-signed certificates, and it is a major annoyance.

How to generate a random string of a fixed length in Go?

const (
    chars       = "0123456789_abcdefghijkl-mnopqrstuvwxyz" //ABCDEFGHIJKLMNOPQRSTUVWXYZ
    charsLen    = len(chars)
    mask        = 1<<6 - 1
)

var rng = rand.NewSource(time.Now().UnixNano())

// RandStr ????????????
func RandStr(ln int) string {
    /* chars 38???
     * rng.Int63() ????64bit????,??????6bit(2^6=64) ????10?
     */
    buf := make([]byte, ln)
    for idx, cache, remain := ln-1, rng.Int63(), 10; idx >= 0; {
        if remain == 0 {
            cache, remain = rng.Int63(), 10
        }
        buf[idx] = chars[int(cache&mask)%charsLen]
        cache >>= 6
        remain--
        idx--
    }
    return *(*string)(unsafe.Pointer(&buf))
}

BenchmarkRandStr16-8 20000000 68.1 ns/op 16 B/op 1 allocs/op

Lazy Loading vs Eager Loading

I think it is good to categorize relations like this

When to use eager loading

  1. In "one side" of one-to-many relations that you sure are used every where with main entity. like User property of an Article. Category property of a Product.
  2. Generally When relations are not too much and eager loading will be good practice to reduce further queries on server.

When to use lazy loading

  1. Almost on every "collection side" of one-to-many relations. like Articles of User or Products of a Category
  2. You exactly know that you will not need a property instantly.

Note: like Transcendent said there may be disposal problem with lazy loading.

What is the use of DesiredCapabilities in Selenium WebDriver?

You should read the documentation about DesiredCapabilities. There is also a different page for the ChromeDriver. Javadoc from Capabilities:

Capabilities: Describes a series of key/value pairs that encapsulate aspects of a browser.

Basically, the DesiredCapabilities help to set properties for the WebDriver. A typical usecase would be to set the path for the FirefoxDriver if your local installation doesn't correspond to the default settings.

Refresh a page using JavaScript or HTML

Use:

window.location.reload();

Calculating frames per second in a game

Set counter to zero. Each time you draw a frame increment the counter. After each second print the counter. lather, rinse, repeat. If yo want extra credit, keep a running counter and divide by the total number of seconds for a running average.

Java AES encryption and decryption

import javax.crypto.*;    
import java.security.*;  
public class Java {

private static SecretKey key = null;         
   private static Cipher cipher = null; 

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

      Security.addProvider(new com.sun.crypto.provider.SunJCE());

      KeyGenerator keyGenerator =
         KeyGenerator.getInstance("DESede");
      keyGenerator.init(168);
      SecretKey secretKey = keyGenerator.generateKey();
      cipher = Cipher.getInstance("DESede");

      String clearText = "I am an Employee";
      byte[] clearTextBytes = clearText.getBytes("UTF8");

      cipher.init(Cipher.ENCRYPT_MODE, secretKey);
      byte[] cipherBytes = cipher.doFinal(clearTextBytes);
      String cipherText = new String(cipherBytes, "UTF8");

      cipher.init(Cipher.DECRYPT_MODE, secretKey);
      byte[] decryptedBytes = cipher.doFinal(cipherBytes);
      String decryptedText = new String(decryptedBytes, "UTF8");

      System.out.println("Before encryption: " + clearText);
      System.out.println("After encryption: " + cipherText);
      System.out.println("After decryption: " + decryptedText);
   }
}


// Output

/*
Before encryption: I am an Employee  
After encryption: }????j6??m??Zyc????*????l#l??dV  
After decryption: I am an Employee  
*/

How can I get query string values in JavaScript?

This is very simple method to get parameter value(query string)

Use gV(para_name) function to retrieve its value

var a=window.location.search;
a=a.replace(a.charAt(0),""); //Removes '?'
a=a.split("&");

function gV(x){
 for(i=0;i<a.length;i++){
  var b=a[i].substr(0,a[i].indexOf("="));
  if(x==b){
   return a[i].substr(a[i].indexOf("=")+1,a[i].length)}

parsing JSONP $http.jsonp() response in angular.js

The MOST IMPORTANT THING I didn't understand for quite awhile is that the request MUST contain "callback=JSON_CALLBACK", because AngularJS modifies the request url, substituting a unique identifier for "JSON_CALLBACK". The server response must use the value of the 'callback' parameter instead of hard coding "JSON_CALLBACK":

JSON_CALLBACK(json_response);  // wrong!

Since I was writing my own PHP server script, I thought I knew what function name it wanted and didn't need to pass "callback=JSON_CALLBACK" in the request. Big mistake!

AngularJS replaces "JSON_CALLBACK" in the request with a unique function name (like "callback=angular.callbacks._0"), and the server response must return that value:

angular.callbacks._0(json_response);

Is Laravel really this slow?

Since nobody else has mentioned it, I found that the xdebug debugger dramatically increased the time. I served a basic "Hello World, the time is 2020-01-01T01:01:01.010101" dynamic page and used this in my httpd.conf to time the request:

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" **%T/%D**" combined

%T is the serve time in seconds, %D is the time in microseconds. With this in my php.ini:

[XDebug]
xdebug.remote_autostart = 1
xdebug.remote_enable = 1

I was getting around 770ms response times, but with both of those set to 0 to disable them, it jumped to 160ms instantly. Running both of these brought it down to 120ms:

php artisan route:cache
php artisan config:cache

The downside being that if I made config or route changes, I would need to re-cache them, which is annoying.

As a sidenote, oddly, moving the site from my SSD to a spinning HDD provided no performance benefits, which is super odd to me, but I suppose it's maybe cached, I'm on Windows 10 with XAMPP.

how to programmatically fake a touch event to a UIButton?

For Xamarin iOS

btnObj.SendActionForControlEvents(UIControlEvent.TouchUpInside);

Reference

Make a borderless form movable?

There's no property you can flip to make this just happen magically. Look at the events for the form and it becomes fairly trivial to implement this by setting this.Top and this.Left. Specifically you'll want to look at MouseDown, MouseUp and MouseMove.

Printing list elements on separated lines in Python

A slightly more general solution based on join, that works even for pandas.Timestamp:

print("\n".join(map(str, my_list)))

How to check if a particular service is running on Ubuntu

Maybe what you want is the ps command;

ps -ef

will show you all processes running. Then if you have an idea of what you're looking for use grep to filter;

ps -ef | grep postgres

MySQL date format DD/MM/YYYY select query?

for my case this worked

str_to_date(date, '%e/%m/%Y' )

how to convert a string date to date format in oracle10g

You can convert a string to a DATE using the TO_DATE function, then reformat the date as another string using TO_CHAR, i.e.:

SELECT TO_CHAR(
         TO_DATE('15/August/2009,4:30 PM'
                ,'DD/Month/YYYY,HH:MI AM')
       ,'DD-MM-YYYY')
FROM DUAL;

15-08-2009

For example, if your table name is MYTABLE and the varchar2 column is MYDATESTRING:

SELECT TO_CHAR(
         TO_DATE(MYDATESTRING
                ,'DD/Month/YYYY,HH:MI AM')
       ,'DD-MM-YYYY')
FROM MYTABLE;

OnItemCLickListener not working in listview

In my case, I had to remove the next line from the Layout

android:clickable="true"

Selecting the first "n" items with jQuery

I found this note in the end of the lt() docs:

Additional Notes:
Because :lt() is a jQuery extension and not part of the CSS specification, queries using :lt() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use $("your-pure-css-selector").slice(0, index) instead.

So use $("selector").slice(from, to) for better performances.

Map HTML to JSON

Representing complex HTML documents will be difficult and full of corner cases, but I just wanted to share a couple techniques to show how to get this kind of program started. This answer differs in that it uses data abstraction and the toJSON method to recursively build the result

Below, html2json is a tiny function which takes an HTML node as input and it returns a JSON string as the result. Pay particular attention to how the code is quite flat but it's still plenty capable of building a deeply nested tree structure – all possible with virtually zero complexity

_x000D_
_x000D_
// data Elem = Elem Node_x000D_
_x000D_
const Elem = e => ({_x000D_
  toJSON : () => ({_x000D_
    tagName: _x000D_
      e.tagName,_x000D_
    textContent:_x000D_
      e.textContent,_x000D_
    attributes:_x000D_
      Array.from(e.attributes, ({name, value}) => [name, value]),_x000D_
    children:_x000D_
      Array.from(e.children, Elem)_x000D_
  })_x000D_
})_x000D_
_x000D_
// html2json :: Node -> JSONString_x000D_
const html2json = e =>_x000D_
  JSON.stringify(Elem(e), null, '  ')_x000D_
  _x000D_
console.log(html2json(document.querySelector('main')))
_x000D_
<main>_x000D_
  <h1 class="mainHeading">Some heading</h1>_x000D_
  <ul id="menu">_x000D_
    <li><a href="/a">a</a></li>_x000D_
    <li><a href="/b">b</a></li>_x000D_
    <li><a href="/c">c</a></li>_x000D_
  </ul>_x000D_
  <p>some text</p>_x000D_
</main>
_x000D_
_x000D_
_x000D_

In the previous example, the textContent gets a little butchered. To remedy this, we introduce another data constructor, TextElem. We'll have to map over the childNodes (instead of children) and choose to return the correct data type based on e.nodeType – this gets us a littler closer to what we might need

_x000D_
_x000D_
// data Elem = Elem Node | TextElem Node_x000D_
_x000D_
const TextElem = e => ({_x000D_
  toJSON: () => ({_x000D_
    type:_x000D_
      'TextElem',_x000D_
    textContent:_x000D_
      e.textContent_x000D_
  })_x000D_
})_x000D_
_x000D_
const Elem = e => ({_x000D_
  toJSON : () => ({_x000D_
    type:_x000D_
      'Elem',_x000D_
    tagName: _x000D_
      e.tagName,_x000D_
    attributes:_x000D_
      Array.from(e.attributes, ({name, value}) => [name, value]),_x000D_
    children:_x000D_
      Array.from(e.childNodes, fromNode)_x000D_
  })_x000D_
})_x000D_
_x000D_
// fromNode :: Node -> Elem_x000D_
const fromNode = e => {_x000D_
  switch (e.nodeType) {_x000D_
    case 3:  return TextElem(e)_x000D_
    default: return Elem(e)_x000D_
  }_x000D_
}_x000D_
_x000D_
// html2json :: Node -> JSONString_x000D_
const html2json = e =>_x000D_
  JSON.stringify(Elem(e), null, '  ')_x000D_
  _x000D_
console.log(html2json(document.querySelector('main')))
_x000D_
<main>_x000D_
  <h1 class="mainHeading">Some heading</h1>_x000D_
  <ul id="menu">_x000D_
    <li><a href="/a">a</a></li>_x000D_
    <li><a href="/b">b</a></li>_x000D_
    <li><a href="/c">c</a></li>_x000D_
  </ul>_x000D_
  <p>some text</p>_x000D_
</main>
_x000D_
_x000D_
_x000D_

Anyway, that's just two iterations on the problem. Of course you'll have to address corner cases where they come up, but what's nice about this approach is that it gives you a lot of flexibility to encode the HTML however you wish in JSON – and without introducing too much complexity

In my experience, you could keep iterating with this technique and achieve really good results. If this answer is interesting to anyone and would like me to expand upon anything, let me know ^_^

Related: Recursive methods using JavaScript: building your own version of JSON.stringify

How to load external webpage in WebView

Add below method in your activity class.Here browser is nothing but your webview object.

Now you can view web contain page wise easily.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && browser.canGoBack()) {
        browser.goBack();
        return true;
    }
    return false;
}

Base64 String throwing invalid character error

One gotcha to do with converting Base64 from a string is that some conversion functions use the preceding "data:image/jpg;base64," and others only accept the actual data.

Why can templates only be implemented in the header file?

It means that the most portable way to define method implementations of template classes is to define them inside the template class definition.

template < typename ... >
class MyClass
{

    int myMethod()
    {
       // Not just declaration. Add method implementation here
    }
};

"Sub or Function not defined" when trying to run a VBA script in Outlook

I had a similar situation with this issue. In this case it would have looked like this

Sub Test()
   MsqBox ("Hello world")
End Sub

The problem was, that I had a lot more code there and couldn't recognize, that there was a misspelling in "MsqBox" (q instead of g) and therefore I had an error, it was really misleading, but since you can get on this error like that, maybe someone else will notice that it was cause by a misspelling like this...

How can I use a search engine to search for special characters?

This search engine was made to solve exactly the kind of problem you're having: http://symbolhound.com/

I am the developer of SymbolHound.

Postgresql - unable to drop database because of some auto connections to DB

In my opinion there are some idle queries running in the backgroud.

  1. Try showing running queries first
SELECT pid, age(clock_timestamp(), query_start), usename, query 
FROM pg_stat_activity 
WHERE query != '<IDLE>' AND query NOT ILIKE '%pg_stat_activity%' 
ORDER BY query_start desc;
  1. kill idle query ( Check if they are referencing the database in question or you can kill all of them or kill a specific using the pid from the select results )

SELECT pg_terminate_backend(procpid);

Note: Killing a select query doesnt make any bad impact

How to check if JavaScript object is JSON

You can use Array.isArray to check for arrays. Then typeof obj == 'string', and typeof obj == 'object'.

var s = 'a string', a = [], o = {}, i = 5;
function getType(p) {
    if (Array.isArray(p)) return 'array';
    else if (typeof p == 'string') return 'string';
    else if (p != null && typeof p == 'object') return 'object';
    else return 'other';
}
console.log("'s' is " + getType(s));
console.log("'a' is " + getType(a));
console.log("'o' is " + getType(o));
console.log("'i' is " + getType(i));

's' is string
'a' is array
'o' is object
'i' is other

Entity Framework: table without primary key

Update to @CodeNotFound's answer.

In EF Core 3.0 DbQuery<T> has been deprecated, instead you should use Keyless entity types which supposedly does the same thing. These are configured with the ModelBuilder HasNoKey() method. In your DbContext class, do this

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder
        .Entity<YourEntityType>(eb =>
        {
            eb.HasNoKey();
        });

}

There are restrictions though, notably:

  • Are never tracked for changes in the DbContext and therefore are never inserted, updated or deleted on the database.
  • Only support a subset of navigation mapping capabilities, specifically:
    • They may never act as the principal end of a relationship.
    • They may not have navigations to owned entities
    • They can only contain reference navigation properties pointing to regular entities.
    • Entities cannot contain navigation properties to keyless entity types.

This means that for the question of

If I want to use them and modify data, must I necessarily add a PK to those tables, or is there a workaround so that I don't have to?

You cannot modify data this way - however you can read. One could envision using another way (e.g. ADO.NET, Dapper) to modify data though - this could be a solution in cases where you rarely need to do non-read operations and still would like to stick with EF Core for your majority cases.

Also, if you truly need/want to work with heap(keyless) tables - consider ditching EF and use another way to talk to your database.

How to sort a list of strings?

The proper way to sort strings is:

import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'), cmp=locale.strcoll) == [u'aa', u'Ab', u'ad']

# Without using locale.strcoll you get:
assert sorted((u'Ab', u'ad', u'aa')) == [u'Ab', u'aa', u'ad']

The previous example of mylist.sort(key=lambda x: x.lower()) will work fine for ASCII-only contexts.

How can I print a quotation mark in C?

#include<stdio.h>
int main(){
char ch='"';
printf("%c",ch);
return 0;
}

Output: "

PHP salt and hash SHA256 for login password

These examples are from php.net. Thanks to you, I also just learned about the new php hashing functions.

Read the php documentation to find out about the possibilities and best practices: http://www.php.net/manual/en/function.password-hash.php

Save a password hash:

$options = [
    'cost' => 11,
];
// Get the password from post
$passwordFromPost = $_POST['password'];

$hash = password_hash($passwordFromPost, PASSWORD_BCRYPT, $options);

// Now insert it (with login or whatever) into your database, use mysqli or pdo!

Get the password hash:

// Get the password from the database and compare it to a variable (for example post)
$passwordFromPost = $_POST['password'];
$hashedPasswordFromDB = ...;

if (password_verify($passwordFromPost, $hashedPasswordFromDB)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

Trigger a keypress/keydown/keyup event in JS/jQuery?

For typescript cast to KeyboardEventInit and provide the correct keyCode integer

const event = new KeyboardEvent("keydown", {
          keyCode: 38,
        } as KeyboardEventInit);

Why does Eclipse Java Package Explorer show question mark on some classes?

It sounds like you're using Subclipse; is that correct? If so, there's a great list of decorators and their descriptions at this answer by Tim Stone.

Here's the relevant snippet for your case:

Unversioned File - A file not under version control. These are typically new files that you have not committed to the repository yet.
Synchronized File - A file with no local changes.

Android Studio and android.support.v4.app.Fragment: cannot resolve symbol

Do sth. modification (just to gradle sync) over app level build.gradle and sync. Again, redo what you changed in build.gradle and sync. It should fix your problem.

Monitoring the Full Disclosure mailinglist

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

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

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

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

How to center Font Awesome icons horizontally?

i solved my problem with this:

<div class="d-flex justify-content-center"></div>

im using bootstrap with font awesome icons.

if you want to know more acess the link below: https://getbootstrap.com/docs/4.0/utilities/flex/