Programs & Examples On #Plural

Pertaining to handling text that must change depending on the number of items involved, according to the rules of different languages.

Enum Naming Convention - Plural

This is one of the few places that I disagree with the convention enough to go against it. TBH, I HATE that the definition of an enum and the instance of it can have the same name. I postfix all of my Enums with "Enum" specifically because it makes it clear what the context of it is in any given usage. IMO it makes the code much more readable.

public enum PersonTypesEnum {
    smart,
    sad,
    funny,
    angry
}


public class Person {   
    public PersonTypesEnum PersonType {get; set;}
}

Nobody will ever confuse what is the enum and what is the instance of it.

How to center form in bootstrap 3

I tried this and it worked

_x000D_
_x000D_
<div class="container">_x000D_
 <div class="row justify-content-center">_x000D_
  <div class="form-group col-md-4 col-md-offset-5 align-center ">_x000D_
       <input type="text" name="username" placeholder="Username" >_x000D_
  </div>_x000D_
 </div> _x000D_
</div>
_x000D_
_x000D_
_x000D_

Difference between .dll and .exe?

Dll v/s Exe

1)DLL file is a dynamic link library which can be used in exe files and other dll files.
EXE file is a executable file which runs in a separate process which is managed by OS.

2)DLLs are not directly executable . They are separate files containing functions that can be called by programs and other DLLs to perform computations and functions.
An EXE is a program that can be executed . Ex :Windows program

3)Reusability
DLL: They can be reused for some other application. As long as the coder knows the names and parameters of the functions and procedures in the DLL file .
EXE: Only for specific purpose .

4)A DLL would share the same process and memory space of the calling application while an
EXE creates its separate process and memory space.

5)Uses
DLL: You want many applications to use it but you don't want to give them the source code You can't copy-paste the code for the button in every program, so you decide you want to create a DL-Library (DLL).

EXE: When we work with project templates like Windows Forms Applications, Console Applications, WPF Applications and Windows Services they generate an exe assembly when compiled.

6)Similarities :
Both DLL and EXE are binary files have a complex nested structure defined by the Portable Executable format, and they are not intended to be editable by users.

'tsc command not found' in compiling typescript

If your TSC command is not found in MacOS after proper installation of TypeScript (using the following command: $ sudo npm install -g typescript, then ensure Node /bin path is added to the PATH variable in .bash_profile.

Open .bash_profile using terminal: $ open ~/.bash_profile;

Edit/Verify bash profile to include the following line (using your favorite text editor):

export PATH="$PATH:"/usr/local/lib/node_modules/node/bin"";

Load the latest bash profile using terminal: source ~/.bash_profile;

Lastly, try the command: $ tsc --version.

Get index of element as child relative to parent

Take a look at this example.

$("#wizard li").click(function () {
    alert($(this).index()); // alert index of li relative to ul parent
});

Throw away local commits in Git

If your excess commits are only visible to you, you can just do git reset --hard origin/<branch_name> to move back to where the origin is. This will reset the state of the repository to the previous commit, and it will discard all local changes.

Doing a git revert makes new commits to remove old commits in a way that keeps everyone's history sane.

Saving a Numpy array as an image

for saving a numpy array as image, U have several choices:

1) best of other: OpenCV

 import cv2   
 cv2.imwrite('file name with extension(like .jpg)', numpy_array)

2) Matplotlib

  from matplotlib import pyplot as plt
  plt.imsave('file name with extension(like .jpg)', numpy_array)

3) PIL

  from PIL import Image
  image = Image.fromarray(numpy_array)
  image.save('file name with extension(like .jpg)')

4) ...

Android disable screen timeout while app is running

Its importante to note that these methods all must be run from the UI thread to work. See changing KeepScreenOn from javascript in Android cordova app

Regex to match a 2-digit number (to validate Credit/Debit Card Issue number)

You can use the start (^) and end ($) of line indicators:

^[0-9]{2}$

Some language also have functions that allows you to match against an entire string, where-as you were using a find function. Matching against the entire string will make your regex work as an alternative to the above. The above regex will also work, but the ^ and $ will be redundant.

Defining Z order of views of RelativeLayout in Android

I encountered the same issues: In a relative layout parentView, I have 2 children childView1 and childView2. At first, I put childView1 above childView2 and I want childView1 to be on top of childView2. Changing the order of children views did not solve the problem for me. What worked for me is to set android:clipChildren="false" on parentView and in the code I set:

childView1.bringToFront();

parentView.invalidate();

Oracle: how to UPSERT (update or insert into a table?)

A note regarding the two solutions that suggest:

1) Insert, if exception then update,

or

2) Update, if sql%rowcount = 0 then insert

The question of whether to insert or update first is also application dependent. Are you expecting more inserts or more updates? The one that is most likely to succeed should go first.

If you pick the wrong one you will get a bunch of unnecessary index reads. Not a huge deal but still something to consider.

Updating a dataframe column in spark

While you cannot modify a column as such, you may operate on a column and return a new DataFrame reflecting that change. For that you'd first create a UserDefinedFunction implementing the operation to apply and then selectively apply that function to the targeted column only. In Python:

from pyspark.sql.functions import UserDefinedFunction
from pyspark.sql.types import StringType

name = 'target_column'
udf = UserDefinedFunction(lambda x: 'new_value', StringType())
new_df = old_df.select(*[udf(column).alias(name) if column == name else column for column in old_df.columns])

new_df now has the same schema as old_df (assuming that old_df.target_column was of type StringType as well) but all values in column target_column will be new_value.

Could not extract response: no suitable HttpMessageConverter found for response type

Since you return to the client just String and its content type == 'text/plain', there is no any chance for default converters to determine how to convert String response to the FFSampleResponseHttp object.

The simple way to fix it:

  • remove expected-response-type from <int-http:outbound-gateway>
  • add to the replyChannel1 <json-to-object-transformer>

Otherwise you should write your own HttpMessageConverter to convert the String to the appropriate object.

To make it work with MappingJackson2HttpMessageConverter (one of default converters) and your expected-response-type, you should send your reply with content type = 'application/json'.

If there is a need, just add <header-enricher> after your <service-activator> and before sending a reply to the <int-http:inbound-gateway>.

So, it's up to you which solution to select, but your current state doesn't work, because of inconsistency with default configuration.

UPDATE

OK. Since you changed your server to return FfSampleResponseHttp object as HTTP response, not String, just add contentType = 'application/json' header before sending the response for the HTTP and MappingJackson2HttpMessageConverter will do the stuff for you - your object will be converted to JSON and with correct contentType header.

From client side you should come back to the expected-response-type="com.mycompany.MyChannel.model.FFSampleResponseHttp" and MappingJackson2HttpMessageConverter should do the stuff for you again.

Of course you should remove <json-to-object-transformer> from you message flow after <int-http:outbound-gateway>.

Convert dictionary to list collection in C#

Alternatively:

var keys = new List<string>(dicNumber.Keys);

Update index after sorting data-frame

You can set new indices by using set_index:

df2.set_index(np.arange(len(df2.index)))

Output:

   x  y
0  0  0
1  0  1
2  0  2
3  1  0
4  1  1
5  1  2
6  2  0
7  2  1
8  2  2

What's the difference between display:inline-flex and display:flex?

flex and inline-flex both apply flex layout to children of the container. Container with display:flex behaves like a block-level element itself, while display:inline-flex makes the container behaves like an inline element.

java.math.BigInteger cannot be cast to java.lang.Long

Your error might be in this line:

List<Long> result = query.list();

where query.list() is returning a BigInteger List instead of Long list. Try to change it to.

List<BigInteger> result = query.list();

How can I analyze a heap dump in IntelliJ? (memory leak)

You can just run "Java VisualVM" which is located at jdk/bin/jvisualvm.exe

This will open a GUI, use the "File" menu -> "Load..." then choose your *.hprof file

That's it, you're done!

Using Jquery Datatable with AngularJs

Take a look at this: AngularJS+JQuery(datatable)

FULL code: http://jsfiddle.net/zdam/7kLFU/

JQuery Datatables's Documentation: http://www.datatables.net/

var dialogApp = angular.module('tableExample', []);

    dialogApp.directive('myTable', function() {
        return function(scope, element, attrs) {

            // apply DataTable options, use defaults if none specified by user
            var options = {};
            if (attrs.myTable.length > 0) {
                options = scope.$eval(attrs.myTable);
            } else {
                options = {
                    "bStateSave": true,
                    "iCookieDuration": 2419200, /* 1 month */
                    "bJQueryUI": true,
                    "bPaginate": false,
                    "bLengthChange": false,
                    "bFilter": false,
                    "bInfo": false,
                    "bDestroy": true
                };
            }

            // Tell the dataTables plugin what columns to use
            // We can either derive them from the dom, or use setup from the controller           
            var explicitColumns = [];
            element.find('th').each(function(index, elem) {
                explicitColumns.push($(elem).text());
            });
            if (explicitColumns.length > 0) {
                options["aoColumns"] = explicitColumns;
            } else if (attrs.aoColumns) {
                options["aoColumns"] = scope.$eval(attrs.aoColumns);
            }

            // aoColumnDefs is dataTables way of providing fine control over column config
            if (attrs.aoColumnDefs) {
                options["aoColumnDefs"] = scope.$eval(attrs.aoColumnDefs);
            }

            if (attrs.fnRowCallback) {
                options["fnRowCallback"] = scope.$eval(attrs.fnRowCallback);
            }

            // apply the plugin
            var dataTable = element.dataTable(options);



            // watch for any changes to our data, rebuild the DataTable
            scope.$watch(attrs.aaData, function(value) {
                var val = value || null;
                if (val) {
                    dataTable.fnClearTable();
                    dataTable.fnAddData(scope.$eval(attrs.aaData));
                }
            });
        };
    });

function Ctrl($scope) {

    $scope.message = '';            

        $scope.myCallback = function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {            
            $('td:eq(2)', nRow).bind('click', function() {
                $scope.$apply(function() {
                    $scope.someClickHandler(aData);
                });
            });
            return nRow;
        };

        $scope.someClickHandler = function(info) {
            $scope.message = 'clicked: '+ info.price;
        };

        $scope.columnDefs = [ 
            { "mDataProp": "category", "aTargets":[0]},
            { "mDataProp": "name", "aTargets":[1] },
            { "mDataProp": "price", "aTargets":[2] }
        ]; 

        $scope.overrideOptions = {
            "bStateSave": true,
            "iCookieDuration": 2419200, /* 1 month */
            "bJQueryUI": true,
            "bPaginate": true,
            "bLengthChange": false,
            "bFilter": true,
            "bInfo": true,
            "bDestroy": true
        };


        $scope.sampleProductCategories = [

              {
                "name": "1948 Porsche 356-A Roadster",
                "price": 53.9,
                  "category": "Classic Cars",
                  "action":"x"
              },
              {
                "name": "1948 Porsche Type 356 Roadster",
                "price": 62.16,
            "category": "Classic Cars",
                  "action":"x"
              },
              {
                "name": "1949 Jaguar XK 120",
                "price": 47.25,
            "category": "Classic Cars",
                  "action":"x"
              }
              ,
              {
                "name": "1936 Harley Davidson El Knucklehead",
                "price": 24.23,
            "category": "Motorcycles",
                  "action":"x"
              },
              {
                "name": "1957 Vespa GS150",
                "price": 32.95,
            "category": "Motorcycles",
                  "action":"x"
              },
              {
                "name": "1960 BSA Gold Star DBD34",
                "price": 37.32,
            "category": "Motorcycles",
                  "action":"x"
              }
           ,
              {
                "name": "1900s Vintage Bi-Plane",
                "price": 34.25,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "1900s Vintage Tri-Plane",
                "price": 36.23,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "1928 British Royal Navy Airplane",
                "price": 66.74,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "1980s Black Hawk Helicopter",
                "price": 77.27,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "ATA: B757-300",
                "price": 59.33,
            "category": "Planes",
                  "action":"x"
              }

        ];            

}

How to build a JSON array from mysql database

Just an update for Mysqli users :

$base= mysqli_connect($dbhost,  $dbuser, $dbpass, $dbbase);

if (mysqli_connect_errno()) 
  die('Could not connect: ' . mysql_error());

$return_arr = array();

if ($result = mysqli_query( $base, $sql )){
    while ($row = mysqli_fetch_assoc($result)) {
    $row_array['id'] = $row['id'];
    $row_array['col1'] = $row['col1'];
    $row_array['col2'] = $row['col2'];

    array_push($return_arr,$row_array);
   }
 }

mysqli_close($base);

echo json_encode($return_arr);

Responsive css background images

I think, the best way to do it is this:

body {
    font-family: Arial,Verdana,sans-serif;
    background:url("/images/image.jpg") no-repeat fixed bottom right transparent;
}

In this way there's no need to do nothing more and it's quite simple.

At least, it works for me.

I hope it helps.

how to take user input in Array using java?

import java.util.Scanner;

class bigest {
    public static void main (String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println ("how many number you want to put in the pot?");
        int num = input.nextInt();
        int numbers[] = new int[num];

        for (int i = 0; i < num; i++) {
            System.out.println ("number" + i + ":");
            numbers[i] = input.nextInt();
        }

        for (int temp : numbers){
            System.out.print (temp + "\t");
        }

        input.close();
    }
}

Property 'value' does not exist on type 'Readonly<{}>'

I suggest to use

for string only state values

export default class Home extends React.Component<{}, { [key: string]: string }> { }

for string key and any type of state values

export default class Home extends React.Component<{}, { [key: string]: any}> { }

for any key / any values

export default class Home extends React.Component<{}, { [key: any]: any}> {}

Google Maps JS API v3 - Simple Multiple Marker Example

Here is another example of multiple markers loading with a unique title and infoWindow text. Tested with the latest google maps API V3.11.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>Multiple Markers Google Maps</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
        <script src="https://maps.googleapis.com/maps/api/js?v=3.11&sensor=false" type="text/javascript"></script>
        <script type="text/javascript">
        // check DOM Ready
        $(document).ready(function() {
            // execute
            (function() {
                // map options
                var options = {
                    zoom: 5,
                    center: new google.maps.LatLng(39.909736, -98.522109), // centered US
                    mapTypeId: google.maps.MapTypeId.TERRAIN,
                    mapTypeControl: false
                };

                // init map
                var map = new google.maps.Map(document.getElementById('map_canvas'), options);

                // NY and CA sample Lat / Lng
                var southWest = new google.maps.LatLng(40.744656, -74.005966);
                var northEast = new google.maps.LatLng(34.052234, -118.243685);
                var lngSpan = northEast.lng() - southWest.lng();
                var latSpan = northEast.lat() - southWest.lat();

                // set multiple marker
                for (var i = 0; i < 250; i++) {
                    // init markers
                    var marker = new google.maps.Marker({
                        position: new google.maps.LatLng(southWest.lat() + latSpan * Math.random(), southWest.lng() + lngSpan * Math.random()),
                        map: map,
                        title: 'Click Me ' + i
                    });

                    // process multiple info windows
                    (function(marker, i) {
                        // add click event
                        google.maps.event.addListener(marker, 'click', function() {
                            infowindow = new google.maps.InfoWindow({
                                content: 'Hello, World!!'
                            });
                            infowindow.open(map, marker);
                        });
                    })(marker, i);
                }
            })();
        });
        </script>
    </head>
    <body>
        <div id="map_canvas" style="width: 800px; height:500px;"></div>
    </body>
