Programs & Examples On #Django voting

Obtaining only the filename when using OpenFileDialog property "FileName"

Use: Path.GetFileName Method

var onlyFileName = System.IO.Path.GetFileName(ofd.FileName);

How to parse a string into a nullable int

The following should work for any struct type. It is based off code by Matt Manela from MSDN forums. As Murph points out the exception handling could be expensive compared to using the Types dedicated TryParse method.

        public static bool TryParseStruct<T>(this string value, out Nullable<T> result)
            where T: struct 
        {
            if (string.IsNullOrEmpty(value))
            {
                result = new Nullable<T>();

                return true;
            }

            result = default(T);
            try
            {
                IConvertible convertibleString = (IConvertible)value;
                result = new Nullable<T>((T)convertibleString.ToType(typeof(T), System.Globalization.CultureInfo.CurrentCulture));
            }
            catch(InvalidCastException)
            {
                return false;
            }
            catch (FormatException)
            {
                return false;
            }

           return true;
        }

These were the basic test cases I used.

        string parseOne = "1";
        int? resultOne;
        bool successOne = parseOne.TryParseStruct<int>(out resultOne);
        Assert.IsTrue(successOne);
        Assert.AreEqual(1, resultOne);

        string parseEmpty = string.Empty;
        int? resultEmpty;
        bool successEmpty = parseEmpty.TryParseStruct<int>(out resultEmpty);
        Assert.IsTrue(successEmpty);
        Assert.IsFalse(resultEmpty.HasValue);

        string parseNull = null;
        int? resultNull;
        bool successNull = parseNull.TryParseStruct<int>(out resultNull);
        Assert.IsTrue(successNull);
        Assert.IsFalse(resultNull.HasValue);

        string parseInvalid = "FooBar";
        int? resultInvalid;
        bool successInvalid = parseInvalid.TryParseStruct<int>(out resultInvalid);
        Assert.IsFalse(successInvalid);

Delete specific values from column with where condition?

You don't want to delete if you're wanting to leave the row itself intact. You want to update the row, and change the column value.

The general form for this would be an UPDATE statement:

UPDATE <table name>
SET
    ColumnA = <NULL, or '', or whatever else is suitable for the new value for the column>
WHERE
    ColumnA = <bad value> /* or any other search conditions */

Adding an onclick event to a table row

Here is how I do this. I create a table with a thead and tbody tags. And then add a click event to the tbody element by id.

<script>
    document.getElementById("mytbody").click = clickfunc;
    function clickfunc(e) {
        // to find what td element has the data you are looking for
        var tdele = e.target.parentNode.children[x].innerHTML;
        // to find the row
        var trele = e.target.parentNode;
    }
</script>
<table>
    <thead>
        <tr>
            <th>Header 1</th>
            <th>Header 2</th>
        </tr>
    </thead>
    <tbody id="mytbody">
        <tr><td>Data Row</td><td>1</td></tr>
        <tr><td>Data Row</td><td>2</td></tr>
        <tr><td>Data Row</td><td>3</td></tr>
    </tbody>
</table>

Which Eclipse version should I use for an Android app?

As of 10/2011 ... classic is fine for Android development.

See Compare Eclipse Packages for a nice chart.

How to change color of ListView items on focus and on click

listview.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(final AdapterView<?> parent, View view,
                final int position, long id) {
            // TODO Auto-generated method stub

             parent.getChildAt(position).setBackgroundColor(getResources().getColor(R.color.listlongclick_selection));

            return false;
        }
    });

LEFT JOIN only first row

I've used something else (I think better...) and want to share it:

I created a VIEW that has a "group" clause

CREATE VIEW vCountries AS SELECT * PROVINCES GROUP BY country_code

SELECT * FROM client INNER JOIN vCountries on client_province = province_id

I want to say yet, that I think that we need to do this solution BECAUSE WE DID SOMETHING WRONG IN THE ANALYSIS... at least in my case... but sometimes it's cheaper to do this that to redesign everything...

I hope it helps!

Best TCP port number range for internal applications

I decided to download the assigned port numbers from IANA, filter out the used ports, and sort each "Unassigned" range in order of most ports available, descending. This did not work, since the csv file has ranges marked as "Unassigned" that overlap other port number reservations. I manually expanded the ranges of assigned port numbers, leaving me with a list of all assigned port numbers. I then sorted that list and generated my own list of unassigned ranges.

Since this stackoverflow.com page ranked very high in my search about the topic, I figured I'd post the largest ranges here for anyone else who is interested. These are for both TCP and UDP where the number of ports in the range is at least 500.

Total   Start   End
829     29170   29998
815     38866   39680
710     41798   42507
681     43442   44122
661     46337   46997
643     35358   36000
609     36866   37474
596     38204   38799
592     33657   34248
571     30261   30831
563     41231   41793
542     21011   21552
528     28590   29117
521     14415   14935
510     26490   26999

Source (via the CSV download button):

http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml

Access Tomcat Manager App from different host

Following two configuration is working for me.

1 .tomcat-users.xml details
--------------------------------
  <role rolename="manager-gui"/>
  <role rolename="manager-script"/>
  <role rolename="manager-jmx"/>
  <role rolename="manager-status"/>
  <role rolename="admin-gui"/>
  <role rolename="admin-script"/>
  <role rolename="tomcat"/>


  <user  username="tomcat"  password="tomcat" roles="tomcat"/>

  <user  username="admin"  password="admin" roles="admin-gui"/>

  <user  username="adminscript"  password="adminscrip" roles="admin-script"/>

  <user  username="tomcat"  password="s3cret" roles="manager-gui"/>
  <user  username="status"  password="status" roles="manager-status"/>

  <user  username="both"    password="both"   roles="manager-gui,manager-status"/>

  <user  username="script"  password="script" roles="manager-script"/>
  <user  username="jmx"     password="jmx"    roles="manager-jmx"/>

2. context.xml  of <tomcat>/webapps/manager/META-INF/context.xml and 
<tomcat>/webapps/host-manager/META-INF/context.xml
------------------------------------------------------------------------
<Context antiResourceLocking="false" privileged="true" >

  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow=".*" />
  <Manager sessionAttributeValueClassNameFilter="java\.lang\.(?:Boolean|Integer|Long|Number|String)|org\.apache\.catalina\.filters\.CsrfPreventionFilter\$LruCache(?:\$1)?|java\.util\.(?:Linked)?HashMap"/>

How to split a python string on new line characters

a.txt

this is line 1
this is line 2

code:

Python 3.4.0 (default, Mar 20 2014, 22:43:40) 
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']

I'm on Linux, but I guess you just use \r\n on Windows and it would also work

How do you make an element "flash" in jQuery

$('#district').css({opacity: 0});
$('#district').animate({opacity: 1}, 700 );

How to find files modified in last x minutes (find -mmin does not work as expected)

this command may be help you sir

find -type f -mtime -60

Convert list to array in Java

An alternative in Java 8:

String[] strings = list.stream().toArray(String[]::new);

Since Java 11:

String[] strings = list.toArray(String[]::new);

Using Rsync include and exclude options to include directory and file by pattern

The problem is that --exclude="*" says to exclude (for example) the 1260000000/ directory, so rsync never examines the contents of that directory, so never notices that the directory contains files that would have been matched by your --include.

I think the closest thing to what you want is this:

rsync -nrv --include="*/" --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/

(which will include all directories, and all files matching file_11*.jpg, but no other files), or maybe this:

rsync -nrv --include="/[0-9][0-9][0-9]0000000/" --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/

(same concept, but much pickier about the directories it will include).

How to hide the title bar for an Activity in XML with existing custom theme

Add

<item name="android:windowNoTitle">true</item>

inside AppTheme (styles.xml)

Getting time span between two times in C#?

Two points:

  1. Check your inputs. I can't imagine a situation where you'd get 2 hours by subtracting the time values you're talking about. If I do this:

        DateTime startTime = Convert.ToDateTime("7:00 AM");
        DateTime endtime = Convert.ToDateTime("2:00 PM");
        TimeSpan duration = startTime - endtime;
    

    ... I get -07:00:00 as the result. And even if I forget to provide the AM/PM value:

        DateTime startTime = Convert.ToDateTime("7:00");
        DateTime endtime = Convert.ToDateTime("2:00");
        TimeSpan duration = startTime - endtime;
    

    ... I get 05:00:00. So either your inputs don't contain the values you have listed or you are in a machine environment where they are begin parsed in an unexpected way. Or you're not actually getting the results you are reporting.

  2. To find the difference between a start and end time, you need to do endTime - startTime, not the other way around.

Accessing constructor of an anonymous class

In my case, a local class (with custom constructor) worked as an anonymous class:

Object a = getClass1(x);

public Class1 getClass1(int x) {
  class Class2 implements Class1 {
    void someNewMethod(){
    }
    public Class2(int a){
      super();
      System.out.println(a);
    }
  }
  Class1 c = new Class2(x);
  return c;
}

Javascript AES encryption

Judging from my own experience, asmcrypto.js provides the fastest AES implementation in JavaScript (especially in Firefox since it can fully leverage asm.js there).

From the readme:

Chrome/31.0
SHA256: 51 MiB/s (9 times faster than SJCL and CryptoJS)
AES-CBC: 47 MiB/s (13 times faster than CryptoJS and 20 times faster than SJCL)

Firefox/26.0
SHA256: 144 MiB/s (5 times faster than CryptoJS and 20 times faster than SJCL)
AES-CBC: 81 MiB/s (3 times faster than CryptoJS and 8 times faster than SJCL)

Edit: The Web Cryptography API is now implemented in most browsers and should be used as the primary solution if you care about performance. Be aware that IE11 implemented an earlier draft version of the standard which did not use promises.

Some examples can be found here:

What's wrong with overridable method calls in constructors?

I guess for Wicket it's better to call add method in the onInitialize() (see components lifecycle) :

public abstract class BasicPage extends WebPage {

    public BasicPage() {
    }

    @Override
    public void onInitialize() {
        add(new Label("title", getTitle()));
    }

    protected abstract String getTitle();
}

jQuery - Create hidden form element on the fly

function addHidden(theForm, key, value) {
    // Create a hidden input element, and append it to the form:
    var input = document.createElement('input');
    input.type = 'hidden';
    input.name = key; //name-as-seen-at-the-server
    input.value = value;
    theForm.appendChild(input);
}

// Form reference:
var theForm = document.forms['detParameterForm'];

// Add data:
addHidden(theForm, 'key-one', 'value');

How can I use the python HTMLParser library to extract data from a specific div tag?

This works perfectly:

print (soup.find('the tag').text)

vim line numbers - how to have them on by default?

Terminal > su > password > vim /etc/vimrc

Click here and edit as in line number (13):

set nu

click here and Edit as "Line number (13)"

Programmatically set TextBlock Foreground Color

To get the Color from Hex.

using System.Windows.Media;

Color color = (Color)ColorConverter.ConvertFromString("#FFDFD991");

and then set the foreground

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(color); 

Find files containing a given text

find . -type f -name '*php' -o -name '*js' -o -name '*html' |\
xargs grep -liE 'document\.cookie|setcookie'

.map() a Javascript ES6 Map?

You can map() arrays, but there is no such operation for Maps. The solution from Dr. Axel Rauschmayer:

  • Convert the map into an array of [key,value] pairs.
  • Map or filter the array.
  • Convert the result back to a map.

Example:

let map0 = new Map([
  [1, "a"],
  [2, "b"],
  [3, "c"]
]);

const map1 = new Map(
  [...map0]
  .map(([k, v]) => [k * 2, '_' + v])
);

resulted in

{2 => '_a', 4 => '_b', 6 => '_c'}

Storing integer values as constants in Enum manner in java

You can use ordinal. So PAGE.SIGN_CREATE.ordinal() returns 1.

EDIT:

The only problem with doing this is that if you add, remove or reorder the enum values you will break the system. For many this is not an issue as they will not remove enums and will only add additional values to the end. It is also no worse than integer constants which also require you not to renumber them. However it is best to use a system like:

public enum PAGE{
  SIGN_CREATE0(0), SIGN_CREATE(1) ,HOME_SCREEN(2), REGISTER_SCREEN(3)

  private int id;

  PAGE(int id){
    this.id = id;
  }

  public int getID(){
    return id;
  }

}

You can then use getID. So PAGE.SIGN_CREATE.getID() returns 1.

Animate a custom Dialog

First, you have to create two animation resources in res/anim dir

slide_up.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
    android:duration="@android:integer/config_mediumAnimTime"
    android:fromYDelta="100%"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toXDelta="0">
</translate>
</set>

slide_bottom.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate 
    android:duration="@android:integer/config_mediumAnimTime" 
    android:fromYDelta="0%p" 
    android:interpolator="@android:anim/accelerate_interpolator" 
    android:toYDelta="100%p">
</translate>
</set>

then you have to create a style

<style name="DialogAnimation">
    <item name="android:windowEnterAnimation">@anim/slide_up</item>
    <item name="android:windowExitAnimation">@anim/slide_bottom</item>
</style>

and add this line to your class

dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; //style id

Based in http://www.devexchanges.info/2015/10/showing-dialog-with-animation-in-android.html

Javascript split regex question

or just (anything but numbers):

date.split(/\D/);

Add Expires headers

try this solution and it is working fine for me

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>

<IfModule mod_headers.c>
  <FilesMatch "\.(js|css|xml|gz)$">
    Header append Vary: Accept-Encoding
  </FilesMatch>
</IfModule>

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

<IfModule mod_deflate.c>
SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml text/x-js text/js 
</IfModule>

## EXPIRES CACHING ##

List of tuples to dictionary

It seems everyone here assumes the list of tuples have one to one mapping between key and values (e.g. it does not have duplicated keys for the dictionary). As this is the first question coming up searching on this topic, I post an answer for a more general case where we have to deal with duplicates:

mylist = [(a,1),(a,2),(b,3)]    
result = {}
for i in mylist:  
   result.setdefault(i[0],[]).append(i[1])
print(result)
>>> result = {a:[1,2], b:[3]}

What is SYSNAME data type in SQL Server?

Just as an FYI....

select * from sys.types where system_type_id = 231 gives you two rows.