</html>

Screenshot of 250 Markers:

Google Maps API V3.11 with Multiple Markers

It will automatically randomize the Lat/Lng to make it unique. This example will be very helpful if you want to test 500, 1000, xxx markers and performance.

How do I create ColorStateList programmatically?

Bouncing off the answer by Jonathan Ellis, in Kotlin you can define a helper function to make the code a bit more idiomatic and easier to read, so you can write this instead:

val colorList = colorStateListOf(
    intArrayOf(-android.R.attr.state_enabled) to Color.BLACK,
    intArrayOf(android.R.attr.state_enabled) to Color.RED,
)

colorStateListOf can be implemented like this:

fun colorStateListOf(vararg mapping: Pair<IntArray, Int>): ColorStateList {
    val (states, colors) = mapping.unzip()
    return ColorStateList(states.toTypedArray(), colors.toIntArray())
}

I also have:

fun colorStateListOf(@ColorInt color: Int): ColorStateList {
    return ColorStateList.valueOf(color)
}

So that I can call the same function name, no matter if it's a selector or single color.

In VBA get rid of the case sensitivity when comparing words?

There is a statement you can issue at the module level:

Option Compare Text

This makes all "text comparisons" case insensitive. This means the following code will show the message "this is true":

Option Compare Text

Sub testCase()
  If "UPPERcase" = "upperCASE" Then
    MsgBox "this is true: option Compare Text has been set!"
  End If
End Sub

See for example http://www.ozgrid.com/VBA/vba-case-sensitive.htm . I'm not sure it will completely solve the problem for all instances (such as the Application.Match function) but it will take care of all the if a=b statements. As for Application.Match - you may want to convert the arguments to either upper case or lower case using the LCase function.

How to save S3 object to a file using boto3

For those of you who would like to simulate the set_contents_from_string like boto2 methods, you can try

import boto3
from cStringIO import StringIO

s3c = boto3.client('s3')
contents = 'My string to save to S3 object'
target_bucket = 'hello-world.by.vor'
target_file = 'data/hello.txt'
fake_handle = StringIO(contents)

# notice if you do fake_handle.read() it reads like a file handle
s3c.put_object(Bucket=target_bucket, Key=target_file, Body=fake_handle.read())

For Python3:

In python3 both StringIO and cStringIO are gone. Use the StringIO import like:

from io import StringIO

To support both version:

try:
   from StringIO import StringIO
except ImportError:
   from io import StringIO

Xcode: failed to get the task for process

If anyone is having this issue but is sure they have their certificates and code signing correctly set up, check the capabilities tab when you click on the project (i.e. next to build settings tab, build phases tab, etc).

In my case there were broken links for Game Center and In-App Purchases that needed fixing (by clicking the "fix me" buttons) to solve this issue.

How to open new browser window on button click event?

You can use some code like this, you can adjust a height and width as per your need

    protected void button_Click(object sender, EventArgs e)
    {
        // open a pop up window at the center of the page.
        ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", "var Mleft = (screen.width/2)-(760/2);var Mtop = (screen.height/2)-(700/2);window.open( 'your_page.aspx', null, 'height=700,width=760,status=yes,toolbar=no,scrollbars=yes,menubar=no,location=no,top=\'+Mtop+\', left=\'+Mleft+\'' );", true);
    }

echo key and value of an array without and with loop

A recursive function for a change;) I use it to output the media information for videos etc elements of which can use nested array / attributes.

function custom_print_array($arr = array()) {
    $output = '';
    foreach($arr as $key => $val) {
        if(is_array($val)){
            $output .= '<li><strong>' . ucwords(str_replace('_',' ', $key)) . ':</strong><ul class="children">' . custom_print_array($val) . '</ul>' . '</li>';
        }
        else {
            $output .=  '<li><strong>' . ucwords(str_replace('_',' ', $key)) . ':</strong> ' . $val . '</li>';
        }
    }
    return $output;
}

Can't bind to 'formControl' since it isn't a known property of 'input' - Angular2 Material Autocomplete issue

Another reason this can happen:

The component you are using formControl in is not declared in a module that imports the ReactiveFormsModule.

So check the module that declares the component that throws this error.

Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

I resolved this issue by excluding byte-buddy dependency from springfox

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>2.7.0</version>
  <exclusions>
  <exclusion>
    <groupId>net.bytebuddy</groupId>
    <artifactId>byte-buddy</artifactId>
  </exclusion>
  </exclusions>
</dependency>

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>2.7.0</version>
  <exclusions>
  <exclusion>
    <groupId>net.bytebuddy</groupId>
    <artifactId>byte-buddy</artifactId>
  </exclusion>
</exclusions>
</dependency>

Impersonate tag in Web.Config

Put the identity element before the authentication element

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

How to convert column with dtype as object to string in Pandas Dataframe

since strings data types have variable length, it is by default stored as object dtype. If you want to store them as string type, you can do something like this.

df['column'] = df['column'].astype('|S80') #where the max length is set at 80 bytes,

or alternatively

df['column'] = df['column'].astype('|S') # which will by default set the length to the max len it encounters

How to deploy correctly when using Composer's develop / production switch?

Actually, I would highly recommend AGAINST installing dependencies on the production server.

My recommendation is to checkout the code on a deployment machine, install dependencies as needed (this includes NOT installing dev dependencies if the code goes to production), and then move all the files to the target machine.

Why?

  • on shared hosting, you might not be able to get to a command line
  • even if you did, PHP might be restricted there in terms of commands, memory or network access
  • repository CLI tools (Git, Svn) are likely to not be installed, which would fail if your lock file has recorded a dependency to checkout a certain commit instead of downloading that commit as ZIP (you used --prefer-source, or Composer had no other way to get that version)
  • if your production machine is more like a small test server (think Amazon EC2 micro instance) there is probably not even enough memory installed to execute composer install
  • while composer tries to no break things, how do you feel about ending with a partially broken production website because some random dependency could not be loaded during Composers install phase

Long story short: Use Composer in an environment you can control. Your development machine does qualify because you already have all the things that are needed to operate Composer.

What's the correct way to deploy this without installing the -dev dependencies?

The command to use is

composer install --no-dev

This will work in any environment, be it the production server itself, or a deployment machine, or the development machine that is supposed to do a last check to find whether any dev requirement is incorrectly used for the real software.

The command will not install, or actively uninstall, the dev requirements declared in the composer.lock file.

If you don't mind deploying development software components on a production server, running composer install would do the same job, but simply increase the amount of bytes moved around, and also create a bigger autoloader declaration.

ASP.NET Web API : Correct way to return a 401/unauthorised response

You get a 500 response code because you're throwing an exception (the HttpException) which indicates some kind of server error, this is the wrong approach.

Just set the response status code .e.g

Response.StatusCode = (int)HttpStatusCode.Unauthorized;

Why can't I use a list as a dict key in python?

The issue is that tuples are immutable, and lists are not. Consider the following

d = {}
li = [1,2,3]
d[li] = 5
li.append(4)

What should d[li] return? Is it the same list? How about d[[1,2,3]]? It has the same values, but is a different list?

Ultimately, there is no satisfactory answer. For example, if the only key that works is the original key, then if you have no reference to that key, you can never again access the value. With every other allowed key, you can construct a key without a reference to the original.

If both of my suggestions work, then you have very different keys that return the same value, which is more than a little surprising. If only the original contents work, then your key will quickly go bad, since lists are made to be modified.

Vertically align text next to an image?

Multiline solution:

http://jsfiddle.net/zH58L/6/

<div style="display:table;width:30px;height:160px;">
    <img style="display:table-cell;width:30px;height:60px;padding:50px" src='...' />
    <div style="display:table-cell;height:30px;vertical-align:middle">
      Multiline text centered vertically
    </div>
</div>
<!-- note: img (height + 2x padding) must be equal to root div height -->

Works in all browers and ie9+

Cannot set property 'display' of undefined

I've found this answer in the site https://plainjs.com/javascript/styles/set-and-get-css-styles-of-elements-53/.

In this code we add multiple styles in an element:

_x000D_
_x000D_
let_x000D_
    element = document.querySelector('span')_x000D_
  , cssStyle = (el, styles) => {_x000D_
      for (var property in styles) {_x000D_
          el.style[property] = styles[property];_x000D_
      }_x000D_
  }_x000D_
;_x000D_
_x000D_
cssStyle(element, { background:'tomato', color: 'white', padding: '0.5rem 1rem'});
_x000D_
span{_x000D_
font-family: sans-serif;_x000D_
color: #323232;_x000D_
background: #fff;_x000D_
}
_x000D_
<span>_x000D_
lorem ipsum_x000D_
</span>
_x000D_
_x000D_
_x000D_

Long press on UITableView

Just add UILongPressGestureRecognizer to the given prototype cell in storyboard, then pull the gesture to the viewController's .m file to create an action method. I made it as I said.

Set proxy through windows command line including login parameters

The best way around this is (and many other situations) in my experience, is to use cntlm which is a local no-authentication proxy which points to a remote authentication proxy. You can then just set WinHTTP to point to your local CNTLM (usually localhost:3128), and you can set CNTLM itself to point to the remote authentication proxy. CNTLM has a "magic NTLM dialect detection" option which generates password hashes to be put into the CNTLM configuration files.

Query for documents where array size is greater than 1

There's a more efficient way to do this in MongoDB 2.2+ now that you can use numeric array indexes in query object keys.

// Find all docs that have at least two name array elements.
db.accommodations.find({'name.1': {$exists: true}})

You can support this query with an index that uses a partial filter expression (requires 3.2+):

// index for at least two name array elements
db.accommodations.createIndex(
    {'name.1': 1},
    {partialFilterExpression: {'name.1': {$exists: true}}}
);

How to exclude file only from root folder in Git

If the above solution does not work for you, try this:

#1.1 Do NOT ignore file pattern in  any subdirectory
!*/config.php
#1.2 ...only ignore it in the current directory
/config.php

##########################

# 2.1 Ignore file pattern everywhere
config.php
# 2.2 ...but NOT in the current directory
!/config.php

How to connect to a remote Windows machine to execute commands using python?

I don't know WMI but if you want a simple Server/Client, You can use this simple code from tutorialspoint

Server:

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                # Close the connection 

Client

#!/usr/bin/python           # This is client.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close                     # Close the socket when done

it also have all the needed information for simple client/server applications.

Just convert the server and use some simple protocol to call a function from python.

P.S: i'm sure there are a lot of better options, it's just a simple one if you want...

Check if a div exists with jquery

If you are simply checking for the existence of an ID, there is no need to go into jQuery, you could simply:

if(document.getElementById("yourid") !== null)
{
}

getElementById returns null if it can't be found.

Reference.

If however you plan to use the jQuery object later i'd suggest:

$(document).ready(function() {
    var $myDiv = $('#DivID');

    if ( $myDiv.length){
        //you can now reuse  $myDiv here, without having to select it again.
    }


});

A selector always returns a jQuery object, so there shouldn't be a need to check against null (I'd be interested if there is an edge case where you need to check for null - but I don't think there is).

If the selector doesn't find anything then length === 0 which is "falsy" (when converted to bool its false). So if it finds something then it should be "truthy" - so you don't need to check for > 0. Just for it's "truthyness"

Bash scripting missing ']'

If you created your script on windows and want to run it on linux machine, and you're sure there is no mistake in your code, install dos2unix on linux machine and run dos2unix yourscript.sh. Then, run the script.

jQuery show for 5 seconds then hide

You can use .delay() before an animation, like this:

$("#myElem").show().delay(5000).fadeOut();

If it's not an animation, use setTimeout() directly, like this:

$("#myElem").show();
setTimeout(function() { $("#myElem").hide(); }, 5000);

You do the second because .hide() wouldn't normally be on the animation (fx) queue without a duration, it's just an instant effect.

Or, another option is to use .delay() and .queue() yourself, like this:

$("#myElem").show().delay(5000).queue(function(n) {
  $(this).hide(); n();
});

Full-screen iframe with a height of 100%

As per https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe, percentage values are no longer allowed. But the following worked for me

<iframe width="100%" height="this.height=window.innerHeight;" style="border:none" src=""></iframe>

Though width:100% works, height:100% does not work. So window.innerHeight has been used. You can also use css pixels for height.

Working code: Link Working site: Link

How to test abstract class in Java with JUnit?

I would create a jUnit inner class that inherits from the abstract class. This can be instantiated and have access to all the methods defined in the abstract class.

public class AbstractClassTest {
   public void testMethod() {
   ...
   }
}


class ConcreteClass extends AbstractClass {

}

How to strip all whitespace from string

For Python 3:

>>> import re
>>> re.sub(r'\s+', '', 'strip my \n\t\r ASCII and \u00A0 \u2003 Unicode spaces')
'stripmyASCIIandUnicodespaces'
>>> # Or, depending on the situation:
>>> re.sub(r'(\s|\u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF)+', '', \
... '\uFEFF\t\t\t strip all \u000A kinds of \u200B whitespace \n')
'stripallkindsofwhitespace'

...handles any whitespace characters that you're not thinking of - and believe us, there are plenty.

\s on its own always covers the ASCII whitespace:

  • (regular) space
  • tab
  • new line (\n)
  • carriage return (\r)
  • form feed
  • vertical tab

Additionally:

  • for Python 2 with re.UNICODE enabled,
  • for Python 3 without any extra actions,

...\s also covers the Unicode whitespace characters, for example:

  • non-breaking space,
  • em space,
  • ideographic space,

...etc. See the full list here, under "Unicode characters with White_Space property".

However \s DOES NOT cover characters not classified as whitespace, which are de facto whitespace, such as among others:

  • zero-width joiner,
  • Mongolian vowel separator,
  • zero-width non-breaking space (a.k.a. byte order mark),

...etc. See the full list here, under "Related Unicode characters without White_Space property".

So these 6 characters are covered by the list in the second regex, \u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF.

Sources:

How to push to History in React Router v4?

This is how I did it:

import React, {Component} from 'react';

export default class Link extends Component {
    constructor(props) {
        super(props);
        this.onLogout = this.onLogout.bind(this);
    }
    onLogout() {
        this.props.history.push('/');
    }
    render() {
        return (
            <div>
                <h1>Your Links</h1>
                <button onClick={this.onLogout}>Logout</button>
            </div>
        );
    }
}

Use this.props.history.push('/cart'); to redirect to cart page it will be saved in history object.

Enjoy, Michael.

How to compute the similarity between two text documents?

For Syntactic Similarity There can be 3 easy ways of detecting similarity.

  • Word2Vec
  • Glove
  • Tfidf or countvectorizer

For Semantic Similarity One can use BERT Embedding and try a different word pooling strategies to get document embedding and then apply cosine similarity on document embedding.

An advanced methodology can use BERT SCORE to get similarity. BERT SCORE

Research Paper Link: https://arxiv.org/abs/1904.09675

How to add key,value pair to dictionary?

I am not sure what you mean by "dynamic". If you mean adding items to a dictionary at runtime, it is as easy as dictionary[key] = value.

If you wish to create a dictionary with key,value to start with (at compile time) then use (surprise!)

dictionary[key] = value

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

Forcing the TCP/IP connection (by providing 127.0.0.1 instead of localhost or .) can reveal the real reason for the error. In my case, the database name specified in connection string was incorrect.

So, here is the checklist so far:

  • Make sure Named Pipe is enabled in configuration manager (don't forget to restart the server).
  • Make sure SQL Server Authentication (or Mixed Mode) is enabled.
  • Make sure your user name and password are correct.
  • Make sure the database you are connecting to exists.

Function names in C++: Capitalize or not?

Since C++11, you may want to use either snake_case or camelCase for function names.

This is because to make a class work as the range-expression in a range-based for-loop, you have to define functions called begin and end (case-sensitive) for that class.

Consequently, using e.g. PascalCase for function names means you have to break the naming consistency in your project if you ever need to make a class work with the range-based for.

SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error

In my case the servlet name defined in the web.xml was not same as the sevlet name in the servlet mapping tag. I have corrected this and the WAR was deployed successfully.

Get JSON Data from URL Using Android?

Don't know about android but in POJ I use

public final class MyJSONObject extends JSONObject {
    public MyJSONObject(URL url) throws IOException {
        super(getServerData(url));
    }
    static String getServerData(URL url) throws IOException {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        BufferedReader ir = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String text = ir.lines().collect(Collectors.joining("\n"));
        return (text);
    }
}

Disable/enable an input with jQuery?

You can put this somewhere global in your code:

$.prototype.enable = function () {
    $.each(this, function (index, el) {
        $(el).removeAttr('disabled');
    });
}

$.prototype.disable = function () {
    $.each(this, function (index, el) {
        $(el).attr('disabled', 'disabled');
    });
}

And then you can write stuff like:

$(".myInputs").enable();
$("#otherInput").disable();

Webclient / HttpWebRequest with Basic Authentication returns 404 not found for valid URL

This part of code worked fine for me:

        WebRequest request = WebRequest.Create(url);
        request.Method = WebRequestMethods.Http.Get;
        NetworkCredential networkCredential = new NetworkCredential(logon, password); // logon in format "domain\username"
        CredentialCache myCredentialCache = new CredentialCache {{new Uri(url), "Basic", networkCredential}};
        request.PreAuthenticate = true;
        request.Credentials = myCredentialCache;
        using (WebResponse response = request.GetResponse())
        {
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);

            using (Stream dataStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(dataStream))
                {
                    string responseFromServer = reader.ReadToEnd();
                    Console.WriteLine(responseFromServer);
                }
            }
        }

How can I wait In Node.js (JavaScript)? l need to pause for a period of time

let co = require('co');
const sleep = ms => new Promise(res => setTimeout(res, ms));

co(function*() {
    console.log('Welcome to My Console,');
    yield sleep(3000);
    console.log('Blah blah blah blah extra-blah');
});

This code above is the side effect of the solving Javascript's asynchronous callback hell problem. This is also the reason I think that makes Javascript a useful language in the backend. Actually this is the most exciting improvement introduced to modern Javascript in my opinion. To fully understand how it works, how generator works needs to be fully understood. The function keyword followed by a * is called a generator function in modern Javascript. The npm package co provided a runner function to run a generator.

Essentially generator function provided a way to pause the execution of a function with yield keyword, at the same time, yield in a generator function made it possible to exchange information between inside the generator and the caller. This provided a mechanism for the caller to extract data from a promise from an asynchronous call and to pass the resolved data back to the generator. Effectively, it makes an asynchronous call synchronous.

ERROR 1044 (42000): Access denied for 'root' With All Privileges

Try to comment string "sql-mode=..." in file my.cnf and than restart mysql.

Reading the selected value from asp:RadioButtonList using jQuery

this:

$('#rblDiv input').click(function(){
    alert($('#rblDiv input').index(this));
});

will get you the index of the radio button that was clicked (i think, untested) (note you've had to wrap your RBL in #rblDiv

you could then use that to display the corresponding div like this:

$('.divCollection div:eq(' + $('#rblDiv input').index(this) +')').show();

Is that what you meant?

Edit: Another approach would be to give the rbl a class name, then go:

$('.rblClass').val();

Sending email from Command-line via outlook without having to click send

Option 1
You didn't say much about your environment, but assuming you have it available you could use a PowerShell script; one example is here. The essence of this is:

$smtp = New-Object Net.Mail.SmtpClient("ho-ex2010-caht1.exchangeserverpro.net")
$smtp.Send("[email protected]","[email protected]","Test Email","This is a test")

You could then launch the script from the command line as per this example:

powershell.exe -noexit c:\scripts\test.ps1

Note that PowerShell 2.0, which is installed by default on Windows 7 and Windows Server 2008R2, includes a simpler Send-MailMessage command, making things easier.

Option 2
If you're prepared to use third-party software, is something line this SendEmail command-line tool. It depends on your target environment, though; if you're deploying your batch file to multiple machines, that will obviously require inclusion (but not formal installation) each time.

Option 3
You could drive Outlook directly from a VBA script, which in turn you would trigger from a batch file; this would let you send an email using Outlook itself, which looks to be closest to what you're wanting. There are two parts to this; first, figure out the VBA scripting required to send an email. There are lots of examples for this online, including from Microsoft here. Essence of this is:

Sub SendMessage(DisplayMsg As Boolean, Optional AttachmentPath)
    Dim objOutlook As Outlook.Application
    Dim objOutlookMsg As Outlook.MailItem
    Dim objOutlookRecip As Outlook.Recipient
    Dim objOutlookAttach As Outlook.Attachment

    Set objOutlook = CreateObject("Outlook.Application")
    Set objOutlookMsg  = objOutlook.CreateItem(olMailItem)

    With objOutlookMsg
        Set objOutlookRecip = .Recipients.Add("Nancy Davolio")
        objOutlookRecip.Type = olTo
        ' Set the Subject, Body, and Importance of the message.
        .Subject = "This is an Automation test with Microsoft Outlook"
        .Body = "This is the body of the message." &vbCrLf & vbCrLf
        .Importance = olImportanceHigh  'High importance

        If Not IsMissing(AttachmentPath) Then
            Set objOutlookAttach = .Attachments.Add(AttachmentPath)
        End If

        For Each ObjOutlookRecip In .Recipients
            objOutlookRecip.Resolve
        Next

        .Save
        .Send
    End With
    Set objOutlook = Nothing
End Sub

Then, launch Outlook from the command line with the /autorun parameter, as per this answer (alter path/macroname as necessary):

C:\Program Files\Microsoft Office\Office11\Outlook.exe" /autorun macroname

Option 4
You could use the same approach as option 3, but move the Outlook VBA into a PowerShell script (which you would run from a command line). Example here. This is probably the tidiest solution, IMO.

how to format date in Component of angular 5

There is equally formatDate

const format = 'dd/MM/yyyy';
const myDate = '2019-06-29';
const locale = 'en-US';
const formattedDate = formatDate(myDate, format, locale);

According to the API it takes as param either a date string, a Date object, or a timestamp.

Gotcha: Out of the box, only en-US is supported.

If you need to add another locale, you need to add it and register it in you app.module, for example for Spanish:

import { registerLocaleData } from '@angular/common';
import localeES from "@angular/common/locales/es";
registerLocaleData(localeES, "es");

Don't forget to add corresponding import:

import { formatDate } from "@angular/common";

one line if statement in php

Use ternary operator:

echo (($test == '') ? $redText : '');
echo $test == '' ? $redText : ''; //removed parenthesis

But in this case you can't use shorter reversed version because it will return bool(true) in first condition.

echo (($test != '') ?: $redText); //this will not work properly for this case

Java: get greatest common divisor

The % going to give us the gcd Between two numbers, it means:- % or mod of big_number/small_number are =gcd, and we write it on java like this big_number % small_number.

EX1: for two integers

  public static int gcd(int x1,int x2)
    {
        if(x1>x2)
        {
           if(x2!=0)
           {
               if(x1%x2==0)     
                   return x2;
                   return x1%x2;
                   }
           return x1;
           }
          else if(x1!=0)
          {
              if(x2%x1==0)
                  return x1;
                  return x2%x1;
                  }
        return x2;
        } 

EX2: for three integers

public static int gcd(int x1,int x2,int x3)
{

    int m,t;
    if(x1>x2)
        t=x1;
    t=x2;
    if(t>x3)
        m=t;
    m=x3;
    for(int i=m;i>=1;i--)
    {
        if(x1%i==0 && x2%i==0 && x3%i==0)
        {
            return i;
        }
    }
    return 1;
}

rails simple_form - hidden field - create?

Shortest Yet !!!

=f.hidden_field :title, :value => "some value"

Shorter, DRYer and perhaps more obvious.

Of course with ruby 1.9 and the new hash format we can go 3 characters shorter with...

=f.hidden_field :title, value: "some value"

How to concatenate strings in windows batch file for loop?

Try this, with strings:

set "var=string1string2string3"

and with string variables:

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

Reading/parsing Excel (xls) files with Python

    with open(csv_filename) as file:
        data = file.read()

    with open(xl_file_name, 'w') as file:
        file.write(data)

You can turn CSV to excel like above with inbuilt packages. CSV can be handled with an inbuilt package of dictreader and dictwriter which will work the same way as python dictionary works. which makes it a ton easy I am currently unaware of any inbuilt packages for excel but I had come across openpyxl. It was also pretty straight forward and simple You can see the code snippet below hope this helps

    import openpyxl
    book = openpyxl.load_workbook(filename)
    sheet = book.active 
    result =sheet['AP2']
    print(result.value)

Excel VBA code to copy a specific string to clipboard

If you want to put a variable's value in the clipboard using the Immediate window, you can use this single line to easily put a breakpoint in your code:

Set MSForms_DataObject = CreateObject("new:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}"): MSForms_DataObject.SetText VARIABLENAME: MSForms_DataObject.PutInClipboard: Set MSForms_DataObject = Nothing

Changing the JFrame title

If your class extends JFrame then use this.setTitle(newTitle.getText());

If not and it contains a JFrame let's say named myFrame, then use myFrame.setTitle(newTitle.getText());

Now that you have posted your program, it is obvious that you need only one JTextField to get the new title. These changes will do the trick:

JTextField poolLengthText, poolWidthText, poolDepthText, poolVolumeText, hotTub,
        hotTubLengthText, hotTubWidthText, hotTubDepthText, hotTubVolumeText, temp, results,
        newTitle;

and:

    public void createOptions()
    {
        options = new JPanel();
        options.setLayout(null);
        JLabel labelOptions = new JLabel("Change Company Name:");
        labelOptions.setBounds(120, 10, 150, 20);
        options.add(labelOptions);
        newTitle = new JTextField("Some Title");
        newTitle.setBounds(80, 40, 225, 20);
        options.add(newTitle);
//        myTitle = new JTextField("My Title...");
//        myTitle.setBounds(80, 40, 225, 20);
//        myTitle.add(labelOptions);
        JButton newName = new JButton("Set New Name");
        newName.setBounds(60, 80, 150, 20);
        newName.addActionListener(this);
        options.add(newName);
        JButton Exit = new JButton("Exit");
        Exit.setBounds(250, 80, 80, 20);
        Exit.addActionListener(this);
        options.add(Exit);
    }

and:

private void New_Name()
{
    this.setTitle(newTitle.getText());
}

Blurring an image via CSS?

With CSS3 we can easily adjust an image. But remember this does not change the image. It only displays the adjusted image.

See the following code for more details.

To make an image gray:

img {
 -webkit-filter: grayscale(100%);
}

To give a sepia look:

img {
 -webkit-filter: sepia(100%);
}

To adjust brightness:

img {
 -webkit-filter: brightness(50%);
}

To adjust contrast:

img {
 -webkit-filter: contrast(200%);
}

To Blur an image:

img {
 -webkit-filter: blur(10px);
}

You should also do it for different browser. That is include all css statements

  filter: grayscale(100%);
 -webkit-filter: grayscale(100%);
 -moz-filter: grayscale(100%);

To use multiple

 filter: blur(5px) grayscale(1);

Codepen Demo

How to refresh datagrid in WPF

Reload the datasource of your grid after the update

myGrid.ItemsSource = null;
myGrid.ItemsSource = myDataSource;

Copy and Paste a set range in the next empty row

You could also try this

Private Sub CommandButton1_Click()

Sheets("Sheet1").Range("A3:E3").Copy

Dim lastrow As Long
lastrow = Range("A65536").End(xlUp).Row

Sheets("Summary Info").Activate
Cells(lastrow + 1, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

End Sub

MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?

Delete all documents from a collection in cmd:

cd C:\Program Files\MongoDB\Server\4.2\bin
mongo
use yourdb
db.yourcollection.remove( { } )

jQuery: how to find first visible input/select/textarea excluding buttons?

Here is my solution. The code should be easy enough to follow but here is the idea:

  • get all inputs, selects, and textareas
  • filter out all buttons and hidden fields
  • filter to only enabled, visible fields
  • select the first one
  • focus the selected field

The code:

function focusFirst(parent) {
    $(parent).find('input, textarea, select')
        .not('input[type=hidden],input[type=button],input[type=submit],input[type=reset],input[type=image],button')
        .filter(':enabled:visible:first')
        .focus();
}

Then simply call focusFirst with your parent element or selector.

Selector:

focusFirst('form#aspnetForm');

Element:

var el = $('form#aspnetForm');
focusFirst(el);

Creating an Array from a Range in VBA

If we do it just like this:

Dim myArr as Variant
myArr = Range("A1:A10")

the new array will be with two dimensions. Which is not always somehow comfortable to work with:

enter image description here

To get away of the two dimensions, when getting a single column to array, we may use the built-in Excel function “Transpose”. With it, the data becomes in one dimension:

enter image description here

If we have the data in a row, a single transpose will not do the job. We need to use the Transpose function twice:

enter image description here

Note: As you see from the screenshots, when generated this way, arrays start with 1, not with 0. Just be a bit careful.

Set Page Title using PHP

Simply add $title variable before require function

<?php
    $title = "Your title goes here";
    require("header.php");
  ?>

header.php

<title><?php echo $title; ?></title>

Node.js - Maximum call stack size exceeded

In some languages this can be solved with tail call optimization, where the recursion call is transformed under the hood into a loop so no maximum stack size reached error exists.

But in javascript the current engines don't support this, it's foreseen for new version of the language Ecmascript 6.

Node.js has some flags to enable ES6 features but tail call is not yet available.

So you can refactor your code to implement a technique called trampolining, or refactor in order to transform recursion into a loop.

How to set Meld as git mergetool

After installing it http://meldmerge.org/ I had to tell git where it was:

git config --global merge.tool meld
git config --global diff.tool meld
git config --global mergetool.meld.path “C:\Program Files (x86)\Meld\meld.exe”

And that seems to work. Both merging and diffing with “git difftool” or “git mergetool”

If someone facing issue such as Meld crash after starting (problem indication with python) then you need to set up Meld/lib to your system environment variable as bellow C:\Program Files (x86)\Meld\lib

How to make two plots side-by-side using Python?

Check this page out: http://matplotlib.org/examples/pylab_examples/subplots_demo.html

plt.subplots is similar. I think it's better since it's easier to set parameters of the figure. The first two arguments define the layout (in your case 1 row, 2 columns), and other parameters change features such as figure size:

import numpy as np
import matplotlib.pyplot as plt

x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(5, 3))
axes[0].plot(x1, y1)
axes[1].plot(x2, y2)
fig.tight_layout()

enter image description here

Fetch API with Cookie

This works for me:

import Cookies from 'universal-cookie';
const cookies = new Cookies();

function headers(set_cookie=false) {
  let headers = {
    'Accept':       'application/json',
    'Content-Type': 'application/json',
    'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
};
if (set_cookie) {
    headers['Authorization'] = "Bearer " + cookies.get('remember_user_token');
}
return headers;
}

Then build your call:

export function fetchTests(user_id) {
  return function (dispatch) {
   let data = {
    method:      'POST',
    credentials: 'same-origin',
    mode:        'same-origin',
    body:        JSON.stringify({
                     user_id: user_id
                }),
    headers:     headers(true)
   };
   return fetch('/api/v1/tests/listing/', data)
      .then(response => response.json())
      .then(json => dispatch(receiveTests(json)));
    };
  }

No notification sound when sending notification from firebase in android

do like this

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    //codes..,.,,

    Uri sound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        builder.setSound(sound);

}