(i'm not sure what this means yet but i'm 100% sure it's messing up my code right now)

edit: i guess what it means is that you should join by the user_type_id in this situation (my situation) or possibly both the user_type_id and the system_type_id

name        system_type_id   user_type_id   schema_id   principal_id    max_length  precision   scale   collation_name                  is_nullable     is_user_defined     is_assembly_type    default_object_id   rule_object_id
nvarchar    231              231            4           NULL            8000        0           0       SQL_Latin1_General_CP1_CI_AS    1               0                   0                   0                   0
sysname     231              256            4           NULL            256         0           0       SQL_Latin1_General_CP1_CI_AS    0               0                   0                   0                   0

create procedure dbo.yyy_test (
    @col_one    nvarchar(max),
    @col_two    nvarchar(max)  = 'default',
    @col_three  nvarchar(1),
    @col_four   nvarchar(1)    = 'default',
    @col_five   nvarchar(128),
    @col_six    nvarchar(128)  = 'default',
    @col_seven  sysname  
)
as begin 

    select 1
end 

This query:

select  parm.name AS Parameter,    
        parm.max_length, 
        parm.parameter_id 
         
from    sys.procedures sp

        join sys.parameters parm ON sp.object_id = parm.object_id 
        
where   sp.name = 'yyy_test'

order   by parm.parameter_id

Yields:

parameter           max_length  parameter_id
@col_one            -1          1
@col_two            -1          2
@col_three           2          3
@col_four            2          4
@col_five            256        5
@col_six             256        6
@col_seven           256        7

And This:

select  parm.name as parameter,    
        parm.max_length, 
        parm.parameter_id,
        typ.name as data_type, 
        typ.system_type_id, 
        typ.user_type_id,
        typ.collation_name,
        typ.is_nullable 
from    sys.procedures sp

        join sys.parameters parm ON sp.object_id = parm.object_id
        
        join sys.types typ ON parm.system_type_id = typ.system_type_id
        
where   sp.name = 'yyy_test'

order   by parm.parameter_id

Gives You This:

parameter   max_length  parameter_id    data_type   system_type_id  user_type_id    collation_name                  is_nullable
@col_one    -1          1               nvarchar    231             231             SQL_Latin1_General_CP1_CI_AS    1
@col_one    -1          1               sysname     231             256             SQL_Latin1_General_CP1_CI_AS    0
@col_two    -1          2               nvarchar    231             231             SQL_Latin1_General_CP1_CI_AS    1
@col_two    -1          2               sysname     231             256             SQL_Latin1_General_CP1_CI_AS    0
@col_three   2          3               nvarchar    231             231             SQL_Latin1_General_CP1_CI_AS    1
@col_three   2          3               sysname     231             256             SQL_Latin1_General_CP1_CI_AS    0
@col_four    2          4               nvarchar    231             231             SQL_Latin1_General_CP1_CI_AS    1
@col_four    2          4               sysname     231             256             SQL_Latin1_General_CP1_CI_AS    0
@col_five    256        5               nvarchar    231             231             SQL_Latin1_General_CP1_CI_AS    1
@col_five    256        5               sysname     231             256             SQL_Latin1_General_CP1_CI_AS    0
@col_six     256        6               nvarchar    231             231             SQL_Latin1_General_CP1_CI_AS    1
@col_six     256        6               sysname     231             256             SQL_Latin1_General_CP1_CI_AS    0
@col_seven   256        7               nvarchar    231             231             SQL_Latin1_General_CP1_CI_AS    1
@col_seven   256        7               sysname     231             256             SQL_Latin1_General_CP1_CI_AS    0

Using a dispatch_once singleton model in Swift

The best approach in Swift above 1.2 is a one-line singleton, as -

class Shared: NSObject {

    static let sharedInstance = Shared()

    private override init() { }
}

To know more detail about this approach you can visit this link.

require(vendor/autoload.php): failed to open stream

This error occurs because of missing some files and the main reason is "Composer"

enter image description here

First Run these commands in CMD

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === 'e0012edf3e80b6978849f5eff0d4b4e4c79ff1609dd1e613307e16318854d24ae64f26d17af3ef0bf7cfb710ca74755a') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

Then Create a New project
Example:

D:/Laravel_Projects/New_Project
laravel new New_Project

After that start the server using

php artisan serve

How can I add or update a query string parameter?

This is my preference, and it covers the cases I can think of. Can anyone think of a way to reduce it to a single replace?

function setParam(uri, key, val) {
    return uri
        .replace(RegExp("([?&]"+key+"(?=[=&#]|$)[^#&]*|(?=#|$))"), "&"+key+"="+encodeURIComponent(val))
        .replace(/^([^?&]+)&/, "$1?");
}

How to set up a cron job to run an executable every hour?

use

path_to_exe >> log_file

to see the output of your command also errors can be redirected with

path_to_exe &> log_file

also you can use

crontab -l

to check if your edits were saved.

How create a new deep copy (clone) of a List<T>?

You can use this:

var newList= JsonConvert.DeserializeObject<List<Book>>(list.toJson());

POST an array from an HTML form without javascript

You can also post multiple inputs with the same name and have them save into an array by adding empty square brackets to the input name like this:

<input type="text" name="comment[]" value="comment1"/>
<input type="text" name="comment[]" value="comment2"/>
<input type="text" name="comment[]" value="comment3"/>
<input type="text" name="comment[]" value="comment4"/>

If you use php:

print_r($_POST['comment']) 

you will get this:

Array ( [0] => 'comment1' [1] => 'comment2' [2] => 'comment3' [3] => 'comment4' )

Set focus on <input> element

This is working i Angular 8 without setTimeout:

import {AfterContentChecked, Directive, ElementRef} from '@angular/core';

@Directive({
  selector: 'input[inputAutoFocus]'
})
export class InputFocusDirective implements AfterContentChecked {
  constructor(private element: ElementRef<HTMLInputElement>) {}

  ngAfterContentChecked(): void {
    this.element.nativeElement.focus();
  }
}

Explanation: Ok so this works because of: Change detection. It's the same reason that setTimout works, but when running a setTimeout in Angular it will bypass Zone.js and run all checks again, and it works because when the setTimeout is complete all changes are completed. With the correct lifecycle hook (AfterContentChecked) the same result can be be reached, but with the advantage that the extra cycle won't be run. The function will fire when all changes are checked and passed, and runs after the hooks AfterContentInit and DoCheck. If i'm wrong here please correct me.

More one lifecycles and change detection on https://angular.io/guide/lifecycle-hooks

UPDATE: I found an even better way to do this if one is using Angular Material CDK, the a11y-package. First import A11yModule in the the module declaring the component you have the input-field in. Then use cdkTrapFocus and cdkTrapFocusAutoCapture directives and use like this in html and set tabIndex on the input:

<div class="dropdown" cdkTrapFocus cdkTrapFocusAutoCapture>
    <input type="text tabIndex="0">
</div>

We had some issues with our dropdowns regarding positioning and responsiveness and started using the OverlayModule from the cdk instead, and this method using A11yModule works flawlessly.

"Automatic" vs "Automatic (Delayed start)"

In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.

Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.

Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).