Import SQL dump into PostgreSQL database

I use:

cat /home/path/to/dump/file | psql -h localhost -U <user_name> -d <db_name>

Hope this will help someone.

Initialising a multidimensional array in Java

Java doesn't have "true" multidimensional arrays.

For example, arr[i][j][k] is equivalent to ((arr[i])[j])[k]. In other words, arr is simply an array, of arrays, of arrays.

So, if you know how arrays work, you know how multidimensional arrays work!


Declaration:

int[][][] threeDimArr = new int[4][5][6];

or, with initialization:

int[][][] threeDimArr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };

Access:

int x = threeDimArr[1][0][1];

or

int[][] row = threeDimArr[1];

String representation:

Arrays.deepToString(threeDimArr);

yields

"[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]"

Useful articles

Isn't the size of character in Java 2 bytes?

Java allocates 2 of 2 bytes for character as it follows UTF-16. It occupies minimum 2 bytes while storing a character, and maximum of 4 bytes. There is no 1 byte or 3 bytes of storage for character.

Opening Chrome From Command Line

you can create batch file and insert into it the bellow line:

cmd /k start chrome "http://yourWebSite.com

after that you do just double click on this batch file.

How to automatically crop and center an image

Try this: Set your image crop dimensions and use this line in your CSS:

object-fit: cover;

iOS application: how to clear notifications?

Update for iOS 10 (Swift 3)

In order to clear all local notifications in iOS 10 apps, you should use the following code:

import UserNotifications

...

if #available(iOS 10.0, *) {
    let center = UNUserNotificationCenter.current()
    center.removeAllPendingNotificationRequests() // To remove all pending notifications which are not delivered yet but scheduled.
    center.removeAllDeliveredNotifications() // To remove all delivered notifications
} else {
    UIApplication.shared.cancelAllLocalNotifications()
}

This code handles the clearing of local notifications for iOS 10.x and all preceding versions of iOS. You will need to import UserNotifications for the iOS 10.x code.

What is the newline character in the C language: \r or \n?

'\r' = carriage return and '\n' = line feed.

In fact, there are some different behaviors when you use them in different OSes. On Unix it is '\n', but it is '\r''\n' on Windows.

Getting and removing the first character of a string

See ?substring.

x <- 'hello stackoverflow'
substring(x, 1, 1)
## [1] "h"
substring(x, 2)
## [1] "ello stackoverflow"

The idea of having a pop method that both returns a value and has a side effect of updating the data stored in x is very much a concept from object-oriented programming. So rather than defining a pop function to operate on character vectors, we can make a reference class with a pop method.

PopStringFactory <- setRefClass(
  "PopString",
  fields = list(
    x = "character"  
  ),
  methods = list(
    initialize = function(x)
    {
      x <<- x
    },
    pop = function(n = 1)
    {
      if(nchar(x) == 0)
      {
        warning("Nothing to pop.")
        return("")
      }
      first <- substring(x, 1, n)
      x <<- substring(x, n + 1)
      first
    }
  )
)

x <- PopStringFactory$new("hello stackoverflow")
x
## Reference class object of class "PopString"
## Field "x":
## [1] "hello stackoverflow"
replicate(nchar(x$x), x$pop())
## [1] "h" "e" "l" "l" "o" " " "s" "t" "a" "c" "k" "o" "v" "e" "r" "f" "l" "o" "w"

What is Android keystore file, and what is it used for?

The answer I would provide is that a keystore file is to authenticate yourself to anyone who is asking. It isn't restricted to just signing .apk files, you can use it to store personal certificates, sign data to be transmitted and a whole variety of authentication.

In terms of what you do with it for Android and probably what you're looking for since you mention signing apk's, it is your certificate. You are branding your application with your credentials. You can brand multiple applications with the same key, in fact, it is recommended that you use one certificate to brand multiple applications that you write. It easier to keep track of what applications belong to you.

I'm not sure what you mean by implications. I suppose it means that no one but the holder of your certificate can update your application. That means that if you release it into the wild, lose the cert you used to sign the application, then you cannot release updates so keep that cert safe and backed up if need be.

But apart from signing apks to release into the wild, you can use it to authenticate your device to a server over SSL if you so desire, (also Android related) among other functions.

Is there a PowerShell "string does not contain" cmdlet or syntax?

You can use the -notmatch operator to get the lines that don't have the characters you are interested in.

     Get-Content $FileName | foreach-object { 
     if ($_ -notmatch $arrayofStringsNotInterestedIn) { $) }

How to resize superview to fit all subviews with autolayout?

Eric Baker's comment tipped me off to the core idea that in order for a view to have its size be determined by the content placed within it, then the content placed within it must have an explicit relationship with the containing view in order to drive its height (or width) dynamically. "Add subview" does not create this relationship as you might assume. You have to choose which subview is going to drive the height and/or width of the container... most commonly whatever UI element you have placed in the lower right hand corner of your overall UI. Here's some code and inline comments to illustrate the point.

Note, this may be of particular value to those working with scroll views since it's common to design around a single content view that determines its size (and communicates this to the scroll view) dynamically based on whatever you put in it. Good luck, hope this helps somebody out there.

//
//  ViewController.m
//  AutoLayoutDynamicVerticalContainerHeight
//

#import "ViewController.h"

@interface ViewController ()
@property (strong, nonatomic) UIView *contentView;
@property (strong, nonatomic) UILabel *myLabel;
@property (strong, nonatomic) UILabel *myOtherLabel;
@end

@implementation ViewController

- (void)viewDidLoad
{
    // INVOKE SUPER
    [super viewDidLoad];

    // INIT ALL REQUIRED UI ELEMENTS
    self.contentView = [[UIView alloc] init];
    self.myLabel = [[UILabel alloc] init];
    self.myOtherLabel = [[UILabel alloc] init];
    NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(_contentView, _myLabel, _myOtherLabel);

    // TURN AUTO LAYOUT ON FOR EACH ONE OF THEM
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    self.myLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.myOtherLabel.translatesAutoresizingMaskIntoConstraints = NO;

    // ESTABLISH VIEW HIERARCHY
    [self.view addSubview:self.contentView]; // View adds content view
    [self.contentView addSubview:self.myLabel]; // Content view adds my label (and all other UI... what's added here drives the container height (and width))
    [self.contentView addSubview:self.myOtherLabel];

    // LAYOUT

    // Layout CONTENT VIEW (Pinned to left, top. Note, it expects to get its vertical height (and horizontal width) dynamically based on whatever is placed within).
    // Note, if you don't want horizontal width to be driven by content, just pin left AND right to superview.
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to left, no horizontal width yet
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to top, no vertical height yet

    /* WHATEVER WE ADD NEXT NEEDS TO EXPLICITLY "PUSH OUT ON" THE CONTAINING CONTENT VIEW SO THAT OUR CONTENT DYNAMICALLY DETERMINES THE SIZE OF THE CONTAINING VIEW */
    // ^To me this is what's weird... but okay once you understand...

    // Layout MY LABEL (Anchor to upper left with default margin, width and height are dynamic based on text, font, etc (i.e. UILabel has an intrinsicContentSize))
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];

    // Layout MY OTHER LABEL (Anchored by vertical space to the sibling label that comes before it)
    // Note, this is the view that we are choosing to use to drive the height (and width) of our container...

    // The LAST "|" character is KEY, it's what drives the WIDTH of contentView (red color)
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];

    // Again, the LAST "|" character is KEY, it's what drives the HEIGHT of contentView (red color)
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_myLabel]-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];

    // COLOR VIEWS
    self.view.backgroundColor = [UIColor purpleColor];
    self.contentView.backgroundColor = [UIColor redColor];
    self.myLabel.backgroundColor = [UIColor orangeColor];
    self.myOtherLabel.backgroundColor = [UIColor greenColor];

    // CONFIGURE VIEWS

    // Configure MY LABEL
    self.myLabel.text = @"HELLO WORLD\nLine 2\nLine 3, yo";
    self.myLabel.numberOfLines = 0; // Let it flow

    // Configure MY OTHER LABEL
    self.myOtherLabel.text = @"My OTHER label... This\nis the UI element I'm\narbitrarily choosing\nto drive the width and height\nof the container (the red view)";
    self.myOtherLabel.numberOfLines = 0;
    self.myOtherLabel.font = [UIFont systemFontOfSize:21];
}

@end

How to resize superview to fit all subviews with autolayout.png

How to get number of entries in a Lua table?

The easiest way that I know of to get the number of entries in a table is with '#'. #tableName gets the number of entries as long as they are numbered:

tbl={
    [1]
    [2]
    [3]
    [4]
    [5]
}
print(#tbl)--prints the highest number in the table: 5

Sadly, if they are not numbered, it won't work.

How to replace a hash key with another key

Previous answers are good enough, but they might update original data. In case if you don't want the original data to be affected, you can try my code.

 newhash=hash.reject{|k| k=='_id'}.merge({id:hash['_id']})

First it will ignore the key '_id' then merge with the updated one.

How to save user input into a variable in html and js

I found this to work best for me https://jsfiddle.net/Lu92akv6/ [I found this to work for me try this fiddle][1]

_x000D_
_x000D_
document.getElementById("btnmyNumber").addEventListener("click", myFunctionVar);_x000D_
function myFunctionVar() {_x000D_
  var numberr = parseInt(document.getElementById("myNumber").value, 10);_x000D_
  // alert(numberr);_x000D_
  if ( numberr > 1) {_x000D_
_x000D_
    document.getElementById("minusE5").style.display = "none";_x000D_
_x000D_
_x000D_
_x000D_
}}
_x000D_
   <form onsubmit="return false;">_x000D_
       <input class="button button3" type="number" id="myNumber" value="" min="0" max="30">_x000D_
       <input type="submit" id="btnmyNumber">_x000D_
_x000D_
       </form>
_x000D_
_x000D_
_x000D_

How can I wait for 10 second without locking application UI in android

You never want to call thread.sleep() on the UI thread as it sounds like you have figured out. This freezes the UI and is always a bad thing to do. You can use a separate Thread and postDelayed

This SO answer shows how to do that as well as several other options

Handler

TimerTask

You can look at these and see which will work best for your particular situation

compression and decompression of string data in java

If you ever need to transfer the zipped content via network or store it as text, you have to use Base64 encoder(such as apache commons codec Base64) to convert the byte array to a Base64 String, and decode the string back to byte array at remote client. Found an example at Use Zip Stream and Base64 Encoder to Compress Large String Data!

"E: Unable to locate package python-pip" on Ubuntu 18.04

You might have python 3 pip installed already. Instead of pip install you can use pip3 install.

Write / add data in JSON file using Node.js

I agree with above answers, Here is a complete read and write sample for anyone who needs it.

     router.post('/', function(req, res, next) {

        console.log(req.body);
        var id = Math.floor((Math.random()*100)+1);

        var tital = req.body.title;
        var description = req.body.description;
        var mynotes = {"Id": id, "Title":tital, "Description": description};
        
        fs.readFile('db.json','utf8', function(err,data){
            var obj = JSON.parse(data);
            obj.push(mynotes);
            var strNotes = JSON.stringify(obj);
            fs.writeFile('db.json',strNotes, function(err){
                if(err) return console.log(err);
                console.log('Note added');
            });

        })
        
        
    });


  

How to Decrease Image Brightness in CSS

OP wants to decrease brightness, not increase it. Opacity makes the image look brighter, not darker.

You can do this by overlaying a black div over the image and setting the opacity of that div.

<style>
#container {
    position: relative;
}
div.overlay {
    opacity: .9;
    background-color: black;
    position: absolute;
    left: 0; top: 0; height: 256px; width: 256px;
}
</style>

Normal:<br />
<img src="http://i.imgur.com/G8eyr.png">
<br />
Decreased brightness:<br />
<div id="container">
    <div class="overlay"></div>
    <img src="http://i.imgur.com/G8eyr.png">
</div>

DEMO

How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template?

In you app config file change the url to localhost/example/public

Then when you want to link to something

<a href="{{ url('page') }}">Some Text</a>

without blade

<a href="<?php echo url('page') ?>">Some Text</a>

NPM: npm-cli.js not found when running npm

I experienced this same issue when installing Node version manager (NVM) on Windows 10.

Whenever I run the command:

npm install -g yarn

I was getting the error below:

Error: Cannot find module 'C:\Program Files\nodejs\node_modules\npm\bin\node_modules\npm\bin\npm-cli.js'

The issue was that there other components of the previous Node installations that were interfering with the Node version manager (NVM) setup.

Here's how I fixed it:

All I had to do was to go to the Control Panel of the Windows machine.

Uninstalled Node version manager (NVM) for windows. This removed every other component and directory of the previous Node installations.

Next, I did a new installation of the Node version manager (NVM)

This time when I ran the command below everything worked fine:

npm install -g yarn

That's all.

I hope this helps

jQuery: Performing synchronous AJAX requests

function getRemote() {
    return $.ajax({
        type: "GET",
        url: remote_url,
        async: false,
        success: function (result) {
            /* if result is a JSon object */
            if (result.valid)
                return true;
            else
                return false;
        }
    });
}

What are ABAP and SAP?

with SAP, you might be referring to a popular business software:

http://en.wikipedia.org/wiki/SAP_AG

And according to Wikipedia, ABAP is a programming language (short for Advanced Business Application Programming) created by SAP AG.

Check if any ancestor has a class using jQuery

You can use parents method with specified .class selector and check if any of them matches it:

if ($elem.parents('.left').length != 0) {
    //someone has this class
}

How to Use Sockets in JavaScript\HTML?

I think it is important to mention, now that this question is over 1 year old, that Socket.IO has since come out and seems to be the primary way to work with sockets in the browser now; it is also compatible with Node.js as far as I know.

How to specify the private SSH-key to use when executing shell command on Git?

The problem is when you have different remote repositories on the same host (say github.com), and you want to interact with them using different ssh keys (i.e. different GitHub accounts).

In order to do that:

  1. First you should declare your different keys in ~/.ssh/config file.

    # Key for usual repositories on github.com
    Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa
    
    # Key for a particular repository on github.com
    Host XXX
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_other_rsa
    

    By doing this you associate the second key with a new friendly name "XXX" for github.com.

  2. Then you must change the remote origin of your particular repository, so that it uses the friendly name you've just defined.

    Go to your local repository folder within a command prompt, and display the current remote origin:

    >git remote -v
    origin  [email protected]:myuser/myrepo.git (fetch)
    origin  [email protected]:myuser/myrepo.git (push)
    

    Then change origin with:

    >git remote set-url origin git@XXX:myuser/myrepo.git
    >git remote -v
    origin  git@XXX:myuser/myrepo.git (fetch)
    origin  git@XXX:myuser/myrepo.git (push)
    

    Now you can push, fetch... with the right key automatically.

How to convert Nonetype to int or string?

In some situations it is helpful to have a function to convert None to int zero:

def nz(value):

    '''
    Convert None to int zero else return value.
    '''

    if value == None:
        return 0
    return value

Format a JavaScript string using placeholders and an object of substitutions?

You can use JQuery(jquery.validate.js) to make it work easily.

$.validator.format("My name is {0}, I'm {1} years old",["Bob","23"]);

Or if you want to use just that feature you can define that function and just use it like

function format(source, params) {
    $.each(params,function (i, n) {
        source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
    })
    return source;
}
alert(format("{0} is a {1}", ["Michael", "Guy"]));

credit to jquery.validate.js team

How to check if a table exists in MS Access for vb macros

Setting a reference to the Microsoft Access 12.0 Object Library allows us to test if a table exists using DCount.

Public Function ifTableExists(tblName As String) As Boolean

    If DCount("[Name]", "MSysObjects", "[Name] = '" & tblName & "'") = 1 Then

        ifTableExists = True

    End If

End Function

How to hide a div with jQuery?

$("myDiv").hide(); and $("myDiv").show(); does not work in Internet Explorer that well.

The way I got around this was to get the html content of myDiv using .html().

I then wrote it to a newly created DIV. I then appended the DIV to the body and appended the content of the variable Content to the HiddenField then read that contents from the newly created div when I wanted to show the DIV.

After I used the .remove() method to get rid of the DIV that was temporarily holding my DIVs html.

var Content = $('myDiv').html(); 
        $('myDiv').empty();
        var hiddenField = $("<input type='hidden' id='myDiv2'>");
        $('body').append(hiddenField);
        HiddenField.val(Content);

and then when I wanted to SHOW the content again.

        var Content = $('myDiv');
        Content.html($('#myDiv2').val());
        $('#myDiv2').remove();

This was more reliable that the .hide() & .show() methods.

Performing a Stress Test on Web Application?

One more note, for our web application, I found that we had huge performance issues due to contention between threads over locks... so the moral was to think over the locking scheme very carefully. We ended up having worker threads to throttle too many requests using an asynchronous http handler, otherwise the application would just get overwhelmed and crash and burn. It meant a huge backlog could pile up, but at least the site would stay up.

jQuery selector for the label of a checkbox

This should do it:

$("label[for=comedyclubs]")

If you have non alphanumeric characters in your id then you must surround the attr value with quotes:

$("label[for='comedy-clubs']")

How can I change Mac OS's default Java VM returned from /usr/libexec/java_home

Edit: this information is for visualvm specifically, not for any other java app

As mentioned by others, you need to modify the visualvm.conf

For the latest version of JvisualVM 1.3.6 on Mac, the install directories have changed.

It is currently in /Applications/VisualVM.app/Contents/Resources/visualvm/etc/visualvm.conf.

However this may depend on where you have installed VisualVM. The easiest way to find where your VisualVM is to start it, and then look at the process using:

ps -ef | grep VisualVM

You will see something like:

... -Dnetbeans.dirs=/Applications/VisualVM.app/Contents/Resources/visualvm/visualvm...

You want to take the netbeans.dir property and look up a directory and you will find the etc folder.

Uncomment this line in the visualvm.conf and change the path to the jdk

visualvm_jdkhome="/path/to/jdk"

Additionally, if you are having slowness with your visualvm and you have a lot of memory, I would suggest greatly increasing the amount of memory available and running it in server mode:

visualvm_default_options="-J-XX:MaxPermSize=96m -J-Xmx2048m -J-Xms2048m -J-server -J-XX:+UseCompressedOops -J-XX:+UseConcMarkSweepGC -J-XX:+UseParNewGC -J-XX:NewRatio=2 -J-Dnetbeans.accept_license_class=com.sun.tools.visualvm.modules.startup.AcceptLicense -J-Dsun.jvmstat.perdata.syncWaitMs=10000 -J-Dsun.java2d.noddraw=true -J-Dsun.java2d.d3d=false"

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

I got the same error, I'm using laravel 5.4 with webpack, here package.json before:

{
  ...
  ...
  "devDependencies": {
    "jquery": "^1.12.4",
    ...
    ...
  },
  "dependencies": {
    "datatables.net": "^2.1.1",
    ...
    ...
  }
}

I had to move jquery and datatables.net npm packages under one of these "dependencies": {} or "devDependencies": {} in package.json and the error disappeared, after:

{
  ...
  ...
  "devDependencies": {
    "jquery": "^1.12.4",
    "datatables.net": "^2.1.1",
    ...
    ...
  }
}

I hope that helps!

How to increase apache timeout directive in .htaccess?

Just in case this helps anyone else:

If you're going to be adding the TimeOut directive, and your website uses multiple vhosts (eg. one for port 80, one for port 443), then don't forget to add the directive to all of them!

Reading *.wav files in Python

Per the documentation, scipy.io.wavfile.read(somefile) returns a tuple of two items: the first is the sampling rate in samples per second, the second is a numpy array with all the data read from the file:

from scipy.io import wavfile
samplerate, data = wavfile.read('./output/audio.wav')

calling javascript function on OnClientClick event of a Submit button

The above solutions must work. However you can try this one:

OnClientClick="return SomeMethod();return false;"

and remove return statement from the method.

'True' and 'False' in Python

From 6.11. Boolean operations:

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.

The key phrasing here that I think you are misunderstanding is "interpreted as false" or "interpreted as true". This does not mean that any of those values are identical to True or False, or even equal to True or False.

The expression '/bla/bla/bla' will be treated as true where a Boolean expression is expected (like in an if statement), but the expressions '/bla/bla/bla' is True and '/bla/bla/bla' == True will evaluate to False for the reasons in Ignacio's answer.

How to correctly close a feature branch in Mercurial?

imho there are two cases for branches that were forgot to close

Case 1: branch was not merged into default

in this case I update to the branch and do another commit with --close-branch, unfortunatly this elects the branch to become the new tip and hence before pushing it to other clones I make sure that the real tip receives some more changes and others don't get confused about that strange tip.

hg up myBranch
hg commit --close-branch

Case 2: branch was merged into default

This case is not that much different from case 1 and it can be solved by reproducing the steps for case 1 and two additional ones.

in this case I update to the branch changeset, do another commit with --close-branch and merge the new changeset that became the tip into default. the last operation creates a new tip that is in the default branch - HOORAY!

hg up myBranch
hg commit --close-branch
hg up default
hg merge myBranch

Hope this helps future readers.

How can I determine installed SQL Server instances and their versions?

From Windows command-line, type:

SC \\server_name query | find /I "SQL Server ("

Where "server_name" is the name of any remote server on which you wish to display the SQL instances.

This requires enough permissions of course.

How to get substring of NSString?

Here is a little combination of @Regexident Option 1 and @Garett answers, to get a powerful string cutter between a prefix and suffix, with MORE...ANDMORE words on it.

NSString *haystack = @"MOREvalue:hello World:valueANDMORE";
NSString *prefix = @"value:";
NSString *suffix = @":value";
NSRange prefixRange = [haystack rangeOfString:prefix];
NSRange suffixRange = [[haystack substringFromIndex:prefixRange.location+prefixRange.length] rangeOfString:suffix];
NSRange needleRange = NSMakeRange(prefixRange.location+prefix.length, suffixRange.location);
NSString *needle = [haystack substringWithRange:needleRange];
NSLog(@"needle: %@", needle);

How to create a circular ImageView in Android?

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

    public RoundedImageView(Context context) {
        super(context);
    }

    public RoundedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

Perform debounce in React.js

Just another variant with recent react and lodash.

class Filter extends Component {
  static propTypes = {
    text: PropTypes.string.isRequired,
    onChange: PropTypes.func.isRequired
  }

  state = {
    initialText: '',
    text: ''
  }

  constructor (props) {
    super(props)

    this.setText = this.setText.bind(this)
    this.onChange = _.fp.debounce(500)(this.onChange.bind(this))
  }

  static getDerivedStateFromProps (nextProps, prevState) {
    const { text } = nextProps

    if (text !== prevState.initialText) {
      return { initialText: text, text }
    }

    return null
  }

  setText (text) {
    this.setState({ text })
    this.onChange(text)
  }

  onChange (text) {
    this.props.onChange(text)
  }

  render () {
    return (<input value={this.state.text} onChange={(event) => this.setText(event.target.value)} />)
  }
}

Convert JS date time to MySQL datetime

For arbitrary date string,

// Your default date object  
var starttime = new Date();
// Get the iso time (GMT 0 == UTC 0)
var isotime = new Date((new Date(starttime)).toISOString() );
// getTime() is the unix time value, in milliseconds.
// getTimezoneOffset() is UTC time and local time in minutes.
// 60000 = 60*1000 converts getTimezoneOffset() from minutes to milliseconds. 
var fixedtime = new Date(isotime.getTime()-(starttime.getTimezoneOffset()*60000));
// toISOString() is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ.
// .slice(0, 19) removes the last 5 chars, ".sssZ",which is (UTC offset).
// .replace('T', ' ') removes the pad between the date and time.
var formatedMysqlString = fixedtime.toISOString().slice(0, 19).replace('T', ' ');
console.log( formatedMysqlString );

Or a single line solution,

var formatedMysqlString = (new Date ((new Date((new Date(new Date())).toISOString() )).getTime() - ((new Date()).getTimezoneOffset()*60000))).toISOString().slice(0, 19).replace('T', ' ');
console.log( formatedMysqlString );

This solution also works for Node.js when using Timestamp in mysql.

@Gajus Kuizinas's first answer seems to modify mozilla's toISOString prototype

Google Maps API OVER QUERY LIMIT per second limit

Instead of client-side geocoding

geocoder.geocode({
    'address': your_address
  }, function (results, status) {
     if (status == google.maps.GeocoderStatus.OK) {
       var geo_data = results[0];
       // your code ...
   } 
})

I would go to server-side geocoding API

var apikey = YOUR_API_KEY;
var query = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&key=' + apikey;
$.getJSON(query, function (data) {
  if (data.status === 'OK') { 
    var geo_data = data.results[0];
  } 
})

Can curl make a connection to any TCP ports, not just HTTP/HTTPS?

Of course:

curl http://example.com:11740
curl https://example.com:11740

Port 80 and 443 are just default port numbers.

INSERT VALUES WHERE NOT EXISTS

There is a great solution for this problem ,You can use the Merge Keyword of Sql

Merge MyTargetTable hba
USING (SELECT Id = 8, Name = 'Product Listing Message') temp 
ON temp.Id = hba.Id
WHEN NOT matched THEN 
INSERT (Id, Name) VALUES (temp.Id, temp.Name);

You can check this before following, below is the sample

IF OBJECT_ID ('dbo.TargetTable') IS NOT NULL
    DROP TABLE dbo.TargetTable
GO

CREATE TABLE dbo.TargetTable
    (
    Id   INT NOT NULL,
    Name VARCHAR (255) NOT NULL,
    CONSTRAINT PK_TargetTable PRIMARY KEY (Id)
    )
GO



INSERT INTO dbo.TargetTable (Name)
VALUES ('Unknown')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('Mapping')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('Update')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('Message')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('Switch')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('Unmatched')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('ProductMessage')
GO


Merge MyTargetTable hba
USING (SELECT Id = 8, Name = 'Listing Message') temp 
ON temp.Id = hba.Id
WHEN NOT matched THEN 
INSERT (Id, Name) VALUES (temp.Id, temp.Name);

How to determine if a String has non-alphanumeric characters?

Use this function to check if a string is alphanumeric:

public boolean isAlphanumeric(String str)
{
    char[] charArray = str.toCharArray();
    for(char c:charArray)
    {
        if (!Character.isLetterOrDigit(c))
            return false;
    }
    return true;
}

It saves having to import external libraries and the code can easily be modified should you later wish to perform different validation checks on strings.

How do I install boto?

While trying out the

pip install boto

command, I encounter the error

ImportError: No module named pkg_resources

To resolve this, issue another command to handle the setuptools using curl

curl https://bootstrap.pypa.io/ez_setup.py | python

After doing that, the following command will work perfectly.

pip install boto

How to override maven property in command line?

See Introduction to the POM

finalName is created as:

<build>
    <finalName>${project.artifactId}-${project.version}</finalName>
</build>

One of the solutions is to add own property:

<properties>
    <finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
    <finalName>${finalName}</finalName>
 </build>

And now try:

mvn -DfinalName=build clean package

The type WebMvcConfigurerAdapter is deprecated

Use org.springframework.web.servlet.config.annotation.WebMvcConfigurer

With Spring Boot 2.1.4.RELEASE (Spring Framework 5.1.6.RELEASE), do like this

package vn.bkit;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; // Deprecated.
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
public class MvcConfiguration implements WebMvcConfigurer {

    @Bean
    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/");
        resolver.setSuffix(".html");
        return resolver;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

}

Codeigniter displays a blank page instead of error messages

If you get net::ERR_CONTENT_DECODING_FAILED in the console then you are using gzip in your .htaccess file but gzip encoding is Off.

Enable zlib.output_compression=On in php.ini and restart Apache

Qt 5.1.1: Application failed to start because platform plugin "windows" is missing

The application qtbase/bin/windeployqt.exe deploys automatically your application. If you start a prompt with envirenmentvariables set correctly, it deploys to the current directory. You find an example of script:

@echo off
set QTDIR=E:\QT\5110\vc2017

set INCLUDE=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\ATLMFC\include;S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\include;C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um;C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\ucrt;C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\shared;C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um;C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\winrt;C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\cppwinrt