The registry keys of interest (At least in some versions of windows) are:

  • HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart will have the value 1 if delayed, 0 if not.
  • HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay (on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.

What is the fastest factorial function in JavaScript?

Iterative factorial with BigInt for safety

Solution uses BigInt, an ES 2018+/2019 feature.

This is working example uses BigInt, because many answers here all escape the safe boundary of Number (MDN) almost right away. It's not the fastest but it's simple and thus clearer for adapting other optimizations (like a cache of the first 100 numbers).

function factorial(nat) {
   let p = BigInt(1)
   let i = BigInt(nat)

   while (1 < i--) p *= i

   return p
}

Example Usage

// 9.332621544394415e+157
Number(factorial(100))

// "933262154439441526816992388562667004907159682643816214685929638952175999
//  932299156089414639761565182862536979208272237582511852109168640000000000
//  00000000000000"
String(factorial(100))

// 9332621544394415268169923885626670049071596826438162146859296389521759999
// 3229915608941463976156518286253697920827223758251185210916864000000000000
// 000000000000n
factorial(100)
  • The n at the end of a numeric literal like 1303n indicates it's a BigInt type.
  • Remember that you shouldn't mix BigInt with Number unless you explicitly coerce them, and that doing so could cause a loss in accuracy.

how to fix groovy.lang.MissingMethodException: No signature of method:

This may also be because you might have given classname with all letters in lowercase something which groovy (know of version 2.5.0) does not support.

class name - User is accepted but user is not.

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

It is because it did not find sql connector. try:

pip install mysqlclient

Android Spinner : Avoid onItemSelected calls during initialization

For me, Abhi's solution works great up to Api level 27.

But it seems that from Api level 28 and upwards, onItemSelected() is not called when listener is set, which means onItemSelected() is never called.

Therefore, I added a short if-statement to check Api level:

public void onItemSelected(AdapterView<?> parent, View arg1, int pos,long id) {

            if(Build.VERSION.SDK_INT >= 28){ //onItemSelected() doesn't seem to be called when listener is set on Api 28+
                check = 1;
            }

            if(++check > 1) {
                //Do your action here
            }
        }

I think that's quite weird and I'm not sure wether others also have this problem, but in my case it worked well.

Insert a line break in mailto body

For the Single line and double line break here are the following codes.

Single break: %0D0A
Double break: %0D0A%0D0A

Get fragment (value after hash '#') from a URL in php

Getting the data after the hashmark in a query string is simple. Here is an example used for when a client accesses a glossary of terms from a book. It takes the name anchor delivered (#tesla), and delivers the client to that term and highlights the term and its description in blue so its easy to see.

A. setup your strings with a div id, so the name anchor goes where its supposed to and the javascript can change the text colors

<div id="tesla">Tesla</div>
<div id="tesla1">An energy company</div>

B. Use Javascript to do the heavy work, on the server side, inserted in your PHP page, or wherever..

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

C. I am launching the java function automatically when the page is loaded.

<script>
$( document ).ready(function() {

D. get the anchor (#tesla) from the url received by the server

var myhash1 = $(location).attr('hash'); //myhash1 == #tesla

E. trim the hash sign off of it

myhash1 = myhash1.substr(1)  //myhash1 == tesla

F. I need to highlight the term and the description so i create a new var

var myhash2 = '1';
myhash2 = myhash1.concat(myhash2); //myhash2 == tesla1

G. Now I can manipulate the text color for the term and description

var elem = document.getElementById(myhash1);
elem.style.color = 'blue';
elem = document.getElementById(myhash2);
elem.style.color = 'blue';
});
</script>

H. This works. client clicks link on client side (xyz.com#tesla) and goes right to the term. the term and the description are highlighted in blue by javascript for quick reading .. all other entries left in black..

The CSRF token is invalid. Please try to resubmit the form

I had the same error, but in my case the problem was that my application was using multiple first-level domains, while the cookie was using one. Removing cookie_domain: ".%domain%" from framework.session in the config.yml caused cookies to default to whatever domain the form was on, and that fixed the problem.

Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default

In your iOS App can't find a Numeric Keypad attached to your OS X. So you just need to Uncheck connect Hardware Keyboard option in your Simulator, in the following path just for testing purpose:

Simulator -> Hardware -> Keyboard -> Connect Hardware Keyboard

This will resolve the above issue.

I think you should see the below link too. It says it's a bug in the XCode at the end of that Forum post thread!

Reference

Blocking device rotation on mobile web pages

You could use the screenSize.width and screenSize.height properties and detect when the width > height and then handle that situation, either by letting the user know or by adjusting your screen accordingly.

But the best solution is what @Doozer1979 says... Why would you override what the user prefers?

Fatal error: Call to undefined function mysqli_connect()

So this may not be the issue for you, but I was struggling with this error. I discovered what was causing my problem, though I can't really explain as to why.

For me, mysqli_connect was working fine where the connection was made on pages in any various sub-directory. For some reason though, the same code referenced on pages in the root directory was returning this error. The strange thing is that it was working fine on my localhost environment in MAMP in the root directory, however on my shared host it was not.

After struggling to figure out what was giving me "Error 500" white screen from this "PHP Fatal Error," I went through the code and stumbled upon this code in the error handling that was suggested by the PHP Manual (https://www.php.net/manual/en/mysqli.error.php).

if (!mysqli_query($link, "SET a=1")) {
    printf("Error message: %s\n", mysqli_error($link));
}

I randomly decided to remove it and, voila, connection to the database working in root directories. Maybe someone smarter than me can explain this, for anyone struggling with a similar issue.

Install php-mcrypt on CentOS 6

yum install php-mcrypt.x86_64

worked for me instead of

yum install php-mcrypt

How do you add an action to a button programmatically in xcode

 UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self 
       action:@selector(aMethod1:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];   

How to Insert BOOL Value to MySQL Database

TRUE and FALSE are keywords, and should not be quoted as strings:

INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);

By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT in MySQL), which translates into zero for any non-numeric string. Thus, you get 0 for both values in your table.

Non-numeric strings cast to zero:

mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
|                      0 |                       0 |                   12345 |
+------------------------+-------------------------+-------------------------+

But the keywords return their corresponding INT representation:

mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
|    1 |     0 |
+------+-------+

Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id with NULL. The empty string may issue a warning.

Allowing Untrusted SSL Certificates with HttpClient

Most answers here suggest to use the typical pattern:

using (var httpClient = new HttpClient())
{
 // do something
}

because of the IDisposable interface. Please don't!

Microsoft tells you why:

And here you can find a detailed analysis whats going on behind the scenes: You're using HttpClient wrong and it is destabilizing your software

Regarding your SSL question and based on Improper Instantiation antipattern # How to fix the problem

Here is your pattern:

class HttpInterface
{
 // https://docs.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/#how-to-fix-the-problem
 // https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient#remarks
 private static readonly HttpClient client;

 // static initialize
 static HttpInterface()
 {
  // choose one of these depending on your framework
  
  // HttpClientHandler is an HttpMessageHandler with a common set of properties
  var handler = new HttpClientHandler()
  {
      ServerCertificateCustomValidationCallback = delegate { return true; },
  };
  // derives from HttpClientHandler but adds properties that generally only are available on full .NET
  var handler = new WebRequestHandler()
  {
      ServerCertificateValidationCallback = delegate { return true; },
      ServerCertificateCustomValidationCallback = delegate { return true; },
  };

  client = new HttpClient(handler);
 }
 
 .....
 
 // in your code use the static client to do your stuff
 var jsonEncoded = new StringContent(someJsonString, Encoding.UTF8, "application/json");

 // here in sync
 using (HttpResponseMessage resultMsg = client.PostAsync(someRequestUrl, jsonEncoded).Result)
 {
  using (HttpContent respContent = resultMsg.Content)
  {
   return respContent.ReadAsStringAsync().Result;
  }
 }
}

How to navigate through a vector using iterators? (C++)

Vector's iterators are random access iterators which means they look and feel like plain pointers.

You can access the nth element by adding n to the iterator returned from the container's begin() method, or you can use operator [].

std::vector<int> vec(10);
std::vector<int>::iterator it = vec.begin();

int sixth = *(it + 5);
int third = *(2 + it);
int second = it[1];

Alternatively you can use the advance function which works with all kinds of iterators. (You'd have to consider whether you really want to perform "random access" with non-random-access iterators, since that might be an expensive thing to do.)

std::vector<int> vec(10);
std::vector<int>::iterator it = vec.begin();

std::advance(it, 5);
int sixth = *it;

How to draw a line with matplotlib?

As of matplotlib 3.3, you can do this with plt.axline((x1, y1), (x2, y2)).

Insert multiple values using INSERT INTO (SQL Server 2005)

You can also use the following syntax:-

INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO

From here

How to destroy Fragment?

If you are in the fragment itself, you need to call this. Your fragment needs to be the fragment that is being called. Enter code:

getFragmentManager().beginTransaction().remove(yourFragment).commitAllowingStateLoss();

or if you are using supportLib, then you need to call:

getSupportFragmentManager().beginTransaction().remove(yourFragment).commitAllowingStateLoss();

How to convert ISO8859-15 to UTF8?

I have ubuntu 14 and the other answers where no working for me

iconv -f ISO-8859-1 -t UTF-8 in.tex > out.tex

I found this command here

Switch statement: must default be the last case?

There's no defined order in a switch statement. You may look at the cases as something like a named label, like a goto label. Contrary to what people seem to think here, in the case of value 2 the default label is not jumped to. To illustrate with a classical example, here is Duff's device, which is the poster child of the extremes of switch/case in C.

send(to, from, count)
register short *to, *from;
register count;
{
  register n=(count+7)/8;
  switch(count%8){
    case 0: do{ *to = *from++;
    case 7:     *to = *from++;
    case 6:     *to = *from++;
    case 5:     *to = *from++;
    case 4:     *to = *from++;
    case 3:     *to = *from++;
    case 2:     *to = *from++;
    case 1:     *to = *from++;
            }while(--n>0);
  }
}

Go test string contains substring

To compare, there are more options:

import (
    "fmt"
    "regexp"
    "strings"
)

const (
    str    = "something"
    substr = "some"
)

// 1. Contains
res := strings.Contains(str, substr)
fmt.Println(res) // true

// 2. Index: check the index of the first instance of substr in str, or -1 if substr is not present
i := strings.Index(str, substr)
fmt.Println(i) // 0

// 3. Split by substr and check len of the slice, or length is 1 if substr is not present
ss := strings.Split(str, substr)
fmt.Println(len(ss)) // 2

// 4. Check number of non-overlapping instances of substr in str
c := strings.Count(str, substr)
fmt.Println(c) // 1

// 5. RegExp
matched, _ := regexp.MatchString(substr, str)
fmt.Println(matched) // true

// 6. Compiled RegExp
re = regexp.MustCompile(substr)
res = re.MatchString(str)
fmt.Println(res) // true

Benchmarks: Contains internally calls Index, so the speed is almost the same (btw Go 1.11.5 showed a bit bigger difference than on Go 1.14.3).

BenchmarkStringsContains-4              100000000               10.5 ns/op             0 B/op          0 allocs/op
BenchmarkStringsIndex-4                 117090943               10.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsSplit-4                  6958126               152 ns/op              32 B/op          1 allocs/op
BenchmarkStringsCount-4                 42397729                29.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsRegExp-4                  461696              2467 ns/op            1326 B/op         16 allocs/op
BenchmarkStringsRegExpCompiled-4         7109509               168 ns/op               0 B/op          0 allocs/op

how to call url of any other website in php

Depending on what you mean, either redirect or use curl.

Set value to an entire column of a pandas dataframe

df.loc[:,'industry'] = 'yyy'

This does the magic. You are to add '.loc' with ':' for all rows. Hope it helps

Objective-C - Remove last character from string

If it's an NSMutableString (which I would recommend since you're changing it dynamically), you can use:

[myString deleteCharactersInRange:NSMakeRange([myRequestString length]-1, 1)];

How do I declare and initialize an array in Java?

An array has two basic types.

Static Array: Fixed size array (its size should be declared at the start and can not be changed later)

Dynamic Array: No size limit is considered for this. (Pure dynamic arrays do not exist in Java. Instead, List is most encouraged.)

To declare a static array of Integer, string, float, etc., use the below declaration and initialization statements.

_x000D_
_x000D_
int[] intArray = new int[10];
String[] intArray = new int[10];
float[] intArray = new int[10];

// Here you have 10 index starting from 0 to 9
_x000D_
_x000D_
_x000D_

To use dynamic features, you have to use List... List is pure dynamic Array and there is no need to declare size at beginning. Below is the proper way to declare a list in Java -

_x000D_
_x000D_
ArrayList<String> myArray = new ArrayList<String>();
myArray.add("Value 1: something");
myArray.add("Value 2: something more");
_x000D_
_x000D_
_x000D_

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

The code above exports data without the heading columns which is weird. Here's how to do it. You have to merge the two files later though using text a editor.

SELECT column_name FROM information_schema.columns WHERE table_schema = 'my_app_db' AND table_name = 'customers' INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 5.6/Uploads/customers_heading_cols.csv' FIELDS TERMINATED BY '' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY ',';

What does this symbol mean in IntelliJ? (red circle on bottom-left corner of file name, with 'J' in it)

The first answer from irreputable above that starts out with "you need to specify the source dir" is correct, but I don't see him telling you the easy way to do so.

Simply right click on the java sources folder ("java" under src/main/java if it is a Maven project for example) and select Mark Directory As > Sources Root (see screenshot below).

enter image description here

Find the most popular element in int[] array

public class MostFrequentNumber {

    public MostFrequentNumber() {

    }

    int frequentNumber(List<Integer> list){

        int popular = 0;
        int holder = 0;

        for(Integer number: list) {
            int freq = Collections.frequency(list,number);

            if(holder < freq){
                holder = freq;
                popular = number;
            }
        }

       return popular;

    }

    public static void main(String[] args){

        int[] numbers = {4,6,2,5,4,7,6,4,7,7,7};

        List<Integer> list = new ArrayList<Integer>();

        for(Integer num : numbers){
            list.add(num);
        }


        MostFrequentNumber mostFrequentNumber = new MostFrequentNumber();

        System.out.println(mostFrequentNumber.frequentNumber(list));


    }
}

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

Adding the tomcat server in the server runtime will do the job :

Project Properties-> Java Build Path-> Add Library -> Select "Server Runtime" from the list-> Next->Select "Apache Tomcat"-> Finish

Digital Certificate: How to import .cer file in to .truststore file using?

# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.

keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]

Trust this certificate: [Yes]

changeit is the default truststore password

How to detect if CMD is running as Administrator/has elevated privileges?

Here's a simple method I've used on Windows 7 through Windows 10. Basically, I simply use the "IF EXIST" command to check for the Windows\System32\WDI\LogFiles folder. The WDI folder exists on every install of Windows from at least 7 onward, and it requires admin privileges to access. The WDI folder always has a LogFiles folder inside it. So, running "IF EXIST" on the WDI\LogFiles folder will return true if run as admin, and false if not run as admin. This can be used in a batch file to check privilege level, and branch to whichever commands you desire based on that result.

Here's a brief snippet of example code:

IF EXIST %SYSTEMROOT%\SYSTEM32\WDI\LOGFILES GOTO GOTADMIN
(Commands for running with normal privileges)

:GOTADMIN
(Commands for running with admin privileges)

Keep in mind that this method assumes the default security permissions have not been modified on the WDI folder (which is unlikely to happen in most situations, but please see caveat #2 below). Even in that case, it's simply a matter of modifying the code to check for a different common file/folder that requires admin access (System32\config\SAM may be a good alternate candidate), or you could even create your own specifically for that purpose.

There are two caveats about this method though:

  1. Disabling UAC will likely break it through the simple fact that everything would be run as admin anyway.

  2. Attempting to open the WDI folder in Windows Explorer and then clicking "Continue" when prompted will add permanent access rights for that user account, thus breaking my method. If this happens, it can be fixed by removing the user account from the WDI folder security permissions. If for any reason the user MUST be able to access the WDI folder with Windows Explorer, then you'd have to modify the code to check a different folder (as mentioned above, creating your own specifically for this purpose may be a good choice).

So, admittedly my method isn't perfect since it can be broken, but it's a relatively quick method that's easy to implement, is equally compatible with all versions of Windows 7, 8 and 10, and provided I stay mindful of the mentioned caveats has been 100% effective for me.

"import datetime" v.s. "from datetime import datetime"

datetime is a module which contains a type that is also called datetime. You appear to want to use both, but you're trying to use the same name to refer to both. The type and the module are two different things and you can't refer to both of them with the name datetime in your program.

If you need to use anything from the module besides the datetime type (as you apparently do), then you need to import the module with import datetime. You can then refer to the "date" type as datetime.date and the datetime type as datetime.datetime.

You could also do this:

from datetime import datetime, date
today_date = date.today()
date_time = datetime.strp(date_time_string, '%Y-%m-%d %H:%M')

Here you import only the names you need (the datetime and date types) and import them directly so you don't need to refer to the module itself at all.

Ultimately you have to decide what names from the module you need to use, and how best to use them. If you are only using one or two things from the module (e.g., just the date and datetime types), it may be okay to import those names directly. If you're using many things, it's probably better to import the module and access the things inside it using dot syntax, to avoid cluttering your global namespace with date-specific names.

Note also that, if you do import the module name itself, you can shorten the name to ease typing:

import datetime as dt
today_date = dt.date.today()
date_time = dt.datetime.strp(date_time_string, '%Y-%m-%d %H:%M')

EF Core add-migration Build Failed

Open Output window in Visual Studio and check your build log. In my case, even though my current configuration was Release, Add-Migration built the project in Debug, which had an error. For some reason, VS didn't display the error anywhere except Output window for me.

*ngIf and *ngFor on same element causing error

As @Zyzle mentioned, and @Günter mentioned in a comment (https://github.com/angular/angular/issues/7315), this is not supported.

With

<ul *ngIf="show">
  <li *ngFor="let thing of stuff">
    {{log(thing)}}
    <span>{{thing.name}}</span>
  </li>
</ul>

there are no empty <li> elements when the list is empty. Even the <ul> element does not exist (as expected).

When the list is populated, there are no redundant container elements.

The github discussion (4792) that @Zyzle mentioned in his comment also presents another solution using <template> (below I'm using your original markup ‐ using <div>s):

<template [ngIf]="show">
  <div *ngFor="let thing of stuff">
    {{log(thing)}}
    <span>{{thing.name}}</span>
  </div>
</template>

This solution also does not introduce any extra/redundant container elements.

Get checkbox values using checkbox name using jquery

Like it has been said few times, you need to change your selector to

$("input[name='bla[]']")

But I want to add, you have to use single or double quotes when using [] in selector.

How do I post form data with fetch api?

// Write Data

async function write(param) {
  var zahl = param.getAttribute("data-role");

  let mood = {
    appId: app_ID,
    key: "",
    value: zahl
  };

  let response = await fetch(web_api, {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(mood)
  });
  console.log(currentMood);

// Get Data

async function get() {

  let response = await fetch(web_api + "/App/" + app_ID, {
    method: "GET",
    headers: {
      "Content-Typ": "application/jason"
    }
  });

  let todos = await response.json();

// Remove Data

function remove(id) {
  return fetch(web_api" + id, {
    method: "DELETE"
  }).then(response => {
    if (!response.ok) {
      throw new Error("Todo konnte nicht entfernt werden.");
    }
  });
}


async function removeAll() {
  let response = await fetch(web_api + "/App/" + app_ID, {
    method: "GET",
    headers: {
      "Content-Typ": "application/jason"
    }
  });
  let todos = await response.json();
  console.log(todos);

  for (let todo of todos) {
    await remove(todo.id);
  }
}

// Update Data

  function updateTodo(todo) {
return fetch(`https://__________________/api/items/${todo.id}`, {
  method: "PUT",
  body: JSON.stringify(todo),
  headers: {
    "Content-Type": "application/json",
  },
}).then((response) => {
  if (!response.ok) {
    throw new Error("Todo konnte nicht upgedated werden.");
  }
});

}

sort csv by column

import operator
sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=True)

or use lambda

sortedlist = sorted(reader, key=lambda row: row[3], reverse=True)

Object of class stdClass could not be converted to string

try this

return $query->result_array();

What does T&& (double ampersand) mean in C++11?

It denotes an rvalue reference. Rvalue references will only bind to temporary objects, unless explicitly generated otherwise. They are used to make objects much more efficient under certain circumstances, and to provide a facility known as perfect forwarding, which greatly simplifies template code.

In C++03, you can't distinguish between a copy of a non-mutable lvalue and an rvalue.

std::string s;
std::string another(s);           // calls std::string(const std::string&);
std::string more(std::string(s)); // calls std::string(const std::string&);

In C++0x, this is not the case.

std::string s;
std::string another(s);           // calls std::string(const std::string&);
std::string more(std::string(s)); // calls std::string(std::string&&);

Consider the implementation behind these constructors. In the first case, the string has to perform a copy to retain value semantics, which involves a new heap allocation. However, in the second case, we know in advance that the object which was passed in to our constructor is immediately due for destruction, and it doesn't have to remain untouched. We can effectively just swap the internal pointers and not perform any copying at all in this scenario, which is substantially more efficient. Move semantics benefit any class which has expensive or prohibited copying of internally referenced resources. Consider the case of std::unique_ptr- now that our class can distinguish between temporaries and non-temporaries, we can make the move semantics work correctly so that the unique_ptr cannot be copied but can be moved, which means that std::unique_ptr can be legally stored in Standard containers, sorted, etc, whereas C++03's std::auto_ptr cannot.

Now we consider the other use of rvalue references- perfect forwarding. Consider the question of binding a reference to a reference.

std::string s;
std::string& ref = s;
(std::string&)& anotherref = ref; // usually expressed via template

Can't recall what C++03 says about this, but in C++0x, the resultant type when dealing with rvalue references is critical. An rvalue reference to a type T, where T is a reference type, becomes a reference of type T.

(std::string&)&& ref // ref is std::string&
(const std::string&)&& ref // ref is const std::string&
(std::string&&)&& ref // ref is std::string&&
(const std::string&&)&& ref // ref is const std::string&&

Consider the simplest template function- min and max. In C++03 you have to overload for all four combinations of const and non-const manually. In C++0x it's just one overload. Combined with variadic templates, this enables perfect forwarding.

template<typename A, typename B> auto min(A&& aref, B&& bref) {
    // for example, if you pass a const std::string& as first argument,
    // then A becomes const std::string& and by extension, aref becomes
    // const std::string&, completely maintaining it's type information.
    if (std::forward<A>(aref) < std::forward<B>(bref))
        return std::forward<A>(aref);
    else
        return std::forward<B>(bref);
}

I left off the return type deduction, because I can't recall how it's done offhand, but that min can accept any combination of lvalues, rvalues, const lvalues.

Difference between $(window).load() and $(document).ready() functions

$(document).ready happens when all the elements are present in the DOM, but not necessarily all content.

$(document).ready(function() {
    alert("document is ready");
});

window.onload or $(window).load() happens after all the content resources (images, etc) have been loaded.

$(window).load(function() {
    alert("window is loaded");
});

How to check how many letters are in a string in java?

To answer your questions in a easy way:

    a) String.length();
    b) String.charAt(/* String index */);

Invalid shorthand property initializer

Because it's an object, the way to assign value to its properties is using :.

Change the = to : to fix the error.

var options = {
  host: 'localhost',
  port: 8080,
  path: '/',
  method: 'POST'
 }

Reading binary file and looping over each byte

This post itself is not a direct answer to the question. What it is instead is a data-driven extensible benchmark that can be used to compare many of the answers (and variations of utilizing new features added in later, more modern, versions of Python) that have been posted to this question — and should therefore be helpful in determining which has the best performance.

In a few cases I've modified the code in the referenced answer to make it compatible with the benchmark framework.

First, here are the results for what currently are the latest versions of Python 2 & 3:

Fastest to slowest execution speeds with 32-bit Python 2.7.16
  numpy version 1.16.5
  Test file size: 1,024 KiB
  100 executions, best of 3 repetitions

1                  Tcll (array.array) :   3.8943 secs, rel speed   1.00x,   0.00% slower (262.95 KiB/sec)
2  Vinay Sajip (read all into memory) :   4.1164 secs, rel speed   1.06x,   5.71% slower (248.76 KiB/sec)
3            codeape + iter + partial :   4.1616 secs, rel speed   1.07x,   6.87% slower (246.06 KiB/sec)
4                             codeape :   4.1889 secs, rel speed   1.08x,   7.57% slower (244.46 KiB/sec)
5               Vinay Sajip (chunked) :   4.1977 secs, rel speed   1.08x,   7.79% slower (243.94 KiB/sec)
6           Aaron Hall (Py 2 version) :   4.2417 secs, rel speed   1.09x,   8.92% slower (241.41 KiB/sec)
7                     gerrit (struct) :   4.2561 secs, rel speed   1.09x,   9.29% slower (240.59 KiB/sec)
8                     Rick M. (numpy) :   8.1398 secs, rel speed   2.09x, 109.02% slower (125.80 KiB/sec)
9                           Skurmedel :  31.3264 secs, rel speed   8.04x, 704.42% slower ( 32.69 KiB/sec)

Benchmark runtime (min:sec) - 03:26

Fastest to slowest execution speeds with 32-bit Python 3.8.0
  numpy version 1.17.4
  Test file size: 1,024 KiB
  100 executions, best of 3 repetitions

1  Vinay Sajip + "yield from" + "walrus operator" :   3.5235 secs, rel speed   1.00x,   0.00% slower (290.62 KiB/sec)
2                       Aaron Hall + "yield from" :   3.5284 secs, rel speed   1.00x,   0.14% slower (290.22 KiB/sec)
3         codeape + iter + partial + "yield from" :   3.5303 secs, rel speed   1.00x,   0.19% slower (290.06 KiB/sec)
4                      Vinay Sajip + "yield from" :   3.5312 secs, rel speed   1.00x,   0.22% slower (289.99 KiB/sec)
5      codeape + "yield from" + "walrus operator" :   3.5370 secs, rel speed   1.00x,   0.38% slower (289.51 KiB/sec)
6                          codeape + "yield from" :   3.5390 secs, rel speed   1.00x,   0.44% slower (289.35 KiB/sec)
7                                      jfs (mmap) :   4.0612 secs, rel speed   1.15x,  15.26% slower (252.14 KiB/sec)
8              Vinay Sajip (read all into memory) :   4.5948 secs, rel speed   1.30x,  30.40% slower (222.86 KiB/sec)
9                        codeape + iter + partial :   4.5994 secs, rel speed   1.31x,  30.54% slower (222.64 KiB/sec)
10                                        codeape :   4.5995 secs, rel speed   1.31x,  30.54% slower (222.63 KiB/sec)
11                          Vinay Sajip (chunked) :   4.6110 secs, rel speed   1.31x,  30.87% slower (222.08 KiB/sec)
12                      Aaron Hall (Py 2 version) :   4.6292 secs, rel speed   1.31x,  31.38% slower (221.20 KiB/sec)
13                             Tcll (array.array) :   4.8627 secs, rel speed   1.38x,  38.01% slower (210.58 KiB/sec)
14                                gerrit (struct) :   5.0816 secs, rel speed   1.44x,  44.22% slower (201.51 KiB/sec)
15                 Rick M. (numpy) + "yield from" :  11.8084 secs, rel speed   3.35x, 235.13% slower ( 86.72 KiB/sec)
16                                      Skurmedel :  11.8806 secs, rel speed   3.37x, 237.18% slower ( 86.19 KiB/sec)
17                                Rick M. (numpy) :  13.3860 secs, rel speed   3.80x, 279.91% slower ( 76.50 KiB/sec)

Benchmark runtime (min:sec) - 04:47

I also ran it with a much larger 10 MiB test file (which took nearly an hour to run) and got performance results which were comparable to those shown above.

Here's the code used to do the benchmarking:

from __future__ import print_function
import array
import atexit
from collections import deque, namedtuple
import io
from mmap import ACCESS_READ, mmap
import numpy as np
from operator import attrgetter
import os
import random
import struct
import sys
import tempfile
from textwrap import dedent
import time
import timeit
import traceback

try:
    xrange
except NameError:  # Python 3
    xrange = range


class KiB(int):
    """ KibiBytes - multiples of the byte units for quantities of information. """
    def __new__(self, value=0):
        return 1024*value


BIG_TEST_FILE = 1  # MiBs or 0 for a small file.
SML_TEST_FILE = KiB(64)
EXECUTIONS = 100  # Number of times each "algorithm" is executed per timing run.
TIMINGS = 3  # Number of timing runs.
CHUNK_SIZE = KiB(8)
if BIG_TEST_FILE:
    FILE_SIZE = KiB(1024) * BIG_TEST_FILE
else:
    FILE_SIZE = SML_TEST_FILE  # For quicker testing.

# Common setup for all algorithms -- prefixed to each algorithm's setup.
COMMON_SETUP = dedent("""
    # Make accessible in algorithms.
    from __main__ import array, deque, get_buffer_size, mmap, np, struct
    from __main__ import ACCESS_READ, CHUNK_SIZE, FILE_SIZE, TEMP_FILENAME
    from functools import partial
    try:
        xrange
    except NameError:  # Python 3
        xrange = range
""")


def get_buffer_size(path):
    """ Determine optimal buffer size for reading files. """
    st = os.stat(path)
    try:
        bufsize = st.st_blksize # Available on some Unix systems (like Linux)
    except AttributeError:
        bufsize = io.DEFAULT_BUFFER_SIZE
    return bufsize

# Utility primarily for use when embedding additional algorithms into benchmark.
VERIFY_NUM_READ = """
    # Verify generator reads correct number of bytes (assumes values are correct).
    bytes_read = sum(1 for _ in file_byte_iterator(TEMP_FILENAME))
    assert bytes_read == FILE_SIZE, \
           'Wrong number of bytes generated: got {:,} instead of {:,}'.format(
                bytes_read, FILE_SIZE)
"""

TIMING = namedtuple('TIMING', 'label, exec_time')

class Algorithm(namedtuple('CodeFragments', 'setup, test')):

    # Default timeit "stmt" code fragment.
    _TEST = """
        #for b in file_byte_iterator(TEMP_FILENAME):  # Loop over every byte.
        #    pass  # Do stuff with byte...
        deque(file_byte_iterator(TEMP_FILENAME), maxlen=0)  # Data sink.
    """

    # Must overload __new__ because (named)tuples are immutable.
    def __new__(cls, setup, test=None):
        """ Dedent (unindent) code fragment string arguments.
        Args:
          `setup` -- Code fragment that defines things used by `test` code.
                     In this case it should define a generator function named
                     `file_byte_iterator()` that will be passed that name of a test file
                     of binary data. This code is not timed.
          `test` -- Code fragment that uses things defined in `setup` code.
                    Defaults to _TEST. This is the code that's timed.
        """
        test =  cls._TEST if test is None else test  # Use default unless one is provided.

        # Uncomment to replace all performance tests with one that verifies the correct
        # number of bytes values are being generated by the file_byte_iterator function.
        #test = VERIFY_NUM_READ

        return tuple.__new__(cls, (dedent(setup), dedent(test)))


algorithms = {

    'Aaron Hall (Py 2 version)': Algorithm("""
        def file_byte_iterator(path):
            with open(path, "rb") as file:
                callable = partial(file.read, 1024)
                sentinel = bytes() # or b''
                for chunk in iter(callable, sentinel):
                    for byte in chunk:
                        yield byte
    """),

    "codeape": Algorithm("""
        def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
            with open(filename, "rb") as f:
                while True:
                    chunk = f.read(chunksize)
                    if chunk:
                        for b in chunk:
                            yield b
                    else:
                        break
    """),

    "codeape + iter + partial": Algorithm("""
        def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
            with open(filename, "rb") as f:
                for chunk in iter(partial(f.read, chunksize), b''):
                    for b in chunk:
                        yield b
    """),

    "gerrit (struct)": Algorithm("""
        def file_byte_iterator(filename):
            with open(filename, "rb") as f:
                fmt = '{}B'.format(FILE_SIZE)  # Reads entire file at once.
                for b in struct.unpack(fmt, f.read()):
                    yield b
    """),

    'Rick M. (numpy)': Algorithm("""
        def file_byte_iterator(filename):
            for byte in np.fromfile(filename, 'u1'):
                yield byte
    """),

    "Skurmedel": Algorithm("""
        def file_byte_iterator(filename):
            with open(filename, "rb") as f:
                byte = f.read(1)
                while byte:
                    yield byte
                    byte = f.read(1)
    """),

    "Tcll (array.array)": Algorithm("""
        def file_byte_iterator(filename):
            with open(filename, "rb") as f:
                arr = array.array('B')
                arr.fromfile(f, FILE_SIZE)  # Reads entire file at once.
                for b in arr:
                    yield b
    """),

    "Vinay Sajip (read all into memory)": Algorithm("""
        def file_byte_iterator(filename):
            with open(filename, "rb") as f:
                bytes_read = f.read()  # Reads entire file at once.
            for b in bytes_read:
                yield b
    """),

    "Vinay Sajip (chunked)": Algorithm("""
        def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
            with open(filename, "rb") as f:
                chunk = f.read(chunksize)
                while chunk:
                    for b in chunk:
                        yield b
                    chunk = f.read(chunksize)
    """),

}  # End algorithms

#
# Versions of algorithms that will only work in certain releases (or better) of Python.
#
if sys.version_info >= (3, 3):
    algorithms.update({

        'codeape + iter + partial + "yield from"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    for chunk in iter(partial(f.read, chunksize), b''):
                        yield from chunk
        """),

        'codeape + "yield from"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    while True:
                        chunk = f.read(chunksize)
                        if chunk:
                            yield from chunk
                        else:
                            break
        """),

        "jfs (mmap)": Algorithm("""
            def file_byte_iterator(filename):
                with open(filename, "rb") as f, \
                     mmap(f.fileno(), 0, access=ACCESS_READ) as s:
                    yield from s
        """),

        'Rick M. (numpy) + "yield from"': Algorithm("""
            def file_byte_iterator(filename):
            #    data = np.fromfile(filename, 'u1')
                yield from np.fromfile(filename, 'u1')
        """),

        'Vinay Sajip + "yield from"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    chunk = f.read(chunksize)
                    while chunk:
                        yield from chunk  # Added in Py 3.3
                        chunk = f.read(chunksize)
        """),

    })  # End Python 3.3 update.

if sys.version_info >= (3, 5):
    algorithms.update({

        'Aaron Hall + "yield from"': Algorithm("""
            from pathlib import Path

            def file_byte_iterator(path):
                ''' Given a path, return an iterator over the file
                    that lazily loads the file.
                '''
                path = Path(path)
                bufsize = get_buffer_size(path)

                with path.open('rb') as file:
                    reader = partial(file.read1, bufsize)
                    for chunk in iter(reader, bytes()):
                        yield from chunk
        """),

    })  # End Python 3.5 update.

if sys.version_info >= (3, 8, 0):
    algorithms.update({

        'Vinay Sajip + "yield from" + "walrus operator"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    while chunk := f.read(chunksize):
                        yield from chunk  # Added in Py 3.3
        """),

        'codeape + "yield from" + "walrus operator"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    while chunk := f.read(chunksize):
                        yield from chunk
        """),

    })  # End Python 3.8.0 update.update.


#### Main ####

def main():
    global TEMP_FILENAME

    def cleanup():
        """ Clean up after testing is completed. """
        try:
            os.remove(TEMP_FILENAME)  # Delete the temporary file.
        except Exception:
            pass

    atexit.register(cleanup)

    # Create a named temporary binary file of pseudo-random bytes for testing.
    fd, TEMP_FILENAME = tempfile.mkstemp('.bin')
    with os.fdopen(fd, 'wb') as file:
         os.write(fd, bytearray(random.randrange(256) for _ in range(FILE_SIZE)))

    # Execute and time each algorithm, gather results.
    start_time = time.time()  # To determine how long testing itself takes.

    timings = []
    for label in algorithms:
        try:
            timing = TIMING(label,
                            min(timeit.repeat(algorithms[label].test,
                                              setup=COMMON_SETUP + algorithms[label].setup,
                                              repeat=TIMINGS, number=EXECUTIONS)))
        except Exception as exc:
            print('{} occurred timing the algorithm: "{}"\n  {}'.format(
                    type(exc).__name__, label, exc))
            traceback.print_exc(file=sys.stdout)  # Redirect to stdout.
            sys.exit(1)
        timings.append(timing)

    # Report results.
    print('Fastest to slowest execution speeds with {}-bit Python {}.{}.{}'.format(
            64 if sys.maxsize > 2**32 else 32, *sys.version_info[:3]))
    print('  numpy version {}'.format(np.version.full_version))
    print('  Test file size: {:,} KiB'.format(FILE_SIZE // KiB(1)))
    print('  {:,d} executions, best of {:d} repetitions'.format(EXECUTIONS, TIMINGS))
    print()

    longest = max(len(timing.label) for timing in timings)  # Len of longest identifier.
    ranked = sorted(timings, key=attrgetter('exec_time')) # Sort so fastest is first.
    fastest = ranked[0].exec_time
    for rank, timing in enumerate(ranked, 1):
        print('{:<2d} {:>{width}} : {:8.4f} secs, rel speed {:6.2f}x, {:6.2f}% slower '
              '({:6.2f} KiB/sec)'.format(
                    rank,
                    timing.label, timing.exec_time, round(timing.exec_time/fastest, 2),
                    round((timing.exec_time/fastest - 1) * 100, 2),
                    (FILE_SIZE/timing.exec_time) / KiB(1),  # per sec.
                    width=longest))
    print()
    mins, secs = divmod(time.time()-start_time, 60)
    print('Benchmark runtime (min:sec) - {:02d}:{:02d}'.format(int(mins),
                                                               int(round(secs))))

main()

Python: converting a list of dictionaries to json

To convert it to a single dictionary with some decided keys value, you can use the code below.

data = ListOfDict.copy()
PrecedingText = "Obs_"
ListOfDictAsDict = {}
for i in range(len(data)):
    ListOfDictAsDict[PrecedingText + str(i)] = data[i]

Batch file script to zip files

This is the correct syntax for archiving individual; folders in a batch as individual zipped files...

for /d %%X in (*) do "c:\Program Files\7-Zip\7z.exe" a -mx "%%X.zip" "%%X\*"

Facebook Graph API v2.0+ - /me/friends returns empty, or only friends who also use my application

Facebook has revised their policies now. You can’t get the whole friendlist anyway if your app does not have a Canvas implementation and if your app is not a game. Of course there’s also taggable_friends, but that one is for tagging only.

You will be able to pull the list of friends who have authorised the app only.

The apps that are using Graph API 1.0 will be working till April 30th, 2015 and after that it will be deprecated.

See the following to get more details on this:

Android SDK Manager gives "Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml" error when selecting repository

Open Android SDK Manager and open menu Tools->Options

in Proxy Setting Part Set your proxy and ok

Android Material Design Button Styles

Here is a sample that will help in applying button style consistently across your app.

Here is a sample Theme I used with the specific styles..

<style name="MyTheme" parent="@style/Theme.AppCompat.Light">
   <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_dark</item>
    <item name="colorAccent">@color/accent</item>
    <item name="android:buttonStyle">@style/ButtonAppTheme</item>
</style>
<style name="ButtonAppTheme" parent="android:Widget.Material.Button">
<item name="android:background">@drawable/material_button</item>
</style>

This is how I defined the button shape & effects inside res/drawable-v21 folder...

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?attr/colorControlHighlight">
  <item>
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
      <corners android:radius="2dp" /> 
      <solid android:color="@color/primary" />
    </shape>
  </item>
</ripple>

2dp corners are to keep it consistent with Material theme.

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

How to find out if a Python object is a string?

This evening I ran into a situation in which I thought I was going to have to check against the str type, but it turned out I did not.

My approach to solving the problem will probably work in many situations, so I offer it below in case others reading this question are interested (Python 3 only).

# NOTE: fields is an object that COULD be any number of things, including:
# - a single string-like object
# - a string-like object that needs to be converted to a sequence of 
# string-like objects at some separator, sep
# - a sequence of string-like objects
def getfields(*fields, sep=' ', validator=lambda f: True):
    '''Take a field sequence definition and yield from a validated
     field sequence. Accepts a string, a string with separators, 
     or a sequence of strings'''
    if fields:
        try:
            # single unpack in the case of a single argument
            fieldseq, = fields
            try:
                # convert to string sequence if string
                fieldseq = fieldseq.split(sep)
            except AttributeError:
                # not a string; assume other iterable
                pass
        except ValueError:
            # not a single argument and not a string
            fieldseq = fields
        invalid_fields = [field for field in fieldseq if not validator(field)]
        if invalid_fields:
            raise ValueError('One or more field names is invalid:\n'
                             '{!r}'.format(invalid_fields))
    else:
        raise ValueError('No fields were provided')
    try:
        yield from fieldseq
    except TypeError as e:
        raise ValueError('Single field argument must be a string'
                         'or an interable') from e

Some tests:

from . import getfields

def test_getfields_novalidation():
    result = ['a', 'b']
    assert list(getfields('a b')) == result
    assert list(getfields('a,b', sep=',')) == result
    assert list(getfields('a', 'b')) == result
    assert list(getfields(['a', 'b'])) == result

Usage of $broadcast(), $emit() And $on() in AngularJS

This little example shows how the $rootScope emit a event that will be listen by a children scope in another controller.

(function(){


angular
  .module('ExampleApp',[]);

angular
  .module('ExampleApp')
  .controller('ExampleController1', Controller1);

Controller1.$inject = ['$rootScope'];

function Controller1($rootScope) {
  var vm = this, 
      message = 'Hi my children scope boy';

  vm.sayHi = sayHi;

  function sayHi(){
    $rootScope.$broadcast('greeting', message);
  }

}

angular
  .module('ExampleApp')
  .controller('ExampleController2', Controller2);

Controller2.$inject = ['$scope'];

function Controller2($scope) {
  var vm = this;

  $scope.$on('greeting', listenGreeting)

  function listenGreeting($event, message){
    alert(['Message received',message].join(' : '));
  }

}


})();

http://codepen.io/gpincheiraa/pen/xOZwqa

The answer of @gayathri bottom explain technically the differences of all those methods in the scope angular concept and their implementations $scope and $rootScope.

Ruby: What is the easiest way to remove the first element from an array?

a = [0,1,2,3]

a.drop(1)
# => [1, 2, 3] 

a
# => [0,1,2,3]

and additionally:

[0,1,2,3].drop(2)
=> [2, 3]

[0,1,2,3].drop(3)
=> [3] 

How to send post request to the below post method using postman rest client

The Interface of Postman is changing acccording to the updates.

So You can get full information about postman can get Here.

https://www.getpostman.com/docs/requests

jquery animate background position

You can also use math combination "-=" to move background

$(this).animate( {backgroundPositionX: "-=20px"} ,500);

Execute a command line binary with Node.js

You are looking for child_process.exec

Here is the example:

const exec = require('child_process').exec;
const child = exec('cat *.js bad_file | wc -l',
    (error, stdout, stderr) => {
        console.log(`stdout: ${stdout}`);
        console.log(`stderr: ${stderr}`);
        if (error !== null) {
            console.log(`exec error: ${error}`);
        }
});

Print all but the first three columns

Pretty much all the answers currently add either leading spaces, trailing spaces or some other separator issue. To select from the fourth field where the separator is whitespace and the output separator is a single space using awk would be:

awk '{for(i=4;i<=NF;i++)printf "%s",$i (i==NF?ORS:OFS)}' file

To parametrize the starting field you could do:

awk '{for(i=n;i<=NF;i++)printf "%s",$i (i==NF?ORS:OFS)}' n=4 file

And also the ending field:

awk '{for(i=n;i<=m=(m>NF?NF:m);i++)printf "%s",$i (i==m?ORS:OFS)}' n=4 m=10 file

matplotlib set yaxis label size

If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

Difference between \w and \b regular expression meta characters

@Mahender, you probably meant the difference between \W (instead of \w) and \b. If not, then I would agree with @BoltClock and @jwismar above. Otherwise continue reading.

\W would match any non-word character and so its easy to try to use it to match word boundaries. The problem is that it will not match the start or end of a line. \b is more suited for matching word boundaries as it will also match the start or end of a line. Roughly speaking (more experienced users can correct me here) \b can be thought of as (\W|^|$). [Edit: as @?mega mentions below, \b is a zero-length match so (\W|^|$) is not strictly correct, but hopefully helps explain the diff]

Quick example: For the string Hello World, .+\W would match Hello_ (with the space) but will not match World. .+\b would match both Hello and World.

How to check if an excel cell is empty using Apache POI?

This is the safest and most concise way I see as of POI 3.1.7 up to POI 4:

boolean isBlankCell = CellType.BLANK == cell.getCellTypeEnum();
boolean isEmptyStringCell = CellType.STRING == cell.getCellTypeEnum() && cell.getStringCellValue().trim().isEmpty(); 

if (isBlankCell || isEmptyStringCell) {
    ...

As of POI 4 getCellTypeEnum() will be deprecated if favor of getCellType() but the return type should stay the same.

What is a quick way to force CRLF in C# / .NET?

Environment.NewLine;

A string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms.

Adding to a vector of pair

Read the following documentation:

http://cplusplus.com/reference/std/utility/make_pair/

or

http://en.cppreference.com/w/cpp/utility/pair/make_pair

I think that will help. Those sites are good resources for C++, though the latter seems to be the preferred reference these days.

How to delete node from XML file using C#

DocumentElement is the root node of the document so childNodes[1] doesn't exist in that document. childNodes[0] would be the <Settings> node

Javascript - object key->value

https://jsfiddle.net/sudheernunna/tug98nfm/1/

 var days = {};
days["monday"] = true;
days["tuesday"] = true;
days["wednesday"] = false;
days["thursday"] = true;
days["friday"] = false;
days["saturday"] = true;
days["sunday"] = false;
var userfalse=0,usertrue=0;
for(value in days)
{
   if(days[value]){
   usertrue++;
   }else{
   userfalse++;
   }
    console.log(days[value]);
}
alert("false",userfalse);
alert("true",usertrue);

Swift extract regex matches

@p4bloch if you want to capture results from a series of capture parentheses, then you need to use the rangeAtIndex(index) method of NSTextCheckingResult, instead of range. Here's @MartinR 's method for Swift2 from above, adapted for capture parentheses. In the array that is returned, the first result [0] is the entire capture, and then individual capture groups begin from [1]. I commented out the map operation (so it's easier to see what I changed) and replaced it with nested loops.

func matches(for regex: String!, in text: String!) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex, options: [])
        let nsString = text as NSString
        let results = regex.matchesInString(text, options: [], range: NSMakeRange(0, nsString.length))
        var match = [String]()
        for result in results {
            for i in 0..<result.numberOfRanges {
                match.append(nsString.substringWithRange( result.rangeAtIndex(i) ))
            }
        }
        return match
        //return results.map { nsString.substringWithRange( $0.range )} //rangeAtIndex(0)
    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

An example use case might be, say you want to split a string of title year eg "Finding Dory 2016" you could do this:

print ( matches(for: "^(.+)\\s(\\d{4})" , in: "Finding Dory 2016"))
// ["Finding Dory 2016", "Finding Dory", "2016"]

How do I change the default index page in Apache?

I recommend using .htaccess. You only need to add:

DirectoryIndex home.php

or whatever page name you want to have for it.

EDIT: basic htaccess tutorial.

1) Create .htaccess file in the directory where you want to change the index file.

  • no extension
  • . in front, to ensure it is a "hidden" file

Enter the line above in there. There will likely be many, many other things you will add to this (AddTypes for webfonts / media files, caching for headers, gzip declaration for compression, etc.), but that one line declares your new "home" page.

2) Set server to allow reading of .htaccess files (may only be needed on your localhost, if your hosting servce defaults to allow it as most do)

Assuming you have access, go to your server's enabled site location. I run a Debian server for development, and the default site setup is at /etc/apache2/sites-available/default for Debian / Ubuntu. Not sure what server you run, but just search for "sites-available" and go into the "default" document. In there you will see an entry for Directory. Modify it to look like this:

<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

Then restart your apache server. Again, not sure about your server, but the command on Debian / Ubuntu is:

sudo service apache2 restart

Technically you only need to reload, but I restart just because I feel safer with a full refresh like that.

Once that is done, your site should be reading from your .htaccess file, and you should have a new default home page! A side note, if you have a sub-directory that runs a site (like an admin section or something) and you want to have a different "home page" for that directory, you can just plop another .htaccess file in that sub-site's root and it will overwrite the declaration in the parent.

How can I get the list of files in a directory using C or C++?

UPDATE 2017:

In C++17 there is now an official way to list files of your file system: std::filesystem. There is an excellent answer from Shreevardhan below with this source code:

#include <string>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main()
{
    std::string path = "/path/to/directory";
    for (const auto & entry : fs::directory_iterator(path))
        std::cout << entry.path() << std::endl;
}

Old Answer:

In small and simple tasks I do not use boost, I use dirent.h which is also available for windows:

DIR *dir;
struct dirent *ent;
if ((dir = opendir ("c:\\src\\")) != NULL) {
  /* print all the files and directories within directory */
  while ((ent = readdir (dir)) != NULL) {
    printf ("%s\n", ent->d_name);
  }
  closedir (dir);
} else {
  /* could not open directory */
  perror ("");
  return EXIT_FAILURE;
}

It is just a small header file and does most of the simple stuff you need without using a big template-based approach like boost(no offence, I like boost!).

The author of the windows compatibility layer is Toni Ronkko. In Unix, it is a standard header.

What is the reason behind "non-static method cannot be referenced from a static context"?

If we try to access an instance method from a static context , the compiler has no way to guess which instance method ( variable for which object ), you are referring to. Though, you can always access it using an object reference.

Singleton in Android

As @Lazy stated in this answer, you can create a singleton from a template in Android Studio. It is worth noting that there is no need to check if the instance is null because the static ourInstance variable is initialized first. As a result, the singleton class implementation created by Android Studio is as simple as following code:

public class MySingleton {
    private static MySingleton ourInstance = new MySingleton();

    public static MySingleton getInstance() {
        return ourInstance;
    }

    private MySingleton() {
    }
}

How to extract a string using JavaScript Regex?

This code works:

  let str = "governance[string_i_want]"; 
  let res = str.match(/[^governance\[](.*)[^\]]/g);

res will equal "string_i_want". However, in this example res is still an array, so do not treat res like a string.

By grouping the characters I do not want, using [^string], and matching on what is between the brackets, the code extracts the string I want!

You can try it out here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_match_regexp

Good luck.

How to use nan and inf in C?

This works for both float and double:

double NAN = 0.0/0.0;
double POS_INF = 1.0 /0.0;
double NEG_INF = -1.0/0.0;

Edit: As someone already said, the old IEEE standard said that such values should raise traps. But the new compilers almost always switch the traps off and return the given values because trapping interferes with error handling.

What is a View in Oracle?

A view is simply any SELECT query that has been given a name and saved in the database. For this reason, a view is sometimes called a named query or a stored query. To create a view, you use the SQL syntax:

     CREATE OR REPLACE VIEW <view_name> AS
     SELECT <any valid select query>;

Getting and removing the first character of a string

There is also str_sub from the stringr package

x <- 'hello stackoverflow'
str_sub(x, 2) # or
str_sub(x, 2, str_length(x))
[1] "ello stackoverflow"

CSS two divs next to each other

As everyone has pointed out, you'll do this by setting a float:right; on the RHS content and a negative margin on the LHS.

However.. if you don't use a float: left; on the LHS (as Mohit does) then you'll get a stepping effect because the LHS div is still going to consume the margin'd space in layout.

However.. the LHS float will shrink-wrap the content, so you'll need to insert a defined width childnode if that's not acceptable, at which point you may as well have defined the width on the parent.

However.. as David points out you can change the read-order of the markup to avoid the LHS float requirement, but that's has readability and possibly accessibility issues.

However.. this problem can be solved with floats given some additional markup

(caveat: I don't approve of the .clearing div at that example, see here for details)

All things considered, I think most of us wish there was a non-greedy width:remaining in CSS3...

Fatal error: Call to undefined function base_url() in C:\wamp\www\Test-CI\application\views\layout.php on line 5

codeigniter needs to load the url helper to call the base_url() function.

use application->config->autoload.php

edit autoload helper array and add url helper..

base_url() function is working now..

powershell - list local users and their groups

For Googlers, another way to get a list of users is to use:

Get-WmiObject -Class Win32_UserAccount

From http://buckeyejeeps.com/blog/?p=764

What in the world are Spring beans?

For Spring, all objects are beans! The fundamental step in the Spring Framework is to define your objects as beans. Beans are nothing but object instances that would be created by the spring framework by looking at their class definitions. These definitions basically form the configuration metadata. The framework then creates a plan for which objects need to be instantiated, which dependencies need to be set and injected, the scope of the newly created instance, etc., based on this configuration metadata.

The metadata can be supplied in a simple XML file, just like in the first chapter. Alternatively, one could provide the metadata as Annotation or Java Configuration.

Book: Just Spring

Android BroadcastReceiver within Activity

I think your problem is that you send the broadcast before the other activity start ! so the other activity will not receive anything .

  1. The best practice to test your code is to sendbroadcast from thread or from a service so the activity is opened and its registered the receiver and the background process sends a message.
  2. start the ToastDisplay activity from the sender activity ( I didn't test that but it may work probably )

Declaring variable workbook / Worksheet vba

Use Sheets rather than Sheet and activate them sequentially:

Sub kl()
    Dim wb As Workbook
    Dim ws As Worksheet
    Set wb = ActiveWorkbook
    Set ws = Sheets("Sheet1")
    wb.Activate
    ws.Select
End Sub

how to get list of port which are in use on the server

Open up a command prompt then type...

netstat -a

How to get filename without extension from file path in Ruby

Try File.basename

Returns the last component of the filename given in file_name, which must be formed using forward slashes (``/’’) regardless of the separator used on the local file system. If suffix is given and present at the end of file_name, it is removed.

File.basename("/home/gumby/work/ruby.rb")          #=> "ruby.rb"
File.basename("/home/gumby/work/ruby.rb", ".rb")   #=> "ruby"

In your case:

File.basename("C:\\projects\\blah.dll", ".dll")  #=> "blah"

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

I have tried to make note about these and have collected and written examples from a java perspective.

HTTP for Java Developers

Reverse Ajax - Old style

Async Handling on server side

Reverse Ajax - New style

Server Sent Events

Putting it here for any java developer who is looking into the same subject.

Log.INFO vs. Log.DEBUG

I usually try to use it like this:

  • DEBUG: Information interesting for Developers, when trying to debug a problem.
  • INFO: Information interesting for Support staff trying to figure out the context of a given error
  • WARN to FATAL: Problems and Errors depending on level of damage.

javascript function wait until another function to finish

There are several ways I can think of to do this.

Use a callback:

 function FunctInit(someVarible){
      //init and fill screen
      AndroidCallGetResult();  // Enables Android button.
 }

 function getResult(){ // Called from Android button only after button is enabled
      //return some variables
 }

Use a Timeout (this would probably be my preference):

 var inited = false;
 function FunctInit(someVarible){
      //init and fill screen
      inited = true;
 }

 function getResult(){
      if (inited) {
           //return some variables
      } else {
           setTimeout(getResult, 250);
      }
 }

Wait for the initialization to occur:

 var inited = false;
 function FunctInit(someVarible){
      //init and fill screen
      inited = true;
 }

 function getResult(){
      var a = 1;
      do { a=1; }
      while(!inited);
      //return some variables
 }

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k http://www.example.com/

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to
    http://hostname/bar/img.gif. 

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

converting multiple columns from character to numeric format in r

I think I figured it out. Here's what I did (perhaps not the most elegant solution - suggestions on how to imp[rove this are very much welcome)

#names of columns in data frame
cols <- names(DF)
# character variables
cols.char <- c("fx_code","date")
#numeric variables
cols.num <- cols[!cols %in% cols.char]

DF.char <- DF[cols.char]
DF.num <- as.data.frame(lapply(DF[cols.num],as.numeric))
DF2 <- cbind(DF.char, DF.num)

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

I really like following clean solution.

class Router
  include Rails.application.routes.url_helpers

  def self.default_url_options
    ActionMailer::Base.default_url_options
  end
end

router = Router.new
router.posts_url  # http://localhost:3000/posts
router.posts_path # /posts

It's from http://hawkins.io/2012/03/generating_urls_whenever_and_wherever_you_want/

What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

The ~ selector is in fact the General sibling combinator (renamed to Subsequent-sibling combinator in selectors Level 4):

The general sibling combinator is made of the "tilde" (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.

Consider the following example:

_x000D_
_x000D_
.a ~ .b {_x000D_
  background-color: powderblue;_x000D_
}
_x000D_
<ul>_x000D_
  <li class="b">1st</li>_x000D_
  <li class="a">2nd</li>_x000D_
  <li>3rd</li>_x000D_
  <li class="b">4th</li>_x000D_
  <li class="b">5th</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

.a ~ .b matches the 4th and 5th list item because they:

  • Are .b elements
  • Are siblings of .a
  • Appear after .a in HTML source order.

Likewise, .check:checked ~ .content matches all .content elements that are siblings of .check:checked and appear after it.

Run a shell script with an html button

PHP is likely the easiest.

Just make a file script.php that contains <?php shell_exec("yourscript.sh"); ?> and send anybody who clicks the button to that destination. You can return the user to the original page with header:

<?php
shell_exec("yourscript.sh");
header('Location: http://www.website.com/page?success=true');
?>

Reference: http://php.net/manual/en/function.shell-exec.php

How do I install a NuGet package .nupkg file locally?

You can also use the Package Manager Console and invoke the Install-Package cmdlet by specifying the path to the directory that contains the package file in the -Source parameter:

Install-Package SomePackage -Source C:\PathToThePackageDir\

What is hashCode used for? Is it unique?

GetHashCode() is used to help support using the object as a key for hash tables. (A similar thing exists in Java etc). The goal is for every object to return a distinct hash code, but this often can't be absolutely guaranteed. It is required though that two logically equal objects return the same hash code.

A typical hash table implementation starts with the hashCode value, takes a modulus (thus constraining the value within a range) and uses it as an index to an array of "buckets".

Head and tail in one line

>>> mylist = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> head, tail = mylist[0], mylist[1:]
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]

How can I install Visual Studio Code extensions offline?

UPDATE 2017-12-13

You can now download the extension directly from the marketplace.

Enter image description here

As of Visual Studio Code 1.7.1 dragging or opening the extension does not work any more. In order to install it manually you need to:

  • open the extensions sidebar
  • click on the ellipsis in the right upper corner
  • choose Install from VSIX

Install from VSIX...


Old Method

According to the documentation it is possible to download an extension directly:

An extension's direct download URL is in the form:

https://${publisher}.gallery.vsassets.io/_apis/public/gallery/publisher/${publisher}/extension/${extension name}/${version}/assetbyname/Microsoft.VisualStudio.Services.VSIXPackage

This means that in order to download the extension you need to know

  • the publisher name
  • the version
  • the extension name

You can find all this information in the URL.

Example

Here's an example for downloading an installing the C# v1.3.0 extension:

Publisher, Extension and Version

You can find the publisher and the extension names on the extension's homepage inside its URL:

https://marketplace.visualstudio.com/items?itemName=ms-vscode.csharp

Here the publisher is ms-vscode and the extension name is csharp.

The version can be found on the right side in the More Info area.

To download it you need to create a link from the template above:

https://ms-vscode.gallery.vsassets.io/_apis/public/gallery/publisher/ms-vscode/extension/csharp/1.3.0/assetbyname/Microsoft.VisualStudio.Services.VSIXPackage

All packages will have the same name Microsoft.VisualStudio.Services.VSIXPackage, so you'll need to rename it after downloading if you want to know what package it was later.

Installation

In order to install the extension

  • Rename the file and give it the *.vsix extension
  • Open Visual Studio Code, go to menu FileOpen File... or Ctrl + O and select the .vsix file
  • If everything went fine, you should see this message at the top of the window:

Extension was successfully installed. Restart to enable it.

How do I create a copy of an object in PHP?

If you want to fully copy properties of an object in a different instance, you may want to use this technique:

Serialize it to JSON and then de-serialize it back to Object.

Count number of days between two dates

I kept getting results in seconds, so this worked for me:

(Time.now - self.created_at) / 86400

Best practice for instantiating a new Android Fragment

Best practice to instance fragments with arguments in android is to have static factory method in your fragment.

public static MyFragment newInstance(String name, int age) {
    Bundle bundle = new Bundle();
    bundle.putString("name", name);
    bundle.putInt("age", age);

    MyFragment fragment = new MyFragment();
    fragment.setArguments(bundle);

    return fragment;
}

You should avoid setting your fields with the instance of a fragment. Because whenever android system recreate your fragment, if it feels that the system needs more memory, than it will recreate your fragment by using constructor with no arguments.

You can find more info about best practice to instantiate fragments with arguments here.

How to install PIP on Python 3.6?

I have in this moment install the bs4 with python 3.6.3 on Windows.

C:\yourfolderx\yourfoldery>python.exe -m pip install bs4

with the syntax like the user post below:

I just successfully installed a package for excel. After installing the python 3.6, you have to download the desired package, then install. For eg,

python.exe -m pip download openpyxl==2.1.4

python.exe -m pip install openpyxl==2.1.4

Java - Check if JTextField is empty or not

if(name.getText().hashCode() != 0){
    JOptionPane.showMessageDialog(null, "not empty");
}
else{
    JOptionPane.showMessageDialog(null, "empty");
}

Move the mouse pointer to a specific position?

You can't move the mouse pointer using javascript, and thus for obvious security reasons. The best way to achieve this effect would be to actually place the control under the mouse pointer.

Find index of last occurrence of a sub-string using T-SQL

REVERSE(SUBSTRING(REVERSE(ap_description),CHARINDEX('.',REVERSE(ap_description)),len(ap_description)))  

worked better for me

Detecting Browser Autofill

For anyone looking for a 2020 pure JS solution to detect autofill, here ya go.

Please forgive tab errors, can't get this to sit nicely on SO

    //Chose the element you want to select - in this case input
    var autofill = document.getElementsByTagName('input');
    for (var i = 0; i < autofill.length; i++) {
      //Wrap this in a try/catch because non webkit browsers will log errors on this pseudo element
      try{
        if (autofill[i].matches(':-webkit-autofill')) {
            //Do whatever you like with each autofilled element
        }
      }
      catch(error){
        return(false);
      }
     }

How do I change the default library path for R packages

Windows 10 on a Network

Having your packages stored on the network drive can slow down the performance of R / R Studio considerably, and you spend a lot of time waiting for the libraries to load/install, due to the bottlenecks of having to retrieve and push data over the server back to your local host. See the following for instructions on how to create an .RProfile on your local machine:

  1. Create a directory called C:\Users\xxxxxx\Documents\R\3.4 (or whatever R version you are using, and where you will store your local R packages- your directory location may be different than mine)
  2. On R Console, type Sys.getenv("HOME") to get your home directory (this is where your .RProfile will be stored and R will always check there for packages- and this is on the network if packages are stored there)
  3. Create a file called .Rprofile and place it in :\YOUR\HOME\DIRECTORY\ON_NETWORK (the directory you get after typing Sys.getenv("HOME") in R Console)
  4. File contents of .Rprofile should be like this:

#search 2 places for packages- install new packages to first directory- load built-in packages from the second (this is from your base R package- will be different for some)

.libPaths(c("C:\Users\xxxxxx\Documents\R\3.4", "C:/Program Files/Microsoft/R Client/R_SERVER/library"))

message("*** Setting libPath to local hard drive ***")

#insert a sleep command at line 12 of the unpackPkgZip function. So, just after the package is unzipped.

trace(utils:::unpackPkgZip, quote(Sys.sleep(2)), at=12L, print=TRUE)

message("*** Add 2 second delay when installing packages, to accommodate virus scanner for R 3.4 (fixed in R 3.5+)***")

# fix problem with tcltk for sqldf package: https://github.com/ggrothendieck/sqldf#problem-involvling-tcltk

options(gsubfn.engine = "R")

message("*** Successfully loaded .Rprofile ***")
  1. Restart R Studio and verify that you see that the messages above are displayed.

Now you can enjoy faster performance of your application on local host, vs. storing the packages on the network and slowing everything down.

CXF: No message body writer found for class - automatically mapping non-simple resources

When programmatically creating server, you can add message body writers for json/xml by setting Providers.

JAXRSServerFactoryBean bean = new JAXRSServerFactoryBean();
bean.setAddress("http://localhost:9000/");

List<Object> providers = new ArrayList<Object>();
providers.add(new JacksonJaxbJsonProvider());
providers.add(new JacksonJaxbXMLProvider());
bean.setProviders(providers);

List<Class< ? >> resourceClasses = new ArrayList<Class< ? >>();
resourceClasses.add(YourRestServiceImpl.class);
bean.setResourceClasses(resourceClasses);

bean.setResourceProvider(YourRestServiceImpl.class, new SingletonResourceProvider(new YourRestServiceImpl()));

BindingFactoryManager manager = bean.getBus().getExtension(BindingFactoryManager.class);
JAXRSBindingFactory restFactory = new JAXRSBindingFactory();
restFactory.setBus(bean.getBus());
manager.registerBindingFactory(JAXRSBindingFactory.JAXRS_BINDING_ID, restFactory);

bean.create();

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

I've had a very similar issue using spring-boot-starter-data-redis. To my implementation there was offered a @Bean for RedisTemplate as follows:

@Bean
public RedisTemplate<String, List<RoutePlantCache>> redisTemplate(RedisConnectionFactory connectionFactory) {
    final RedisTemplate<String, List<RoutePlantCache>> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache.class));

    // Add some specific configuration here. Key serializers, etc.
    return template;
}

The fix was to specify an array of RoutePlantCache as following:

template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache[].class));

Below the exception I had:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `[...].RoutePlantCache` out of START_ARRAY token
 at [Source: (byte[])"[{ ... },{ ... [truncated 1478 bytes]; line: 1, column: 1]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1468) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1242) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1190) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeFromArray(BeanDeserializer.java:604) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:190) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3572) ~[jackson-databind-2.11.4.jar:2.11.4]

Detect click outside React component

I found a solution thanks to Ben Alpert on discuss.reactjs.org. The suggested approach attaches a handler to the document but that turned out to be problematic. Clicking on one of the components in my tree resulted in a rerender which removed the clicked element on update. Because the rerender from React happens before the document body handler is called, the element was not detected as "inside" the tree.

The solution to this was to add the handler on the application root element.

main:

window.__myapp_container = document.getElementById('app')
React.render(<App/>, window.__myapp_container)

component:

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

export default class ClickListener extends Component {

  static propTypes = {
    children: PropTypes.node.isRequired,
    onClickOutside: PropTypes.func.isRequired
  }

  componentDidMount () {
    window.__myapp_container.addEventListener('click', this.handleDocumentClick)
  }

  componentWillUnmount () {
    window.__myapp_container.removeEventListener('click', this.handleDocumentClick)
  }

  /* using fat arrow to bind to instance */
  handleDocumentClick = (evt) => {
    const area = ReactDOM.findDOMNode(this.refs.area);

    if (!area.contains(evt.target)) {
      this.props.onClickOutside(evt)
    }
  }

  render () {
    return (
      <div ref='area'>
       {this.props.children}
      </div>
    )
  }
}

Exception in thread "main" java.lang.Error: Unresolved compilation problems

For this error:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:

There are problems with your import or package name.
You can delete the package name or fix import errors

Can a normal Class implement multiple interfaces?

public class A implements C,D {...} valid

this is the way to implement multiple inheritence in java

Retrieve last 100 lines logs

"tail" is command to display the last part of a file, using proper available switches helps us to get more specific output. the most used switch for me is -n and -f

SYNOPSIS

tail [-F | -f | -r] [-q] [-b number | -c number | -n number] [file ...]

Here

-n number : The location is number lines.

-f : The -f option causes tail to not stop when end of file is reached, but rather to wait for additional data to be appended to the input. The -f option is ignored if the standard input is a pipe, but not if it is a FIFO.

Retrieve last 100 lines logs

To get last static 100 lines  
     tail -n 100 <file path>

To get real time last 100 lines
     tail -f -n 100 <file path>

Should I size a textarea with CSS width / height or HTML cols / rows attributes?

 <textarea style="width:300px; height:150px;" ></textarea>

Stored procedure or function expects parameter which is not supplied

in my case, I was passing all the parameters but one of the parameter my code was passing a null value for string.

Eg: cmd.Parameters.AddWithValue("@userName", userName);

in the above case, if the data type of userName is string, I was passing userName as null.

The transaction manager has disabled its support for remote/network transactions

Make sure that the "Distributed Transaction Coordinator" Service is running on both database and client. Also make sure you check "Network DTC Access", "Allow Remote Client", "Allow Inbound/Outbound" and "Enable TIP".

To enable Network DTC Access for MS DTC transactions

  1. Open the Component Services snap-in.

    To open Component Services, click Start. In the search box, type dcomcnfg, and then press ENTER.

  2. Expand the console tree to locate the DTC (for example, Local DTC) for which you want to enable Network MS DTC Access.

  3. On the Action menu, click Properties.

  4. Click the Security tab and make the following changes: In Security Settings, select the Network DTC Access check box.

    In Transaction Manager Communication, select the Allow Inbound and Allow Outbound check boxes.

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

Convert JSONArray to String Array

You can loop to create the String

List<String> list = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
    list.add( jsonArray.getString(i) );
}
String[] stringArray = list.toArray(new String[list.size()]);

Access IP Camera in Python OpenCV

The easiest way to stream video via IP Camera !

I just edit your example. You must replace your IP and add /video on your link. And go ahead with your project

import cv2

cap = cv2.VideoCapture('http://192.168.18.37:8090/video')

while(True):
    ret, frame = cap.read()
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        cv2.destroyAllWindows()
        break

Unable to simultaneously satisfy constraints, will attempt to recover by breaking constraint

 for(UIView *view in [self.view subviews]) {
    [view setTranslatesAutoresizingMaskIntoConstraints:NO];
}

This helped me catch the view causing the problem.

How to make Bootstrap Panel body with fixed height

HTML :

<div class="span4">
  <div class="panel panel-primary">
    <div class="panel-heading">jhdsahfjhdfhs</div>
    <div class="panel-body panel-height">fdoinfds sdofjohisdfj</div>
  </div>
</div>

CSS :

.panel-height {
  height: 100px; / change according to your requirement/
}

How to fix Ora-01427 single-row subquery returns more than one row in select?

Use the following query:

SELECT E.I_EmpID AS EMPID,
       E.I_EMPCODE AS EMPCODE,
       E.I_EmpName AS EMPNAME,
       REPLACE(TO_CHAR(A.I_REQDATE, 'DD-Mon-YYYY'), ' ', '') AS FROMDATE,
       REPLACE(TO_CHAR(A.I_ENDDATE, 'DD-Mon-YYYY'), ' ', '') AS TODATE,
       TO_CHAR(NOD) AS NOD,
       DECODE(A.I_DURATION,
              'FD',
              'FullDay',
              'FN',
              'ForeNoon',
              'AN',
              'AfterNoon') AS DURATION,
       L.I_LeaveType AS LEAVETYPE,
       REPLACE(TO_CHAR((SELECT max(C.I_WORKDATE)
                         FROM T_COMPENSATION C
                        WHERE C.I_COMPENSATEDDATE = A.I_REQDATE
                          AND C.I_EMPID = A.I_EMPID),
                       'DD-Mon-YYYY'),
               ' ',
               '') AS WORKDATE,
       A.I_REASON AS REASON,
       AP.I_REJECTREASON AS REJECTREASON
  FROM T_LEAVEAPPLY A
 INNER JOIN T_EMPLOYEE_MS E
    ON A.I_EMPID = E.I_EmpID
   AND UPPER(E.I_IsActive) = 'YES'
   AND A.I_STATUS = '1'
 INNER JOIN T_LeaveType_MS L
    ON A.I_LEAVETYPEID = L.I_LEAVETYPEID
  LEFT OUTER JOIN T_APPROVAL AP
    ON A.I_REQDATE = AP.I_REQDATE
   AND A.I_EMPID = AP.I_EMPID
   AND AP.I_APPROVALSTATUS = '1'
 WHERE E.I_EMPID <> '22'
 ORDER BY A.I_REQDATE DESC

The trick is to force the inner query return only one record by adding an aggregate function (I have used max() here). This will work perfectly as far as the query is concerned, but, honestly, OP should investigate why the inner query is returning multiple records by examining the data. Are these multiple records really relevant business wise?

const vs constexpr on variables

A constexpr symbolic constant must be given a value that is known at compile time. For example:

?constexpr int max = 100; 
void use(int n)
{
    constexpr int c1 = max+7; // OK: c1 is 107
    constexpr int c2 = n+7;   // Error: we don’t know the value of c2
    // ...
}

To handle cases where the value of a “variable” that is initialized with a value that is not known at compile time but never changes after initialization, C++ offers a second form of constant (a const). For Example:

?constexpr int max = 100; 
void use(int n)
{
    constexpr int c1 = max+7; // OK: c1 is 107
    const int c2 = n+7; // OK, but don’t try to change the value of c2
    // ...
    c2 = 7; // error: c2 is a const
}

Such “const variables” are very common for two reasons:

  1. C++98 did not have constexpr, so people used const.
  2. List item “Variables” that are not constant expressions (their value is not known at compile time) but do not change values after initialization are in themselves widely useful.

Reference : "Programming: Principles and Practice Using C++" by Stroustrup

How to make a window always stay on top in .Net?

If by "going crazy" you mean that each window keeps stealing focus from the other, TopMost will not solve the problem.

Instead, try:

CalledForm.Owner = CallerForm;
CalledForm.Show();

This will show the 'child' form without it stealing focus. The child form will also stay on top of its parent even if the parent is activated or focused. This code only works easily if you've created an instance of the child form from within the owner form. Otherwise, you might have to set the owner using the API.

Django download a file

Reference:

In view.py Implement function like,

def download(request, id):
    obj = your_model_name.objects.get(id=id)
    filename = obj.model_attribute_name.path
    response = FileResponse(open(filename, 'rb'))
    return response

How to pass macro definition from "make" command line arguments (-D) to C source code?

$ cat x.mak
all:
    echo $(OPTION)
$ make -f x.mak 'OPTION=-DPASSTOC=42'
echo -DPASSTOC=42
-DPASSTOC=42

How to create a directory if it doesn't exist using Node.js?

var fs = require('fs');
var dir = './tmp';

if (!fs.existsSync(dir)){
    fs.mkdirSync(dir);
}

Javascript one line If...else...else if statement

Sure, you can do nested ternary operators but they are hard to read.

var variable = (condition) ? (true block) : ((condition2) ? (true block2) : (else block2))

'uint32_t' identifier not found error

You can #include <cstdint>. It's part of C++-standard since 2011.

How to select a schema in postgres when using psql?

\l - Display database
\c - Connect to database
\dn - List schemas
\dt - List tables inside public schemas
\dt schema1. - List tables inside particular schemas. For eg: 'schema1'.

document.getElementByID is not a function

It's document.getElementById() and not document.getElementByID(). Check the casing for Id.

How can I run a function from a script in command line?

I have a situation where I need a function from bash script which must not be executed before (e.g. by source) and the problem with @$ is that myScript.sh is then run twice, it seems... So I've come up with the idea to get the function out with sed:

sed -n "/^func ()/,/^}/p" myScript.sh

And to execute it at the time I need it, I put it in a file and use source:

sed -n "/^func ()/,/^}/p" myScript.sh > func.sh; source func.sh; rm func.sh

Search an Oracle database for tables with specific column names?

Here is one that we have saved off to findcol.sql so we can run it easily from within SQLPlus

set verify off
clear break
accept colnam prompt 'Enter Column Name (or part of): '
set wrap off
select distinct table_name, 
                column_name, 
                data_type || ' (' || 
                decode(data_type,'LONG',null,'LONG RAW',null,
                       'BLOB',null,'CLOB',null,'NUMBER',
                       decode(data_precision,null,to_char(data_length),
                              data_precision||','||data_scale
                             ), data_length
                      ) || ')' data_type
  from all_tab_columns
 where column_name like ('%' || upper('&colnam') || '%');
set verify on

One-line list comprehension: if-else variants

x if y else z is the syntax for the expression you're returning for each element. Thus you need:

[ x if x%2 else x*100 for x in range(1, 10) ]

The confusion arises from the fact you're using a filter in the first example, but not in the second. In the second example you're only mapping each value to another, using a ternary-operator expression.

With a filter, you need:

[ EXP for x in seq if COND ]

Without a filter you need:

[ EXP for x in seq ]

and in your second example, the expression is a "complex" one, which happens to involve an if-else.

How to write a switch statement in Ruby

I've started to use:

a = "secondcase"

var_name = case a
  when "firstcase" then "foo"
  when "secondcase" then "bar"
end

puts var_name
>> "bar"

It helps compact code in some cases.

Making PHP var_dump() values display one line per value

Yes, try wrapping it with <pre>, e.g.:

echo '<pre>' , var_dump($variable) , '</pre>';

How to secure an ASP.NET Web API

Have you tried DevDefined.OAuth?

I have used it to secure my WebApi with 2-Legged OAuth. I have also successfully tested it with PHP clients.

It's quite easy to add support for OAuth using this library. Here's how you can implement the provider for ASP.NET MVC Web API:

1) Get the source code of DevDefined.OAuth: https://github.com/bittercoder/DevDefined.OAuth - the newest version allows for OAuthContextBuilder extensibility.

2) Build the library and reference it in your Web API project.

3) Create a custom context builder to support building a context from HttpRequestMessage:

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http;
using System.Web;

using DevDefined.OAuth.Framework;

public class WebApiOAuthContextBuilder : OAuthContextBuilder
{
    public WebApiOAuthContextBuilder()
        : base(UriAdjuster)
    {
    }

    public IOAuthContext FromHttpRequest(HttpRequestMessage request)
    {
        var context = new OAuthContext
            {
                RawUri = this.CleanUri(request.RequestUri), 
                Cookies = this.CollectCookies(request), 
                Headers = ExtractHeaders(request), 
                RequestMethod = request.Method.ToString(), 
                QueryParameters = request.GetQueryNameValuePairs()
                    .ToNameValueCollection(), 
            };

        if (request.Content != null)
        {
            var contentResult = request.Content.ReadAsByteArrayAsync();
            context.RawContent = contentResult.Result;

            try
            {
                // the following line can result in a NullReferenceException
                var contentType = 
                    request.Content.Headers.ContentType.MediaType;
                context.RawContentType = contentType;

                if (contentType.ToLower()
                    .Contains("application/x-www-form-urlencoded"))
                {
                    var stringContentResult = request.Content
                        .ReadAsStringAsync();
                    context.FormEncodedParameters = 
                        HttpUtility.ParseQueryString(stringContentResult.Result);
                }
            }
            catch (NullReferenceException)
            {
            }
        }

        this.ParseAuthorizationHeader(context.Headers, context);

        return context;
    }

    protected static NameValueCollection ExtractHeaders(
        HttpRequestMessage request)
    {
        var result = new NameValueCollection();

        foreach (var header in request.Headers)
        {
            var values = header.Value.ToArray();
            var value = string.Empty;

            if (values.Length > 0)
            {
                value = values[0];
            }

            result.Add(header.Key, value);
        }

        return result;
    }

    protected NameValueCollection CollectCookies(
        HttpRequestMessage request)
    {
        IEnumerable<string> values;

        if (!request.Headers.TryGetValues("Set-Cookie", out values))
        {
            return new NameValueCollection();
        }

        var header = values.FirstOrDefault();

        return this.CollectCookiesFromHeaderString(header);
    }

    /// <summary>
    /// Adjust the URI to match the RFC specification (no query string!!).
    /// </summary>
    /// <param name="uri">
    /// The original URI. 
    /// </param>
    /// <returns>
    /// The adjusted URI. 
    /// </returns>
    private static Uri UriAdjuster(Uri uri)
    {
        return
            new Uri(
                string.Format(
                    "{0}://{1}{2}{3}", 
                    uri.Scheme, 
                    uri.Host, 
                    uri.IsDefaultPort ?
                        string.Empty :
                        string.Format(":{0}", uri.Port), 
                    uri.AbsolutePath));
    }
}

4) Use this tutorial for creating an OAuth provider: http://code.google.com/p/devdefined-tools/wiki/OAuthProvider. In the last step (Accessing Protected Resource Example) you can use this code in your AuthorizationFilterAttribute attribute:

public override void OnAuthorization(HttpActionContext actionContext)
{
    // the only change I made is use the custom context builder from step 3:
    OAuthContext context = 
        new WebApiOAuthContextBuilder().FromHttpRequest(actionContext.Request);

    try
    {
        provider.AccessProtectedResourceRequest(context);

        // do nothing here
    }
    catch (OAuthException authEx)
    {
        // the OAuthException's Report property is of the type "OAuthProblemReport", it's ToString()
        // implementation is overloaded to return a problem report string as per
        // the error reporting OAuth extension: http://wiki.oauth.net/ProblemReporting
        actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
            {
               RequestMessage = request, ReasonPhrase = authEx.Report.ToString()
            };
    }
}

I have implemented my own provider so I haven't tested the above code (except of course the WebApiOAuthContextBuilder which I'm using in my provider) but it should work fine.

Input mask for numeric and decimal

Try imaskjs. It has Number, RegExp and other masks. Very simple to extend.

How can I verify if one list is a subset of another?

Here is how I know if one list is a subset of another one, the sequence matters to me in my case.

def is_subset(list_long,list_short):
    short_length = len(list_short)
    subset_list = []
    for i in range(len(list_long)-short_length+1):
        subset_list.append(list_long[i:i+short_length])
    if list_short in subset_list:
        return True
    else: return False

Of Countries and their Cities

You can use database from here -

http://myip.ms/info/cities_sql_database/

CREATE TABLE `cities` (
  `cityID` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `cityName` varchar(50) NOT NULL,
  `stateID` smallint(5) unsigned NOT NULL DEFAULT '0',
  `countryID` varchar(3) NOT NULL DEFAULT '',
  `language` varchar(10) NOT NULL DEFAULT '',
  `latitude` double NOT NULL DEFAULT '0',
  `longitude` double NOT NULL DEFAULT '0',
  PRIMARY KEY (`cityID`),
  UNIQUE KEY `unq` (`countryID`,`stateID`,`cityID`),
  KEY `cityName` (`cityName`),
  KEY `stateID` (`stateID`),
  KEY `countryID` (`countryID`),
  KEY `latitude` (`latitude`),
  KEY `longitude` (`longitude`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

How to insert double and float values to sqlite?

I think you should give the data types of the column as NUMERIC or DOUBLE or FLOAT or REAL

Read http://sqlite.org/datatype3.html to more info.

How to detect if a stored procedure already exists

In addition to what has already been said I also like to add a different approach and advocate the use of differential script deployment strategy. Instead of making a stateful script that always checks the current state and acts based on that state, deploy via a series of stateless scripts that upgrade from well known versions. I have used this strategy and it pays off big time as my deployment scripts are now all 'IF' free.

Tomcat: How to find out running tomcat version

run the following

/usr/local/tomcat/bin/catalina.sh version

its response will be something like:

Using CATALINA_BASE:   /usr/local/tomcat
Using CATALINA_HOME:   /usr/local/tomcat
Using CATALINA_TMPDIR: /var/tmp/
Using JRE_HOME:        /usr
Using CLASSPATH:       /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Using CATALINA_PID:    /var/catalina.pid
Server version: Apache Tomcat/7.0.30
Server built:   Sep 27 2012 05:13:37
Server number:  7.0.30.0
OS Name:        Linux
OS Version:     2.6.32-504.3.3.el6.x86_64
Architecture:   amd64
JVM Version:    1.7.0_60-b19
JVM Vendor:     Oracle Corporation

Calculate average in java

public class MainTwo{
    public static void main(String[] arguments) {
        double[] Average = new double[5];
        Average[0] = 4;
        Average[1] = 5;
        Average[2] = 2;
        Average[3] = 4;
        Average[4] = 5;
        double sum = 0;
        if (Average.length > 0) {
            for (int x = 0; x < Average.length; x++) {
                sum+=Average[x];
                System.out.println(Average[x]);
            }
            System.out.println("Sum is " + sum);
            System.out.println("Average is " + sum/Average.length);
      }
   }
}

ReferenceError: fetch is not defined

The following works for me in Node.js 12.x:

npm i node-fetch;

to initialize the Dropbox instance:

var Dropbox = require("dropbox").Dropbox;
var dbx = new Dropbox({
   accessToken: <your access token>,
   fetch: require("node-fetch")    
});

to e.g. upload a content (an asynchronous method used in this case):

await dbx.filesUpload({
  contents: <your content>,
  path: <file path>
});

Send an Array with an HTTP Get

That depends on what the target server accepts. There is no definitive standard for this. See also a.o. Wikipedia: Query string:

While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field (e.g. field1=value1&field1=value2&field2=value3).[4][5]

Generally, when the target server uses a strong typed programming language like Java (Servlet), then you can just send them as multiple parameters with the same name. The API usually offers a dedicated method to obtain multiple parameter values as an array.

foo=value1&foo=value2&foo=value3
String[] foo = request.getParameterValues("foo"); // [value1, value2, value3]

The request.getParameter("foo") will also work on it, but it'll return only the first value.

String foo = request.getParameter("foo"); // value1

And, when the target server uses a weak typed language like PHP or RoR, then you need to suffix the parameter name with braces [] in order to trigger the language to return an array of values instead of a single value.

foo[]=value1&foo[]=value2&foo[]=value3
$foo = $_GET["foo"]; // [value1, value2, value3]
echo is_array($foo); // true

In case you still use foo=value1&foo=value2&foo=value3, then it'll return only the first value.

$foo = $_GET["foo"]; // value1
echo is_array($foo); // false

Do note that when you send foo[]=value1&foo[]=value2&foo[]=value3 to a Java Servlet, then you can still obtain them, but you'd need to use the exact parameter name including the braces.

String[] foo = request.getParameterValues("foo[]"); // [value1, value2, value3]

sudo: docker-compose: command not found

I will leave this here as a possible fix, worked for me at least and might help others. Pretty sure this would be a linux only fix.

I decided to not go with the pip install and go with the github version (option one on the installation guide).

Instead of placing the copied docker-compose directory into /usr/local/bin/docker-compose from the curl/github command, I went with /usr/bin/docker-compose which is the location of Docker itself and will force the program to run in root. So it works in root and sudo but now won't work without sudo so the opposite effect which is what you want to run it as a user anyways.

Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java

I'm not sure why your current code is failing (what is the Exception you get?), but I would like to point out this approach performs O(N-squared). Consider pre-sorting your input arrays (if they are not defined to be pre-sorted) and merging the sorted arrays:

http://www.algolist.net/Algorithms/Merge/Sorted_arrays

Sorting is generally O(N logN) and the merge is O(m+n).

Detect encoding and make everything UTF-8

You need to test the character set on input since responses can come coded with different encodings.

I force all content been sent into UTF-8 by doing detection and translation using the following function:

function fixRequestCharset()
{
  $ref = array(&$_GET, &$_POST, &$_REQUEST);
  foreach ($ref as &$var)
  {
    foreach ($var as $key => $val)
    {
      $encoding = mb_detect_encoding($var[$key], mb_detect_order(), true);
      if (!$encoding)
        continue;
      if (strcasecmp($encoding, 'UTF-8') != 0)
      {
        $encoding = iconv($encoding, 'UTF-8', $var[$key]);
        if ($encoding === false)
          continue;
        $var[$key] = $encoding;
      }
    }
  }
}

That routine will turn all PHP variables that come from the remote host into UTF-8.

Or ignore the value if the encoding could not be detected or converted.

You can customize it to your needs.

Just invoke it before using the variables.

Get age from Birthdate

JsFiddle

You can calculate with Dates.

var birthdate = new Date("1990/1/1");
var cur = new Date();
var diff = cur-birthdate; // This is the difference in milliseconds
var age = Math.floor(diff/31557600000); // Divide by 1000*60*60*24*365.25

Python: Importing urllib.quote

This is how I handle this, without using exceptions.

import sys
if sys.version_info.major > 2:  # Python 3 or later
    from urllib.parse import quote
else:  # Python 2
    from urllib import quote

php $_POST array empty upon form submission

Having the enable_post_data_reading setting disabled will cause this. According to the documentation:

enable_post_data_reading

Disabling this option causes $_POST and $_FILES not to be populated. The only way to read postdata will then be through the php://input stream wrapper. This can be useful to proxy requests or to process the POST data in a memory efficient fashion.

How to add hyperlink in JLabel?

I'd like to offer yet another solution. It's similar to the already proposed ones as it uses HTML-code in a JLabel, and registers a MouseListener on it, but it also displays a HandCursor when you move the mouse over the link, so the look&feel is just like what most users would expect. If browsing is not supported by the platform, no blue, underlined HTML-link is created that could mislead the user. Instead, the link is just presented as plain text. This could be combined with the SwingLink class proposed by @dimo414.

public class JLabelLink extends JFrame {

private static final String LABEL_TEXT = "For further information visit:";
private static final String A_VALID_LINK = "http://stackoverflow.com";
private static final String A_HREF = "<a href=\"";
private static final String HREF_CLOSED = "\">";
private static final String HREF_END = "</a>";
private static final String HTML = "<html>";
private static final String HTML_END = "</html>";

public JLabelLink() {
    setTitle("HTML link via a JLabel");
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    Container contentPane = getContentPane();
    contentPane.setLayout(new FlowLayout(FlowLayout.LEFT));

    JLabel label = new JLabel(LABEL_TEXT);
    contentPane.add(label);

    label = new JLabel(A_VALID_LINK);
    contentPane.add(label);
    if (isBrowsingSupported()) {
        makeLinkable(label, new LinkMouseListener());
    }

    pack();
}

private static void makeLinkable(JLabel c, MouseListener ml) {
    assert ml != null;
    c.setText(htmlIfy(linkIfy(c.getText())));
    c.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
    c.addMouseListener(ml);
}

private static boolean isBrowsingSupported() {
    if (!Desktop.isDesktopSupported()) {
        return false;
    }
    boolean result = false;
    Desktop desktop = java.awt.Desktop.getDesktop();
    if (desktop.isSupported(Desktop.Action.BROWSE)) {
        result = true;
    }
    return result;

}

private static class LinkMouseListener extends MouseAdapter {

    @Override
    public void mouseClicked(java.awt.event.MouseEvent evt) {
        JLabel l = (JLabel) evt.getSource();
        try {
            URI uri = new java.net.URI(JLabelLink.getPlainLink(l.getText()));
            (new LinkRunner(uri)).execute();
        } catch (URISyntaxException use) {
            throw new AssertionError(use + ": " + l.getText()); //NOI18N
        }
    }
}

private static class LinkRunner extends SwingWorker<Void, Void> {

    private final URI uri;

    private LinkRunner(URI u) {
        if (u == null) {
            throw new NullPointerException();
        }
        uri = u;
    }

    @Override
    protected Void doInBackground() throws Exception {
        Desktop desktop = java.awt.Desktop.getDesktop();
        desktop.browse(uri);
        return null;
    }

    @Override
    protected void done() {
        try {
            get();
        } catch (ExecutionException ee) {
            handleException(uri, ee);
        } catch (InterruptedException ie) {
            handleException(uri, ie);
        }
    }

    private static void handleException(URI u, Exception e) {
        JOptionPane.showMessageDialog(null, "Sorry, a problem occurred while trying to open this link in your system's standard browser.", "A problem occured", JOptionPane.ERROR_MESSAGE);
    }
}

private static String getPlainLink(String s) {
    return s.substring(s.indexOf(A_HREF) + A_HREF.length(), s.indexOf(HREF_CLOSED));
}

//WARNING
//This method requires that s is a plain string that requires
//no further escaping
private static String linkIfy(String s) {
    return A_HREF.concat(s).concat(HREF_CLOSED).concat(s).concat(HREF_END);
}

//WARNING
//This method requires that s is a plain string that requires
//no further escaping
private static String htmlIfy(String s) {
    return HTML.concat(s).concat(HTML_END);
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            new JLabelLink().setVisible(true);
        }
    });
}
}

What is the difference between "expose" and "publish" in Docker?

Most people use docker compose with networks. The documentation states:

The Docker network feature supports creating networks without the need to expose ports within the network, for detailed information see the overview of this feature).

Which means that if you use networks for communication between containers you don't need to worry about exposing ports.

How to bind an enum to a combobox control in WPF?

I just kept it simple. I created a list of items with the enum values in my ViewModel:

public enum InputsOutputsBoth
{
    Inputs,
    Outputs,
    Both
}

private IList<InputsOutputsBoth> _ioTypes = new List<InputsOutputsBoth>() 
{ 
    InputsOutputsBoth.Both, 
    InputsOutputsBoth.Inputs, 
    InputsOutputsBoth.Outputs 
};

public IEnumerable<InputsOutputsBoth> IoTypes
{
    get { return _ioTypes; }
    set { }
}

private InputsOutputsBoth _selectedIoType;

public InputsOutputsBoth SelectedIoType
{
    get { return _selectedIoType; }
    set
    {
        _selectedIoType = value;
        OnPropertyChanged("SelectedIoType");
        OnSelectionChanged();
    }
}

In my xaml code I just need this:

<ComboBox ItemsSource="{Binding IoTypes}" SelectedItem="{Binding SelectedIoType, Mode=TwoWay}">

How to create a function in SQL Server

How about this?

CREATE FUNCTION dbo.StripWWWandCom (@input VARCHAR(250))
RETURNS VARCHAR(250)
AS BEGIN
    DECLARE @Work VARCHAR(250)

    SET @Work = @Input

    SET @Work = REPLACE(@Work, 'www.', '')
    SET @Work = REPLACE(@Work, '.com', '')

    RETURN @work
END

and then use:

SELECT ID, dbo.StripWWWandCom (WebsiteName)
FROM dbo.YourTable .....

Of course, this is severely limited in that it will only strip www. at the beginning and .com at the end - nothing else (so it won't work on other host machine names like smtp.yahoo.com and other internet domains such as .org, .edu, .de and etc.)

Inserting HTML elements with JavaScript

To my knowledge, which, to be fair, is fairly new and limited, the only potential issue with this technique is the fact that you are prevented from dynamically creating some table elements.

I use a form to templating by adding "template" elements to a hidden DIV and then using cloneNode(true) to create a clone and appending it as required. Bear in ind that you do need to ensure you re-assign id's as required to prevent duplication.

intellij idea - Error: java: invalid source release 1.9

Select the project, then File > ProjectStructure > ProjectSettings > Modules -> sources You probably have the Language Level set at 9:

screenshot

Just change it to 8 (or whatever you need) and you're set to go.

Also, check the same Language Level settings mentioned above, under Project Settings > Project

enter image description here

vertical align middle in <div>

_x000D_
_x000D_
 div {_x000D_
    height:200px;_x000D_
    text-align: center;_x000D_
    padding: 2px;_x000D_
    border: 1px solid #000;_x000D_
    background-color: green;_x000D_
}_x000D_
_x000D_
.text-align-center {_x000D_
    display: flex;_x000D_
    align-items: center;_x000D_
    justify-content: center;_x000D_
}
_x000D_
<div class="text-align-center"> Align center</div>
_x000D_
_x000D_
_x000D_

Convert string in base64 to image and save on filesystem in Python

If you are trying to decode a web image you can simply use this :

import base64

with open("imageToSave.png", "wb") as fh:
  fh.write(base64.urlsafe_b64decode('data'))

data => is the encoded string

It will take care of the padding errors

Return a string method in C#

You don't have to have a method for that. You could create a property like this instead:

class SalesPerson
{
    string firstName, lastName;
    public string FirstName { get { return firstName; } set { firstName = value; } }
    public string LastName { get { return lastName; } set { lastName = value; } }
    public string FullName { get { return this.FirstName + " " + this.LastName; } }
}

The class could even be shortened to:

class SalesPerson
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName { 
       get { return this.FirstName + " " + this.LastName; } 
    }
}

The property could then be accessed like any other property:

class Program
{
    static void Main(string[] args)
    {
        SalesPerson x = new SalesPerson("John", "Doe");
        Console.WriteLine(x.FullName); // Will print John Doe
    }
}

Diff files present in two different directories

If you are only interested to see the files that differ, you may use:

diff -qr dir_one dir_two | sort

Option "q" will only show the files that differ but not the content that differ, and "sort" will arrange the output alphabetically.