set LIB=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\ATLMFC\lib\x86;S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\lib\x86;C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\lib\um\x86;C:\Program Files (x86)\Windows Kits\10\lib\10.0.14393.0\ucrt\x86;C:\Program Files (x86)\Windows Kits\10\lib\10.0.14393.0\um\x86;

set LIBPATH=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\ATLMFC\lib\x86;S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\lib\x86;S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\lib\x86\store\references;C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.17134.0;C:\ProgramFiles (x86)\Windows Kits\10\References\10.0.17134.0;C:\Windows\Microsoft.NET\Framework\v4.0.30319;

Path=%QTDIR%\qtbase\bin;%PATH%
set VCIDEInstallDir=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\VC\
set VCINSTALLDIR=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\
set VCToolsInstallDir=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.11.25503\
set VisualStudioVersion=15.0
set VS100COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tools\
set VS110COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools\
set VS120COMNTOOLS=S:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\
set VS150COMNTOOLS=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\Tools\
set VS80COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 8\Common7\Tools\
set VS90COMNTOOLS=c:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools\
set VSINSTALLDIR=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\
set VSSDK110Install=C:\Program Files (x86)\Microsoft Visual Studio 11.0\VSSDK\
set VSSDK150INSTALL=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VSSDK
set WindowsLibPath=C:\Program Files (x86)\Windows Kits\10\UnionMetadata;C:\Program Files (x86)\Windows Kits\10\References
set WindowsSdkBinPath=C:\Program Files (x86)\Windows Kits\10\bin\
set WindowsSdkDir=C:\Program Files (x86)\Windows Kits\10\
set WindowsSDKLibVersion=10.0.14393.0\
set WindowsSdkVerBinPath=C:\Program Files (x86)\Windows Kits\10\bin\10.0.14393.0\
set WindowsSDKVersion=10.0.14393.0\
set WindowsSDK_ExecutablePath_x64=C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\x64\
set WindowsSDK_ExecutablePath_x86=C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\

mkdir C:\VCProjects\Application\Build\VS2017_QT5_11_32-Release\setup
cd C:\VCProjects\Application\Build\VS2017_QT5_11_32-Release\setup
copy /Y ..\Release\application.exe .
windeployqt application.exe
pause

Return HTML content as a string, given URL. Javascript Function

you need to return when the readystate==4 e.g.

function httpGet(theUrl)
{
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            return xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", theUrl, false );
    xmlhttp.send();    
}

ASP.NET set hiddenfield a value in Javascript

Prior to ASP.Net 4.0

ClientID

Get the client id generated in the page that uses Master page. As Master page is UserControl type, It will have its own Id and it treats the page as Child control and generates a different id with prefix like ctrl_.

This can be resolved by using <%= ControlName.ClientID %> in a page and can be assigned to any string or a javascript variables that can be referred later.

var myHidden=document.getElementById('<%= hdntxtbxTaksit.ClientID %>');
  • Asp.net server control id will be vary if you use Master page.

ASP.Net 4.0 +

ClientIDMode Property

Use this property to control how you want to generate the ID for you. For your case setting ClientIDMode="static" in page level will resolve the problem. The same thing can be applied at control level as well.

Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"?

I guess the core of your question is why to program to an interface, not to an implementation

Simply because an interface gives you more abstraction, and makes the code more flexible and resilient to changes, because you can use different implementations of the same interface(in this case you may want to change your List implementation to a linkedList instead of an ArrayList ) without changing its client.

What is the best way to add a value to an array in state

This might not directly answer your question but for the sake of those that come with states like the below

 state = {
    currentstate:[
     {
    id: 1 ,
    firstname: 'zinani',
    sex: 'male'

     }
    ]

 }

Solution

const new_value = {
    id: 2 ,
    firstname: 'san',
    sex: 'male'

     }

Replace the current state with the new value

 this.setState({ currentState: [...this.state.currentState, new_array] })

Is it possible to make abstract classes in Python?

Here's a very easy way without having to deal with the ABC module.

In the __init__ method of the class that you want to be an abstract class, you can check the "type" of self. If the type of self is the base class, then the caller is trying to instantiate the base class, so raise an exception. Here's a simple example:

class Base():
    def __init__(self):
        if type(self) is Base:
            raise Exception('Base is an abstract class and cannot be instantiated directly')
        # Any initialization code
        print('In the __init__  method of the Base class')

class Sub(Base):
    def __init__(self):
        print('In the __init__ method of the Sub class before calling __init__ of the Base class')
        super().__init__()
        print('In the __init__ method of the Sub class after calling __init__ of the Base class')

subObj = Sub()
baseObj = Base()

When run, it produces:

In the __init__ method of the Sub class before calling __init__ of the Base class
In the __init__  method of the Base class
In the __init__ method of the Sub class after calling __init__ of the Base class
Traceback (most recent call last):
  File "/Users/irvkalb/Desktop/Demo files/Abstract.py", line 16, in <module>
    baseObj = Base()
  File "/Users/irvkalb/Desktop/Demo files/Abstract.py", line 4, in __init__
    raise Exception('Base is an abstract class and cannot be instantiated directly')
Exception: Base is an abstract class and cannot be instantiated directly

This shows that you can instantiate a subclass that inherits from a base class, but you cannot instantiate the base class directly.

Omitting all xsi and xsd namespaces when serializing an object in .NET?

After reading Microsoft's documentation and several solutions online, I have discovered the solution to this problem. It works with both the built-in XmlSerializer and custom XML serialization via IXmlSerialiazble.

To wit, I'll use the same MyTypeWithNamespaces XML sample that's been used in the answers to this question so far.

[XmlRoot("MyTypeWithNamespaces", Namespace="urn:Abracadabra", IsNullable=false)]
public class MyTypeWithNamespaces
{
    // As noted below, per Microsoft's documentation, if the class exposes a public
    // member of type XmlSerializerNamespaces decorated with the 
    // XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
    // namespaces during serialization.
    public MyTypeWithNamespaces( )
    {
        this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
            // Don't do this!! Microsoft's documentation explicitly says it's not supported.
            // It doesn't throw any exceptions, but in my testing, it didn't always work.

            // new XmlQualifiedName(string.Empty, string.Empty),  // And don't do this:
            // new XmlQualifiedName("", "")

            // DO THIS:
            new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
            // Add any other namespaces, with prefixes, here.
        });
    }

    // If you have other constructors, make sure to call the default constructor.
    public MyTypeWithNamespaces(string label, int epoch) : this( )
    {
        this._label = label;
        this._epoch = epoch;
    }

    // An element with a declared namespace different than the namespace
    // of the enclosing type.
    [XmlElement(Namespace="urn:Whoohoo")]
    public string Label
    {
        get { return this._label; }
        set { this._label = value; }
    }
    private string _label;

    // An element whose tag will be the same name as the property name.
    // Also, this element will inherit the namespace of the enclosing type.
    public int Epoch
    {
        get { return this._epoch; }
        set { this._epoch = value; }
    }
    private int _epoch;

    // Per Microsoft's documentation, you can add some public member that
    // returns a XmlSerializerNamespaces object. They use a public field,
    // but that's sloppy. So I'll use a private backed-field with a public
    // getter property. Also, per the documentation, for this to work with
    // the XmlSerializer, decorate it with the XmlNamespaceDeclarations
    // attribute.
    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces Namespaces
    {
        get { return this._namespaces; }
    }
    private XmlSerializerNamespaces _namespaces;
}

That's all to this class. Now, some objected to having an XmlSerializerNamespaces object somewhere within their classes; but as you can see, I neatly tucked it away in the default constructor and exposed a public property to return the namespaces.

Now, when it comes time to serialize the class, you would use the following code:

MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);

/******
   OK, I just figured I could do this to make the code shorter, so I commented out the
   below and replaced it with what follows:

// You have to use this constructor in order for the root element to have the right namespaces.
// If you need to do custom serialization of inner objects, you can use a shortened constructor.
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces), new XmlAttributeOverrides(),
    new Type[]{}, new XmlRootAttribute("MyTypeWithNamespaces"), "urn:Abracadabra");

******/
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
    new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });

// I'll use a MemoryStream as my backing store.
MemoryStream ms = new MemoryStream();

// This is extra! If you want to change the settings for the XmlSerializer, you have to create
// a separate XmlWriterSettings object and use the XmlTextWriter.Create(...) factory method.
// So, in this case, I want to omit the XML declaration.
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Encoding = Encoding.UTF8; // This is probably the default
// You could use the XmlWriterSetting to set indenting and new line options, but the
// XmlTextWriter class has a much easier method to accomplish that.

// The factory method returns a XmlWriter, not a XmlTextWriter, so cast it.
XmlTextWriter xtw = (XmlTextWriter)XmlTextWriter.Create(ms, xws);
// Then we can set our indenting options (this is, of course, optional).
xtw.Formatting = Formatting.Indented;

// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);

Once you have done this, you should get the following output:

<MyTypeWithNamespaces>
    <Label xmlns="urn:Whoohoo">myLabel</Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

I have successfully used this method in a recent project with a deep hierachy of classes that are serialized to XML for web service calls. Microsoft's documentation is not very clear about what to do with the publicly accesible XmlSerializerNamespaces member once you've created it, and so many think it's useless. But by following their documentation and using it in the manner shown above, you can customize how the XmlSerializer generates XML for your classes without resorting to unsupported behavior or "rolling your own" serialization by implementing IXmlSerializable.

It is my hope that this answer will put to rest, once and for all, how to get rid of the standard xsi and xsd namespaces generated by the XmlSerializer.

UPDATE: I just want to make sure I answered the OP's question about removing all namespaces. My code above will work for this; let me show you how. Now, in the example above, you really can't get rid of all namespaces (because there are two namespaces in use). Somewhere in your XML document, you're going to need to have something like xmlns="urn:Abracadabra" xmlns:w="urn:Whoohoo. If the class in the example is part of a larger document, then somewhere above a namespace must be declared for either one of (or both) Abracadbra and Whoohoo. If not, then the element in one or both of the namespaces must be decorated with a prefix of some sort (you can't have two default namespaces, right?). So, for this example, Abracadabra is the defalt namespace. I could inside my MyTypeWithNamespaces class add a namespace prefix for the Whoohoo namespace like so:

public MyTypeWithNamespaces
{
    this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
        new XmlQualifiedName(string.Empty, "urn:Abracadabra"), // Default Namespace
        new XmlQualifiedName("w", "urn:Whoohoo")
    });
}

Now, in my class definition, I indicated that the <Label/> element is in the namespace "urn:Whoohoo", so I don't need to do anything further. When I now serialize the class using my above serialization code unchanged, this is the output:

<MyTypeWithNamespaces xmlns:w="urn:Whoohoo">
    <w:Label>myLabel</w:Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

Because <Label> is in a different namespace from the rest of the document, it must, in someway, be "decorated" with a namespace. Notice that there are still no xsi and xsd namespaces.

How to find the operating system version using JavaScript?

@Ludwig 's solution was brilliant. A couple of fixes (which didn't have to do with operating system, and I couldn't place as a comment on his original posting because this is too long):

  1. IE 11 no longer identifies itself as MS IE.
  2. Chrome on IOS spoofs itself as Safari

Here they are:

(function (window) {
    {
    /* test cases
        alert(
            'browserInfo result: OS: ' + browserInfo.os +' '+ browserInfo.osVersion + '\n'+
                'Browser: ' + browserInfo.browser +' '+ browserInfo.browserVersion + '\n' +
                'Mobile: ' + browserInfo.mobile + '\n' +
                'Cookies: ' + browserInfo.cookies + '\n' +
                'Screen Size: ' + browserInfo.screen
        );
    */
        var unknown = 'Unknown';

        // screen
        var screenSize = '';
        if (screen.width) {
            width = (screen.width) ? screen.width : '';
            height = (screen.height) ? screen.height : '';
            screenSize += '' + width + " x " + height;
        }

        //browser
        var nVer = navigator.appVersion;
        var nAgt = navigator.userAgent;
        var browser = navigator.appName;
        var version = '' + parseFloat(navigator.appVersion);
        var majorVersion = parseInt(navigator.appVersion, 10);
        var nameOffset, verOffset, ix;

        // Opera
        if ((verOffset = nAgt.indexOf('Opera')) != -1) {
            browser = 'Opera';
            version = nAgt.substring(verOffset + 6);
            if ((verOffset = nAgt.indexOf('Version')) != -1) {
                version = nAgt.substring(verOffset + 8);
            }
        }
        // MSIE
        else if ((verOffset = nAgt.indexOf('MSIE')) != -1) {
            browser = 'Microsoft Internet Explorer';
            version = nAgt.substring(verOffset + 5);
        }

        //IE 11 no longer identifies itself as MS IE, so trap it
        //http://stackoverflow.com/questions/17907445/how-to-detect-ie11
        else if ((browser == 'Netscape') && (nAgt.indexOf('Trident/') != -1)) {

            browser = 'Microsoft Internet Explorer';
            version = nAgt.substring(verOffset + 5);
            if ((verOffset = nAgt.indexOf('rv:')) != -1) {
                version = nAgt.substring(verOffset + 3);
            }

        }

        // Chrome
        else if ((verOffset = nAgt.indexOf('Chrome')) != -1) {
            browser = 'Chrome';
            version = nAgt.substring(verOffset + 7);
        }
        // Safari
        else if ((verOffset = nAgt.indexOf('Safari')) != -1) {
            browser = 'Safari';
            version = nAgt.substring(verOffset + 7);
            if ((verOffset = nAgt.indexOf('Version')) != -1) {
                version = nAgt.substring(verOffset + 8);
            }

            // Chrome on iPad identifies itself as Safari. Actual results do not match what Google claims
            //  at: https://developers.google.com/chrome/mobile/docs/user-agent?hl=ja
            //  No mention of chrome in the user agent string. However it does mention CriOS, which presumably
            //  can be keyed on to detect it.
            if (nAgt.indexOf('CriOS') != -1) {
                //Chrome on iPad spoofing Safari...correct it.
                browser = 'Chrome';
                //Don't believe there is a way to grab the accurate version number, so leaving that for now.
            }
        }
        // Firefox
        else if ((verOffset = nAgt.indexOf('Firefox')) != -1) {
            browser = 'Firefox';
            version = nAgt.substring(verOffset + 8);
        }
        // Other browsers
        else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
            browser = nAgt.substring(nameOffset, verOffset);
            version = nAgt.substring(verOffset + 1);
            if (browser.toLowerCase() == browser.toUpperCase()) {
                browser = navigator.appName;
            }
        }
        // trim the version string
        if ((ix = version.indexOf(';')) != -1) version = version.substring(0, ix);
        if ((ix = version.indexOf(' ')) != -1) version = version.substring(0, ix);
        if ((ix = version.indexOf(')')) != -1) version = version.substring(0, ix);

        majorVersion = parseInt('' + version, 10);
        if (isNaN(majorVersion)) {
            version = '' + parseFloat(navigator.appVersion);
            majorVersion = parseInt(navigator.appVersion, 10);
        }

        // mobile version
        var mobile = /Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(nVer);

        // cookie
        var cookieEnabled = (navigator.cookieEnabled) ? true : false;

        if (typeof navigator.cookieEnabled == 'undefined' && !cookieEnabled) {
            document.cookie = 'testcookie';
            cookieEnabled = (document.cookie.indexOf('testcookie') != -1) ? true : false;
        }

        // system
        var os = unknown;
        var clientStrings = [
            {s:'Windows 3.11', r:/Win16/},
            {s:'Windows 95', r:/(Windows 95|Win95|Windows_95)/},
            {s:'Windows ME', r:/(Win 9x 4.90|Windows ME)/},
            {s:'Windows 98', r:/(Windows 98|Win98)/},
            {s:'Windows CE', r:/Windows CE/},
            {s:'Windows 2000', r:/(Windows NT 5.0|Windows 2000)/},
            {s:'Windows XP', r:/(Windows NT 5.1|Windows XP)/},
            {s:'Windows Server 2003', r:/Windows NT 5.2/},
            {s:'Windows Vista', r:/Windows NT 6.0/},
            {s:'Windows 7', r:/(Windows 7|Windows NT 6.1)/},
            {s:'Windows 8.1', r:/(Windows 8.1|Windows NT 6.3)/},
            {s:'Windows 8', r:/(Windows 8|Windows NT 6.2)/},
            {s:'Windows NT 4.0', r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},
            {s:'Windows ME', r:/Windows ME/},
            {s:'Android', r:/Android/},
            {s:'Open BSD', r:/OpenBSD/},
            {s:'Sun OS', r:/SunOS/},
            {s:'Linux', r:/(Linux|X11)/},
            {s:'iOS', r:/(iPhone|iPad|iPod)/},
            {s:'Mac OS X', r:/Mac OS X/},
            {s:'Mac OS', r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},
            {s:'QNX', r:/QNX/},
            {s:'UNIX', r:/UNIX/},
            {s:'BeOS', r:/BeOS/},
            {s:'OS/2', r:/OS\/2/},
            {s:'Search Bot', r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}
        ];
        for (var id in clientStrings) {
            var cs = clientStrings[id];
            if (cs.r.test(nAgt)) {
                os = cs.s;
                break;
            }
        }

        var osVersion = unknown;

        if (/Windows/.test(os)) {
            osVersion = /Windows (.*)/.exec(os)[1];
            os = 'Windows';
        }

        switch (os) {
            case 'Mac OS X':
                osVersion = /Mac OS X (10[\.\_\d]+)/.exec(nAgt)[1];
                break;

            case 'Android':
                osVersion = /Android ([\.\_\d]+)/.exec(nAgt)[1];
                break;

            case 'iOS':
                osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer);
                osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);
                break;

        }
    }

    window.browserInfo = {
        screen: screenSize,
        browser: browser,
        browserVersion: version,
        mobile: mobile,
        os: os,
        osVersion: osVersion,
        cookies: cookieEnabled
    };
}(this));

Print values for multiple variables on the same line from within a for-loop

Try out cat and sprintf in your for loop.

eg.

cat(sprintf("\"%f\" \"%f\"\n", df$r, df$interest))

See here

Determine file creation date in Java

The API of java.io.File only supports getting the last modified time. And the Internet is very quiet on this topic as well.

Unless I missed something significant, the Java library as is (up to but not yet including Java 7) does not include this capability. So if you were desperate for this, one solution would be to write some C(++) code to call system routines and call it using JNI. Most of this work seems to be already done for you in a library called JNA, though.

You may still need to do a little OS specific coding in Java for this, though, as you'll probably not find the same system calls available in Windows and Unix/Linux/BSD/OS X.

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

You can use % operator to check divisiblity of a given number

The code to check whether given no. is divisible by 3 or 5 when no. less than 1000 is given below:

n=0
while n<1000:
    if n%3==0 or n%5==0:
        print n,'is multiple of 3 or 5'
    n=n+1

C# - Simplest way to remove first occurrence of a substring from another string

int index = sourceString.IndexOf(removeString);
string cleanPath = (index < 0)
    ? sourceString
    : sourceString.Remove(index, removeString.Length);

How add spaces between Slick carousel item

simply add padding on to the slick-side class will do

.slick-slider .slick-slide {
  padding: 0 15px;
}

xsl: how to split strings?

If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.

Type definition in object literal in TypeScript

In your code:

var obj = {
  myProp: string;
};

You are actually creating a object literal and assigning the variable string to the property myProp. Although very bad practice this would actually be valid TS code (don't use this!):

var string = 'A string';

var obj = {
  property: string
};

However, what you want is that the object literal is typed. This can be achieved in various ways:

Interface:

interface myObj {
    property: string;
}

var obj: myObj = { property: "My string" };

Type alias:

type myObjType = {
    property: string
};

var obj: myObjType = { property: "My string" };

Object type literal:

var obj: { property: string; } = { property: "Mystring" };

DataAnnotations validation (Regular Expression) in asp.net mvc 4 - razor view

What browser are you using? I entered your example and tried in both IE8 and Chrome and it validated fine when I typed in the value Sam's

 public class IndexViewModel
 {
    [Required(ErrorMessage="Required")]
    [RegularExpression("^([a-zA-Z0-9 .&'-]+)$", ErrorMessage = "Invalid First Name")]
    public string Name { get; set; }
 }

When I inspect the DOM using IE Developer toolbar and Chrome Developer mode it does not show any special characters.

LINQ to read XML

Try this.

using System.Xml.Linq;

void Main()
{
    StringBuilder result = new StringBuilder();

    //Load xml
    XDocument xdoc = XDocument.Load("data.xml");

    //Run query
    var lv1s = from lv1 in xdoc.Descendants("level1")
               select new { 
                   Header = lv1.Attribute("name").Value,
                   Children = lv1.Descendants("level2")
               };

    //Loop through results
    foreach (var lv1 in lv1s){
            result.AppendLine(lv1.Header);
            foreach(var lv2 in lv1.Children)
                 result.AppendLine("     " + lv2.Attribute("name").Value);
    }

    Console.WriteLine(result);
}

dyld: Library not loaded: @rpath/libswiftCore.dylib

For me, having tried everything with no success, what worked was to remove @executable_path/Frameworks from the Packaging section (don't know how it came to be in there in the first place)

enter image description here

How can I use Async with ForEach?

This is method I created to handle async scenarios with ForEach.

  • If one of tasks fails then other tasks will continue their execution.
  • You have ability to add function that will be executed on every exception.
  • Exceptions are being collected as aggregateException at the end and are available for you.
  • Can handle CancellationToken
 public static class ParallelExecutor
    {
        /// <summary>
        /// Executes asynchronously given function on all elements of given enumerable with task count restriction.
        /// Executor will continue starting new tasks even if one of the tasks throws. If at least one of the tasks throwed exception then <see cref="AggregateException"/> is throwed at the end of the method run.
        /// </summary>
        /// <typeparam name="T">Type of elements in enumerable</typeparam>
        /// <param name="maxTaskCount">The maximum task count.</param>
        /// <param name="enumerable">The enumerable.</param>
        /// <param name="asyncFunc">asynchronous function that will be executed on every element of the enumerable. MUST be thread safe.</param>
        /// <param name="onException">Acton that will be executed on every exception that would be thrown by asyncFunc. CAN be thread unsafe.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        public static async Task ForEachAsync<T>(int maxTaskCount, IEnumerable<T> enumerable, Func<T, Task> asyncFunc, Action<Exception> onException = null, CancellationToken cancellationToken = default)
        {
            using var semaphore = new SemaphoreSlim(initialCount: maxTaskCount, maxCount: maxTaskCount);

            // This `lockObject` is used only in `catch { }` block.
            object lockObject = new object();
            var exceptions = new List<Exception>();
            var tasks = new Task[enumerable.Count()];
            int i = 0;

            try
            {
                foreach (var t in enumerable)
                {
                    await semaphore.WaitAsync(cancellationToken);
                    tasks[i++] = Task.Run(
                        async () =>
                        {
                            try
                            {
                                await asyncFunc(t);
                            }
                            catch (Exception e)
                            {
                                if (onException != null)
                                {
                                    lock (lockObject)
                                    {
                                        onException.Invoke(e);
                                    }
                                }

                                // This exception will be swallowed here but it will be collected at the end of ForEachAsync method in order to generate AggregateException.
                                throw;
                            }
                            finally
                            {
                                semaphore.Release();
                            }
                        }, cancellationToken);

                    if (cancellationToken.IsCancellationRequested)
                    {
                        break;
                    }
                }
            }
            catch (OperationCanceledException e)
            {
                exceptions.Add(e);
            }

            foreach (var t in tasks)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }

                // Exception handling in this case is actually pretty fast.
                // https://gist.github.com/shoter/d943500eda37c7d99461ce3dace42141
                try
                {
                    await t;
                }
#pragma warning disable CA1031 // Do not catch general exception types - we want to throw that exception later as aggregate exception. Nothing wrong here.
                catch (Exception e)
#pragma warning restore CA1031 // Do not catch general exception types
                {
                    exceptions.Add(e);
                }
            }

            if (exceptions.Any())
            {
                throw new AggregateException(exceptions);
            }
        }
    }

Using for loop inside of a JSP

Do this

    <% for(int i = 0; i < allFestivals.size(); i+=1) { %>
        <tr>      
            <td><%=allFestivals.get(i).getFestivalName()%></td>
        </tr>
    <% } %>

Better way is to use c:foreach see link jstl for each

How to compare arrays in C#?

You can use the Enumerable.SequenceEqual() in the System.Linq to compare the contents in the array

bool isEqual = Enumerable.SequenceEqual(target1, target2);

Is it possible to put CSS @media rules inline?

Problem

No, Media Queries cannot be used in this way

<span style="@media (...) { ... }"></span>

Solution

But if you want provided a specific behavior usable on the fly AND responsive, you can use the style markup and not the attribute.

e.i.

<style scoped>
.on-the-fly-behavior {
    background-image: url('particular_ad.png'); 
}
@media (max-width: 300px) {
    .on-the-fly-behavior {
        background-image: url('particular_ad_small.png');
    }
}
</style>
<span class="on-the-fly-behavior"></span>

See the code working in live on CodePen

In my Blog for example, I inject a <style> markup in <head> just after <link> declaration for CSS and it's contain the content of a textarea provided beside of real content textarea for create extra-class on the fly when I wrote an artitle.

Note : the scoped attribute is a part of HTML5 specification. If you do not use it, the validator will blame you but browsers currently not support the real purpose : scoped the content of <style> only on immediatly parent element and that element's child elements. Scoped is not mandatory if the <style> element is in <head> markup.


UPDATE: I advice to always use rules in the mobile first way so previous code should be:

<style scoped>
/* 0 to 299 */
.on-the-fly-behavior {
    background-image: url('particular_ad_small.png'); 
}
/* 300 to X */
@media (min-width: 300px) { /* or 301 if you want really the same as previously.  */
    .on-the-fly-behavior {   
        background-image: url('particular_ad.png');
    }
}
</style>
<span class="on-the-fly-behavior"></span>

a tag as a submit button?

Give the form an id, and then:

document.getElementById("yourFormId").submit();

Best practice would probably be to give your link an id too, and get rid of the event handler:

document.getElementById("yourLinkId").onclick = function() {
    document.getElementById("yourFormId").submit();
}

DataSet panel (Report Data) in SSRS designer is gone

If you are using BIDS with SQL 2008 R2 you can only get the "Report Data" menu by clicking inside the actual report layout itself.

  1. Click inside the actual report layout.

  2. Now select "View" from the main menu bar.

  3. Now select "Report Data" which is the last item.

if arguments is equal to this string, define a variable like this string

Don't forget about spaces:

source=""
samples=("")
if [ $1 = "country" ]; then
   source="country"
   samples="US Canada Mexico..."
else
  echo "try again"
fi

How can I delay a method call for 1 second?

You can use the perform selector for after the 0.1 sec delay method is call for that following code to do this.

[self performSelector:@selector(InsertView)  withObject:nil afterDelay:0.1]; 

Binding a WPF ComboBox to a custom list

I had a similar issue where the SelectedItem never got updated.

My problem was that the selected item was not the same instance as the item contained in the list. So I simply had to override the Equals() method in my MyCustomObject and compare the IDs of those two instances to tell the ComboBox that it's the same object.

public override bool Equals(object obj)
{
    return this.Id == (obj as MyCustomObject).Id;
}

How do I download a file using VBA (without Internet Explorer)

A modified version of above solution to make it more dynamic.

Private Declare Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long

Public Function DownloadFileA(ByVal URL As String, ByVal DownloadPath As String) As Boolean
    On Error GoTo Failed
    DownloadFileA = False
    'As directory must exist, this is a check
    If CreateObject("Scripting.FileSystemObject").FolderExists(CreateObject("Scripting.FileSystemObject").GetParentFolderName(DownloadPath)) = False Then Exit Function
    Dim returnValue As Long
    returnValue = URLDownloadToFile(0, URL, DownloadPath, 0, 0)
    'If return value is 0 and the file exist, then it is considered as downloaded correctly
    DownloadFileA = (returnValue = 0) And (Len(Dir(DownloadPath)) > 0)
    Exit Function

Failed:
End Function

How to do a non-greedy match in grep?

My grep that works after trying out stuff in this thread:

echo "hi how are you " | grep -shoP ".*? "

Just make sure you append a space to each one of your lines

(Mine was a line by line search to spit out words)

Writing a new line to file in PHP (line feed)

PHP_EOL is a predefined constant in PHP since PHP 4.3.10 and PHP 5.0.2. See the manual posting:

Using this will save you extra coding on cross platform developments.

IE.

$data = 'some data'.PHP_EOL;
$fp = fopen('somefile', 'a');
fwrite($fp, $data);

If you looped through this twice you would see in 'somefile':

some data
some data

How to change the href for a hyperlink using jQuery

Try

link.href = 'https://...'

_x000D_
_x000D_
link.href = 'https://stackoverflow.com'
_x000D_
<a id="link" href="#">Click me</a>
_x000D_
_x000D_
_x000D_

VBA Macro to compare all cells of two Excel files

Do NOT loop through all cells!! There is a lot of overhead in communications between worksheets and VBA, for both reading and writing. Looping through all cells will be agonizingly slow. I'm talking hours.

Instead, load an entire sheet at once into a Variant array. In Excel 2003, this takes about 2 seconds (and 250 MB of RAM). Then you can loop through it in no time at all.

In Excel 2007 and later, sheets are about 1000 times larger (1048576 rows × 16384 columns = 17 billion cells, compared to 65536 rows × 256 columns = 17 million in Excel 2003). You will run into an "Out of memory" error if you try to load the whole sheet into a Variant; on my machine I can only load 32 million cells at once. So you have to limit yourself to the range you know has actual data in it, or load the sheet bit by bit, e.g. 30 columns at a time.

Option Explicit

Sub test()

    Dim varSheetA As Variant
    Dim varSheetB As Variant
    Dim strRangeToCheck As String
    Dim iRow As Long
    Dim iCol As Long

    strRangeToCheck = "A1:IV65536"
    ' If you know the data will only be in a smaller range, reduce the size of the ranges above.
    Debug.Print Now
    varSheetA = Worksheets("Sheet1").Range(strRangeToCheck)
    varSheetB = Worksheets("Sheet2").Range(strRangeToCheck) ' or whatever your other sheet is.
    Debug.Print Now

    For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
        For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
            If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then
                ' Cells are identical.
                ' Do nothing.
            Else
                ' Cells are different.
                ' Code goes here for whatever it is you want to do.
            End If
        Next iCol
    Next iRow

End Sub

To compare to a sheet in a different workbook, open that workbook and get the sheet as follows:

Set wbkA = Workbooks.Open(filename:="C:\MyBook.xls")
Set varSheetA = wbkA.Worksheets("Sheet1") ' or whatever sheet you need

oracle sql: update if exists else insert

HC-way :)

DECLARE
  rt_mytable mytable%ROWTYPE;
  CURSOR update_mytable_cursor(p_rt_mytable IN mytable%ROWTYPE) IS
  SELECT *
  FROM   mytable
  WHERE  ID = p_rt_mytable.ID
  FOR UPDATE;
BEGIN
  rt_mytable.ID   := 1;
  rt_mytable.NAME := 'x';
  INSERT INTO mytable VALUES (rt_mytable);
EXCEPTION WHEN DUP_VAL_ON_INDEX THEN
  <<update_mytable>>
  FOR i IN update_mytable_cursor(rt_mytable) LOOP
    UPDATE mytable SET    
      NAME = p_rt_mytable.NAME
    WHERE CURRENT OF update_mytable_cursor;
  END LOOP update_mytable;
END;

When should I use GC.SuppressFinalize()?

SuppressFinalize should only be called by a class that has a finalizer. It's informing the Garbage Collector (GC) that this object was cleaned up fully.

The recommended IDisposable pattern when you have a finalizer is:

public class MyClass : IDisposable
{
    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                // called via myClass.Dispose(). 
                // OK to use any private object references
            }
            // Release unmanaged resources.
            // Set large fields to null.                
            disposed = true;
        }
    }

    public void Dispose() // Implement IDisposable
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~MyClass() // the finalizer
    {
        Dispose(false);
    }
}

Normally, the CLR keeps tabs on objects with a finalizer when they are created (making them more expensive to create). SuppressFinalize tells the GC that the object was cleaned up properly and doesn't need to go onto the finalizer queue. It looks like a C++ destructor, but doesn't act anything like one.

The SuppressFinalize optimization is not trivial, as your objects can live a long time waiting on the finalizer queue. Don't be tempted to call SuppressFinalize on other objects mind you. That's a serious defect waiting to happen.

Design guidelines inform us that a finalizer isn't necessary if your object implements IDisposable, but if you have a finalizer you should implement IDisposable to allow deterministic cleanup of your class.

Most of the time you should be able to get away with IDisposable to clean up resources. You should only need a finalizer when your object holds onto unmanaged resources and you need to guarantee those resources are cleaned up.

Note: Sometimes coders will add a finalizer to debug builds of their own IDisposable classes in order to test that code has disposed their IDisposable object properly.

public void Dispose() // Implement IDisposable
{
    Dispose(true);
#if DEBUG
    GC.SuppressFinalize(this);
#endif
}

#if DEBUG
~MyClass() // the finalizer
{
    Dispose(false);
}
#endif

Correct way to set Bearer token with CURL

Replace:

$authorization = "Bearer 080042cad6356ad5dc0a720c18b53b8e53d4c274"

with:

$authorization = "Authorization: Bearer 080042cad6356ad5dc0a720c18b53b8e53d4c274";

to make it a valid and working Authorization header.

How to call javascript function on page load in asp.net

use your code within

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

        var d = new Date()
        var gmtOffSet = -d.getTimezoneOffset();
        var gmtHours = Math.floor(gmtOffSet / 60);
        var GMTMin = Math.abs(gmtOffSet % 60);
        var dot = ".";
        var retVal = "" + gmtHours + dot + GMTMin;
       document.getElementById('<%= offSet.ClientID%>').value = retVal;

      }
  </script>

JavaScript chop/slice/trim off last character in string

The easiest method is to use the slice method of the string, which allows negative positions (corresponding to offsets from the end of the string):

const s = "your string";
const withoutLastFourChars = s.slice(0, -4);

If you needed something more general to remove everything after (and including) the last underscore, you could do the following (so long as s is guaranteed to contain at least one underscore):

_x000D_
_x000D_
const s = "your_string";_x000D_
const withoutLastChunk = s.slice(0, s.lastIndexOf("_"));_x000D_
console.log(withoutLastChunk);
_x000D_
_x000D_
_x000D_

Constructors in Go

I like the explanation from this blog post:

The function New is a Go convention for packages that create a core type or different types for use by the application developer. Look at how New is defined and implemented in log.go, bufio.go and cypto.go:

log.go

// New creates a new Logger. The out variable sets the
// destination to which log data will be written.
// The prefix appears at the beginning of each generated log line.
// The flag argument defines the logging properties.
func New(out io.Writer, prefix string, flag int) * Logger {
    return &Logger{out: out, prefix: prefix, flag: flag}
}

bufio.go

// NewReader returns a new Reader whose buffer has the default size.
func NewReader(rd io.Reader) * Reader {
    return NewReaderSize(rd, defaultBufSize)
}

crypto.go

// New returns a new hash.Hash calculating the given hash function. New panics
// if the hash function is not linked into the binary.
func (h Hash) New() hash.Hash {
    if h > 0 && h < maxHash {
        f := hashes[h]
        if f != nil {
            return f()
        }
    }
    panic("crypto: requested hash function is unavailable")
}

Since each package acts as a namespace, every package can have their own version of New. In bufio.go multiple types can be created, so there is no standalone New function. Here you will find functions like NewReader and NewWriter.

Pointtype command for gnuplot

You first have to tell Gnuplot to use a style that uses points, e.g. with points or with linespoints. Try for example:

plot sin(x) with points

Output:

Now try:

plot sin(x) with points pointtype 5

Output:

You may also want to look at the output from the test command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:

Preventing HTML and Script injections in Javascript

Try this method to convert a 'string that could potentially contain html code' to 'text format':

$msg = "<div></div>";
$safe_msg = htmlspecialchars($msg, ENT_QUOTES);
echo $safe_msg;

Hope this helps!

SQLite string contains other string query

While LIKE is suitable for this case, a more general purpose solution is to use instr, which doesn't require characters in the search string to be escaped. Note: instr is available starting from Sqlite 3.7.15.

SELECT *
  FROM TABLE  
 WHERE instr(column, 'cats') > 0;

Also, keep in mind that LIKE is case-insensitive, whereas instr is case-sensitive.

ORA-00904: invalid identifier

DEPARTMENT_CODE is not a column that exists in the table Team. Check the DDL of the table to find the proper column name.

Java Class.cast() vs. cast operator

I've only ever used Class.cast(Object) to avoid warnings in "generics land". I often see methods doing things like this:

@SuppressWarnings("unchecked")
<T> T doSomething() {
    Object o;
    // snip
    return (T) o;
}

It's often best to replace it by:

<T> T doSomething(Class<T> cls) {
    Object o;
    // snip
    return cls.cast(o);
}

That's the only use case for Class.cast(Object) I've ever come across.

Regarding compiler warnings: I suspect that Class.cast(Object) isn't special to the compiler. It could be optimized when used statically (i.e. Foo.class.cast(o) rather than cls.cast(o)) but I've never seen anybody using it - which makes the effort of building this optimization into the compiler somewhat worthless.

How to convert Java String into byte[]?

I know I'm a little late tothe party but thisworks pretty neat (our professor gave it to us)

public static byte[] asBytes (String s) {                   
           String tmp;
           byte[] b = new byte[s.length() / 2];
           int i;
           for (i = 0; i < s.length() / 2; i++) {
             tmp = s.substring(i * 2, i * 2 + 2);
             b[i] = (byte)(Integer.parseInt(tmp, 16) & 0xff);
           }
           return b;                                            //return bytes
    }

Query Mongodb on month, day, year... of a datetime

Dates are stored in their timestamp format. If you want everything that belongs to a specific month, query for the start and the end of the month.

var start = new Date(2010, 11, 1);
var end = new Date(2010, 11, 30);

db.posts.find({created_on: {$gte: start, $lt: end}});
//taken from http://cookbook.mongodb.org/patterns/date_range/

Creating a Jenkins environment variable using Groovy

For me the following worked on Jenkins 2.190.1 and was much simpler than some of the other workarounds:

matcher = manager.getLogMatcher('^.*Text we want comes next: (.*)$');

if (matcher.matches()) {
    def myVar = matcher.group(1);
    def envVar = new EnvVars([MY_ENV_VAR: myVar]);
    def newEnv = Environment.create(envVar);
    manager.build.environments.add(0, newEnv);
    // now the matched text from the LogMatcher is passed to an
    // env var we can access at $MY_ENV_VAR in post build steps
}

This was using the Groovy Script plugin with no additional changes to Jenkins.

Parsing boolean values with argparse

I think the most canonical way will be:

parser.add_argument('--ensure', nargs='*', default=None)

ENSURE = config.ensure is None

importing go files in same folder

I just wanted something really basic to move some files out of the main folder, like user2889485's reply, but his specific answer didnt work for me. I didnt care if they were in the same package or not.

My GOPATH workspace is c:\work\go and under that I have

/src/pg/main.go      (package main)
/src/pg/dbtypes.go   (pakage dbtypes)

in main.go I import "/pg/dbtypes"

How to preview an image before and after upload?

Try this: (For Preview)

<script type="text/javascript">
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

<body>
    <form id="form1" runat="server">
        <input type="file" onchange="readURL(this);" />
        <img id="blah" src="#" alt="your image" />
    </form>
</body>

Working Demo here>

Catching KeyboardInterrupt in Python during program shutdown

Checkout this thread, it has some useful information about exiting and tracebacks.

If you are more interested in just killing the program, try something like this (this will take the legs out from under the cleanup code as well):

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('Interrupted')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)

Do I need to pass the full path of a file in another directory to open()?

The examples to os.walk in the documentation show how to do this:

for root, dirs, filenames in os.walk(indir):
    for f in filenames:
        log = open(os.path.join(root, f),'r')

How did you expect the "open" function to know that the string "1" is supposed to mean "/home/des/test/1" (unless "/home/des/test" happens to be your current working directory)?

Python Requests package: Handling xml response

requests does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.

Python comes with built-in XML parsers. I recommend you use the ElementTree API:

import requests
from xml.etree import ElementTree

response = requests.get(url)

tree = ElementTree.fromstring(response.content)

or, if the response is particularly large, use an incremental approach:

    response = requests.get(url, stream=True)
    # if the server sent a Gzip or Deflate compressed response, decompress
    # as we read the raw stream:
    response.raw.decode_content = True

    events = ElementTree.iterparse(response.raw)
    for event, elem in events:
        # do something with `elem`

The external lxml project builds on the same API to give you more features and power still.

React: trigger onChange if input value is changing by state?

you must do 4 following step :

  1. create event

    var event = new Event("change",{
        detail: {
            oldValue:yourValueVariable,
            newValue:!yourValueVariable
        },
        bubbles: true,
        cancelable: true
    });
    event.simulated = true;
    let tracker = this.yourComponentDomRef._valueTracker;
    if (tracker) {
        tracker.setValue(!yourValueVariable);
    }
    
  2. bind value to component dom

    this.yourComponentDomRef.value = !yourValueVariable;
    
  3. bind element onchange to react onChange function

     this.yourComponentDomRef.onchange = (e)=>this.props.onChange(e);
    
  4. dispatch event

    this.yourComponentDomRef.dispatchEvent(event);
    

in above code yourComponentDomRef refer to master dom of your React component for example <div className="component-root-dom" ref={(dom)=>{this.yourComponentDomRef= dom}}>

What is "pom" packaging in maven?

Real life use case

At a Java-heavy company we had a python project that needed to go into a Nexus artifact repository. Python doesn't really have binaries, so simply just wanted to .tar or .zip the python files and push. The repo already had maven integration, so we used <packaging>pom</packaging> designator with the maven assembly plugin to package the python project as a .zip and upload it.

The steps are outlined in this SO post

How to do sed like text replace with python?

massedit.py (http://github.com/elmotec/massedit) does the scaffolding for you leaving just the regex to write. It's still in beta but we are looking for feedback.

python -m massedit -e "re.sub(r'^# deb', 'deb', line)" /etc/apt/sources.list

will show the differences (before/after) in diff format.

Add the -w option to write the changes to the original file:

python -m massedit -e "re.sub(r'^# deb', 'deb', line)" -w /etc/apt/sources.list

Alternatively, you can now use the api:

>>> import massedit
>>> filenames = ['/etc/apt/sources.list']
>>> massedit.edit_files(filenames, ["re.sub(r'^# deb', 'deb', line)"], dry_run=True)

How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

Four fewer characters, but 2 more ms

%%timeit
df.isna().T.any()
# 52.4 ms ± 352 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
df.isna().any(axis=1)
# 50 ms ± 423 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

I'd probably use axis=1

Purpose of Unions in C and C++

Others have mentioned the architecture differences (little - big endian).

I read the problem that since the memory for the variables is shared, then by writing to one, the others change and, depending on their type, the value could be meaningless.

eg. union{ float f; int i; } x;

Writing to x.i would be meaningless if you then read from x.f - unless that is what you intended in order to look at the sign, exponent or mantissa components of the float.

I think there is also an issue of alignment: If some variables must be word aligned then you might not get the expected result.

eg. union{ char c[4]; int i; } x;

If, hypothetically, on some machine a char had to be word aligned then c[0] and c[1] would share storage with i but not c[2] and c[3].

How do I write to a Python subprocess' stdin?

It might be better to use communicate:

from subprocess import Popen, PIPE, STDOUT
p = Popen(['myapp'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
stdout_data = p.communicate(input='data_to_write')[0]

"Better", because of this warning:

Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.

Get AVG ignoring Null or Zero values

In Case of not considering '0' or 'NULL' in average function. Simply use

AVG(NULLIF(your_column_name,0))

What is the correct target for the JAVA_HOME environment variable for a Linux OpenJDK Debian-based distribution?

I usually don't have any JAVA_HOME environment variable. Java can set it up itself. Inside java java.home system property should be available.

How to Create Multiple Where Clause Query Using Laravel Eloquent?

As per my suggestion if you are doing filter or searching

then you should go with :

        $results = User::query();
        $results->when($request->that, function ($q) use ($request) {
            $q->where('that', $request->that);
        });
        $results->when($request->this, function ($q) use ($request) {
            $q->where('this', $request->that);
        });
        $results->when($request->this_too, function ($q) use ($request) {
            $q->where('this_too', $request->that);
        });
        $results->get();