Programs & Examples On #Antiforgerytoken

Cryptographic Nonce for anti-CSRF protection

jQuery Ajax calls and the Html.AntiForgeryToken()

Here is the easiest way I've seen. Note: Make sure you have "@Html.AntiForgeryToken()" in your View

  $("a.markAsDone").click(function (event) {
        event.preventDefault();
        var sToken = document.getElementsByName("__RequestVerificationToken")[0].value;
        $.ajax({
            url: $(this).attr("rel"),
            type: "POST",
            contentType: "application/x-www-form-urlencoded",
            data: { '__RequestVerificationToken': sToken, 'id': parseInt($(this).attr("title")) }
        })
        .done(function (data) {
            //Process MVC Data here
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            //Process Failure here
        });
    });

Calculating Time Difference

The datetime module will do all the work for you:

>>> import datetime
>>> a = datetime.datetime.now()
>>> # ...wait a while...
>>> b = datetime.datetime.now()
>>> print(b-a)
0:03:43.984000

If you don't want to display the microseconds, just use (as gnibbler suggested):

>>> a = datetime.datetime.now().replace(microsecond=0)
>>> b = datetime.datetime.now().replace(microsecond=0)
>>> print(b-a)
0:03:43

How to start MySQL server on windows xp

You need to run the server first. The command you use (in the question) starts a client to connect to the server but the server is not there so there the error.

Since I am not a Windows user (Linux comes equipped) so I might not be the best person to tell you how but I can point to you to a guide and another guide that show you how to get MySQL server up and running in Windows.

After you get that running, you can use the command (in the question) to connect it.

NOTE: You may also try http://www.apachefriends.org/en/xampp.html if you plan to use MySQL for web database development.

Hope this helps.

How to save CSS changes of Styles panel of Chrome Developer Tools?

I know it is an old post, but I save it this way :

  1. Go to Sources pane.
  2. Click Show Navigator (to show the navigator pane on left).enter image description here
  3. Click the CSS file you want. (It will open in the editor, with all changes you made)
  4. Right click on editor and Save your changes.

You can also see Local Modifications to see your revisions, very interesting feature. Also work with scripts.

How to change spinner text size and text color?

Simple and crisp...:

private OnItemSelectedListener OnCatSpinnerCL = new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

       ((TextView) parent.getChildAt(0)).setTextColor(Color.BLUE);
       ((TextView) parent.getChildAt(0)).setTextSize(5);

    }

    public void onNothingSelected(AdapterView<?> parent) {

    }
};

Should I use alias or alias_method?

A year after asking the question comes a new article on the subject:

http://erniemiller.org/2014/10/23/in-defense-of-alias/

It seems that "so many men, so many minds." From the former article author encourages to use alias_method, while the latter suggests using alias.

However there's a common overview of these methods in both blogposts and answers above:

  • use alias when you want to limit aliasing to the scope where it's defined
  • use alias_method to allow inherited classes to access it

SQL Query to search schema of all tables

You can also try doing this using one of many third party tools that are available for this.

Queries are great for simple searches but if you need to do more manipulation with data, search for references and such this is where you can do a much better job with these.

Also, these come in very handy when some objects are encrypted and you need to search for

I’m using ApexSQL Search which is free but there are also many more (also free) on the market such as Red Gate or SSMS Tool Pack.

how to define variable in jquery

In jquery, u can delcare variable two styles.

One is,

$.name = 'anirudha';
alert($.name);

Second is,

var hText = $("#head1").text();

Second is used when you read data from textbox, label, etc.

HTML embed autoplay="false", but still plays automatically

Just change the mime type to: type="audio/mpeg", this way chrome will honor the autostart="false" parameter.

Can a foreign key refer to a primary key in the same table?

Other answers have given clear enough examples of a record referencing another record in the same table.

There are even valid use cases for a record referencing itself in the same table. For example, a point of sale system accepting many tenders may need to know which tender to use for change when the payment is not the exact value of the sale. For many tenders that's the same tender, for others that's domestic cash, for yet other tenders, no form of change is allowed.

All this can be pretty elegantly represented with a single tender attribute which is a foreign key referencing the primary key of the same table, and whose values sometimes match the respective primary key of same record. In this example, the absence of value (also known as NULL value) might be needed to represent an unrelated meaning: this tender can only be used at its full value.

Popular relational database management systems support this use case smoothly.

Take-aways:

  1. When inserting a record, the foreign key reference is verified to be present after the insert, rather than before the insert.

  2. When inserting multiple records with a single statement, the order in which the records are inserted matters. The constraints are checked for each record separately.

  3. Certain other data patterns, such as those involving circular dependences on record level going through two or more tables, cannot be purely inserted at all, or at least not with all the foreign keys enabled, and they have to be established using a combination of inserts and updates (if they are truly necessary).

How to sort 2 dimensional array by column value?

It's this simple:

var a = [[12, 'AAA'], [58, 'BBB'], [28, 'CCC'],[18, 'DDD']];

a.sort(sortFunction);

function sortFunction(a, b) {
    if (a[0] === b[0]) {
        return 0;
    }
    else {
        return (a[0] < b[0]) ? -1 : 1;
    }
}

I invite you to read the documentation.

If you want to sort by the second column, you can do this:

a.sort(compareSecondColumn);

function compareSecondColumn(a, b) {
    if (a[1] === b[1]) {
        return 0;
    }
    else {
        return (a[1] < b[1]) ? -1 : 1;
    }
}

Minimal web server using netcat

I think the problem that all the solution listed doesn't work, is intrinsic in the nature of http service, the every request established is with a different client and the response need to be processed in a different context, every request must fork a new instance of response...

The current solution I think is the -e of netcat but I don't know why doesn't work... maybe is my nc version that I test on openwrt...

with socat it works....

I try this https://github.com/avleen/bashttpd

and it works, but I must run the shell script with this command.

socat tcp-l:80,reuseaddr,fork EXEC:bashttpd &

The socat and netcat samples on github doesn't works for me, but the socat that I used works.

How to write a CSS hack for IE 11?

You can use the following code inside the style tag:

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {  
/* IE10+ specific styles go here */  
}

Below is an example that worked for me:

<style type="text/css">

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {  
   /* IE10+ specific styles go here */  
   #flashvideo {
        width:320px;
        height:240;
        margin:-240px 0 0 350px;
        float:left;
    }

    #googleMap {
        width:320px;
        height:240;
        margin:-515px 0 0 350px;
        float:left;
        border-color:#000000;
    }
}

#nav li {
    list-style:none;
    width:240px;
    height:25px;
    }

#nav a {
    display:block;
    text-indent:-5000px;
    height:25px;
    width:240px;
    }
</style>

Please note that since (#nav li) and (#nav a) are outside of the @media screen ..., they are general styles.

PHP - Notice: Undefined index:

You're getting errors because you're attempting to read post variables that haven't been set, they only get set on form submission. Wrap your php code at the bottom in an

if ($_SERVER['REQUEST_METHOD'] === 'POST') { ... }

Also, your code is ripe for SQL injection. At the very least use mysql_real_escape_string on the post vars before using them in SQL queries. mysql_real_escape_string is not good enough for a production site, but should score you extra points in class.

How to get last inserted id?

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[spCountNewLastIDAnyTableRows]
(
@PassedTableName as NVarchar(255),
@PassedColumnName as NVarchar(225)
)
AS
BEGIN
DECLARE @ActualTableName AS NVarchar(255)
DECLARE @ActualColumnName as NVarchar(225)
    SELECT @ActualTableName = QUOTENAME( TABLE_NAME )
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_NAME = @PassedTableName
    SELECT @ActualColumnName = QUOTENAME( COLUMN_NAME )
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE COLUMN_NAME = @PassedColumnName
    DECLARE @sql AS NVARCHAR(MAX)
    SELECT @sql = 'select MAX('+ @ActualColumnName + ') + 1  as LASTID' + ' FROM ' + @ActualTableName 
    EXEC(@SQL)
END

Xcopy Command excluding files and folders

Just give full path to exclusion file: eg..

-- no - - - - -xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt

correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\list-of-excluded-files.txt

In this example the file would be located " C:\list-of-excluded-files.txt "

or...

correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\mybatch\list-of-excluded-files.txt

In this example the file would be located " C:\mybatch\list-of-excluded-files.txt "

Full path fixes syntax error.

Python - round up to the nearest ten

This will round down correctly as well:

>>> n = 46
>>> rem = n % 10
>>> if rem < 5:
...     n = int(n / 10) * 10
... else:
...     n = int((n + 10) / 10) * 10
...
>>> 50

Limit on the WHERE col IN (...) condition

Depending on the database engine you are using, there can be limits on the length of an instruction.

SQL Server has a very large limit:

http://msdn.microsoft.com/en-us/library/ms143432.aspx

ORACLE has a very easy to reach limit on the other side.

So, for large IN clauses, it's better to create a temp table, insert the values and do a JOIN. It works faster also.

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

What is 0x10 in decimal?

0x means the number is hexadecimal, or base 16.

0x10 is 16.

How to center cell contents of a LaTeX table whose columns have fixed widths?

You can use \centering with your parbox to do this.

More info here and here.

(Sorry for the Google cached link; the original one I had doesn't work anymore.)

How can I customize the tab-to-space conversion factor?

By default, Visual Studio Code auto-detects the indentation of the current open file. If you want to switch this feature off and make all indentation, for example, two spaces, you'd do the following in your User Settings or Workspace settings.

{
    "editor.tabSize": 2,

    "editor.detectIndentation": false
}

How can I remove a commit on GitHub?

For GitHub

  • Reset your commits (HARD) in your local repository
  • Create a new branch
  • Push the new branch
  • Delete OLD branch (Make new one as the default branch if you are deleting the master branch)

Elegant way to report missing values in a data.frame

If you want to do it for particular column, then you can also use this

length(which(is.na(airquality[1])==T))

jQuery if statement to check visibility

 $('#column-left form').hide();
 $('.show-search').click(function() {
    $('#column-left form').stop(true, true).slideToggle(300); //this will slide but not hide that's why
    $('#column-left form').hide(); 
    if(!($('#column-left form').is(":visible"))) {
        $("#offers").show();
    } else {
        $('#offers').hide();
    }
  });

How to kill all processes matching a name?

From man 1 pkill

-f     The pattern is normally only matched against the process name.
       When -f is set, the full command line is used.

Which means, for example, if we see these lines in ps aux:

apache   24268  0.0  2.6 388152 27116 ?        S    Jun13   0:10 /usr/sbin/httpd
apache   24272  0.0  2.6 387944 27104 ?        S    Jun13   0:09 /usr/sbin/httpd
apache   24319  0.0  2.6 387884 27316 ?        S    Jun15   0:04 /usr/sbin/httpd

We can kill them all using the pkill -f option:

pkill -f httpd

Including a groovy script in another groovy

Groovy doesn't have an import keyword like typical scripting languages that will do a literal include of another file's contents (alluded to here: Does groovy provide an include mechanism?).
Because of its object/class oriented nature, you have to "play games" to make things like this work. One possibility is to make all your utility functions static (since you said they don't use objects) and then perform a static import in the context of your executing shell. Then you can call these methods like "global functions".
Another possibility would be using a Binding object (http://groovy.codehaus.org/api/groovy/lang/Binding.html) while creating your Shell and binding all the functions you want to the methods (the downside here would be having to enumerate all methods in the binding but you could perhaps use reflection). Yet another solution would be to override methodMissing(...) in the delegate object assigned to your shell which allows you to basically do dynamic dispatch using a map or whatever method you'd like.

Several of these methods are demonstrated here: http://www.nextinstruction.com/blog/2012/01/08/creating-dsls-with-groovy/. Let me know if you want to see an example of a particular technique.

Batch file to split .csv file

This will give you lines 1 to 20000 in newfile1.csv
and lines 20001 to the end in file newfile2.csv

It overcomes the 8K character limit per line too.

This uses a helper batch file called findrepl.bat from - https://www.dropbox.com/s/rfdldmcb6vwi9xc/findrepl.bat

Place findrepl.bat in the same folder as the batch file or on the path.

It's more robust than a plain batch file, and quicker too.

findrepl /o:1:20000 <file.csv >newfile1.csv
findrepl /o:20001   <file.csv >newfile2.csv

Why dividing two integers doesn't get a float?

Probably the best reason is because 0xfffffffffffffff/15 would give you a horribly wrong answer...

Google Play Services Missing in Emulator (Android 4.4.2)

google play service is just a library to create application but in order to use application that use google play service library , you need to install google play in your emulator.and for that it need the unique device id. and device id is only on the real device not have on emulator. so for testing it , you need real android device.

Java "user.dir" property - what exactly does it mean?

System.getProperty("user.dir") fetches the directory or path of the workspace for the current project

iOS 7 UIBarButton back button arrow color

In iOS 7, you can put the following line of code inside application:didFinishLaunchingWithOptions: in your AppDelegate.m file:

[[UINavigationBar appearance] setTintColor:myColor];

Set myColor to the color you want the back button to be throughout the entire app. No need to put it in every file.

Remove shadow below actionbar

For Xamarin Developers, please use : SupportActionBar.Elevation = 0; for AppCompatActivity or ActionBar.Elevation = 0; for non-compat Activities

PDO's query vs execute

query runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.

execute runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. execute will also perform better if you are repeating a query multiple times. Example of prepared statements:

$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories);
$sth->bindParam(':colour', $colour);
$sth->execute();
// $calories or $color do not need to be escaped or quoted since the
//    data is separated from the query

Best practice is to stick with prepared statements and execute for increased security.

See also: Are PDO prepared statements sufficient to prevent SQL injection?

Location for session files in Apache/PHP

Non of the above worked for me using the IUS repo for CentOS 7 with PHP 7.2:

php -v
> PHP 7.2.30 (cli) (built: Apr 19 2020 00:32:29) ( NTS )

php -r 'echo session_save_path(), "\n";
> 

php -r 'echo sys_get_temp_dir(), "\n";'
> /tmp

However, sessions weren't saved in the /tmp folder, but in the /var/lib/php/mod_php/session/ folder:

ls /var/lib/php/mod_php/session/
> sess_3cebqoq314pcnc2jgqiu840h0k  sess_ck5dtaerol28fpctj6nutbn6fn  sess_i24lgt2v2l58op5kfmj1k6qb3h  sess_nek5q1alop8fkt84gliie91703
> sess_9ff74f4q5ihccnv6com2a8409t  sess_dvrt9fmfuolr8bqt9efdpcbj0d  sess_igdaksn26hm1s5nfvtjfb53pl7  sess_tgf5b7gkgno8kuvl966l9ce7nn

Reset select value to default

A simple way that runs is

 var myselect = $("select.SimpleAddAClass");
 myselect[0].selectedIndex = 0;
 myselect.selectmenu("refresh");

How to check existence of user-define table type in SQL Server 2008?

IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = 'MyType')
    --stuff

sys.types... they aren't schema-scoped objects so won't be in sys.objects

Update, Mar 2013

You can use TYPE_ID too

View a file in a different Git branch without changing branches

Add the following to your ~/.gitconfig file

[alias]
  cat = "!git show \"$1:$2\" #"

And then try this

git cat BRANCHNAME FILEPATH

Personally I prefer separate parameters without a colon. Why? This choice mirrors the parameters of the checkout command, which I tend to use rather frequently and I find it thus much easier to remember than the bizarro colon-separated parameter of the show command.

Opening Android Settings programmatically

Check out the Programmatically Displaying the Settings Page

    startActivity(context, new Intent(Settings.ACTION_SETTINGS), /*options:*/ null);

In general, you use the predefined constant Settings.ACTION__SETTINGS. The full list can be found here

How to use OKHTTP to make a post request?

private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    RequestBody formBody = new FormEncodingBuilder()
        .add("search", "Jurassic Park")
        .build();
    Request request = new Request.Builder()
        .url("https://en.wikipedia.org/w/index.php")
        .post(formBody)
        .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
  }

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1

Can you try to change your json without data key like below?

[{"target_id":9503123,"target_type":"user"}]

MySQL Check if username and password matches in Database

Instead of selecting all the columns in count count(*) you can limit count for one column count(UserName).

You can limit the whole search to one row by using Limit 0,1

SELECT COUNT(UserName)
  FROM TableName
 WHERE UserName = 'User' AND
       Password = 'Pass'
 LIMIT 0, 1

Full Screen DialogFragment in Android

Worked for me in Kotlin,

 override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)

    dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)

}

How do I get the current absolute URL in Ruby on Rails?

You can use the ruby method:

:root_url

which will get the full path with base url:

localhost:3000/bla

Convert Python program to C/C++ code?

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

git add, commit and push commands in one?

I did this .sh script for command

#!/bin/sh
cd LOCALDIRECTORYNAME/  
git config --global user.email "YOURMAILADDRESS"
git config --global user.name "YOURUSERNAME"
git init
git status
git add -A && git commit -m "MASSAGEFORCOMMITS"
git push origin master

How do I iterate through lines in an external file with shell?

cat names.txt|while read line; do
    echo "$line";
done

Java: getMinutes and getHours

int hr=Time.valueOf(LocalTime.now()).getHours();
int minutes=Time.valueOf(LocalTime.now()).getMinutes();

These functions will return int values in hours and minutes.

PackagesNotFoundError: The following packages are not available from current channels:

Thanks, Max S. conda-forge worked for me as well.

scikit-learn on Anaconda-Jupyter Notebook.

Upgrading my scikit-learn from 0.19.1 to 0.19.2 in anaconda installed on Ubuntu on Google VM instance:

Run the following commands in the terminal:

First, check available the packages with versions

conda list    

It will show packages and their installed versions in the output:

scikit-learn              0.19.1           py36hedc7406_0  

Upgrade to 0.19.2 July 2018 release.

conda config --append channels conda-forge
conda install scikit-learn=0.19.2

Now check the version installed correctly or not?

conda list 

Output is:

scikit-learn              0.19.2          py36_blas_openblasha84fab4_201  [blas_openblas]  conda-forge

Note: Don't use pip command if you are using Anaconda or Miniconda

I tried following commands:

!conda update conda 
!pip install -U scikit-learn

It will install the required packages also will show in the conda list but when try to import that package it will not work.

On the website http://scikit-learn.org/stable/install.html it is mentioned as: Warning To upgrade or uninstall scikit-learn installed with Anaconda or conda you should not use the pip.

How to create JNDI context in Spring Boot with Embedded Tomcat Container

Please note instead of

public TomcatEmbeddedServletContainerFactory tomcatFactory()

I had to use the following method signature

public EmbeddedServletContainerFactory embeddedServletContainerFactory() 

Javascript: How to generate formatted easy-to-read JSON straight from an object?

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

How to get index of an item in java.util.Set

One solution (though not very pretty) is to use Apache common List/Set mutation

import org.apache.commons.collections.list.SetUniqueList;

final List<Long> vertexes=SetUniqueList.setUniqueList(new LinkedList<>());

it is a list without duplicates

https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.2/index.html?org/apache/commons/collections/list/SetUniqueList.html

AngularJS ui router passing data between states without URL

The params object is included in $stateParams, but won't be part of the url.

1) In the route configuration:

$stateProvider.state('edit_user', {
    url: '/users/:user_id/edit',
    templateUrl: 'views/editUser.html',
    controller: 'editUserCtrl',
    params: {
        paramOne: { objectProperty: "defaultValueOne" },  //default value
        paramTwo: "defaultValueTwo"
    }
});

2) In the controller:

.controller('editUserCtrl', function ($stateParams, $scope) {       
    $scope.paramOne = $stateParams.paramOne;
    $scope.paramTwo = $stateParams.paramTwo;
});

3A) Changing the State from a controller

$state.go("edit_user", {
    user_id: 1,                
    paramOne: { objectProperty: "test_not_default1" },
    paramTwo: "from controller"
});

3B) Changing the State in html

<div ui-sref="edit_user({ user_id: 3, paramOne: { objectProperty: 'from_html1' }, paramTwo: 'fromhtml2' })"></div>

Example Plunker

ipynb import another ipynb file

Run

!pip install ipynb

and then import the other notebook as

from ipynb.fs.full.<notebook_name> import *

or

from ipynb.fs.full.<notebook_name> import <function_name>

Make sure that all the notebooks are in the same directory.

Edit 1: You can see the official documentation here - https://ipynb.readthedocs.io/en/stable/

Also, if you would like to import only class & function definitions from a notebook (and not the top level statements), you can use ipynb.fs.defs instead of ipynb.fs.full. Full uppercase variable assignment will get evaluated as well.

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

Because C will promote floats to doubles for functions that take variable arguments. Pointers aren't promoted to anything, so you should be using %lf, %lg or %le (or %la in C99) to read in doubles.

comma separated string of selected values in mysql

Try this

SELECT CONCAT('"',GROUP_CONCAT(id),'"') FROM table_level 
where parent_id=4 group by parent_id;

Result will be

 "5,6,9,10,12,14,15,17,18,779"

Adding a Button to a WPF DataGrid

First create a DataGridTemplateColumn to contain the button:

<DataGridTemplateColumn>
  <DataGridTemplateColumn.CellTemplate> 
    <DataTemplate> 
      <Button Click="ShowHideDetails">Details</Button> 
    </DataTemplate> 
  </DataGridTemplateColumn.CellTemplate> 
</DataGridTemplateColumn>

When the button is clicked, update the containing DataGridRow's DetailsVisibility:

void ShowHideDetails(object sender, RoutedEventArgs e)
{
    for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
    if (vis is DataGridRow)
    {
        var row = (DataGridRow)vis;
        row.DetailsVisibility = 
        row.DetailsVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
        break;
    }
}

Why a function checking if a string is empty always returns true?

PHP evaluates an empty string to false, so you can simply use:

if (trim($userinput['phoneNumber'])) {
  // validate the phone number
} else {
  echo "Phone number not entered<br/>";
}

From io.Reader to string in Go

var b bytes.Buffer
b.ReadFrom(r)

// b.String()

Multiple -and -or in PowerShell Where-Object statement

By wrapping your comparisons in {} in your first example you are creating ScriptBlocks; so the PowerShell interpreter views it as Where-Object { <ScriptBlock> -and <ScriptBlock> }. Since the -and operator operates on boolean values, PowerShell casts the ScriptBlocks to boolean values. In PowerShell anything that is not empty, zero or null is true. The statement then looks like Where-Object { $true -and $true } which is always true.

Instead of using {}, use parentheses ().

Also you want to use -eq instead of -match since match uses regex and will be true if the pattern is found anywhere in the string (try: 'xlsx' -match 'xls').

Invoke-Command -computername SERVERNAME { 
    Get-ChildItem -path E:\dfsroots\datastore2\public | 
        Where-Object {($_.extension -eq ".xls" -or $_.extension -eq ".xlk") -and ($_.creationtime -ge "06/01/2014")}
}

A better option is to filter the extensions at the Get-ChildItem command.

Invoke-Command -computername SERVERNAME { 
    Get-ChildItem -path E:\dfsroots\datastore2\public\* -Include *.xls, *.xlk | 
        Where-Object {$_.creationtime -ge "06/01/2014"}
}

Two submit buttons in one form

An even better solution consists of using button tags to submit the form:

<form>
    ...
    <button type="submit" name="action" value="update">Update</button>
    <button type="submit" name="action" value="delete">Delete</button>
</form>

The HTML inside the button (e.g. ..>Update<.. is what is seen by the user; because there is HTML provided, the value is not user-visible; it is only sent to server. This way there is no inconvenience with internationalization and multiple display languages (in the former solution, the label of the button is also the value sent to the server).

Can I add extension methods to an existing static class?

I stumbled upon this thread while trying to find an answer to the same question the OP had. I didn't find the answer I wanted, but I ended up doing this.

public static class MyConsole
{
    public static void WriteLine(this ConsoleColor Color, string Text)
    {
        Console.ForegroundColor = Color;
        Console.WriteLine(Text);   
    }
}

And I use it like this:

ConsoleColor.Cyan.WriteLine("voilà");

What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/bugmailer.sh must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948

And this one: http://forum.xda-developers.com/showthread.php?t=1405639

Passing dynamic javascript values using Url.action()

The easiest way is:

  onClick= 'location.href="/controller/action/"+paramterValue'

Unable to execute dex: Multiple dex files define

If some of you facing this problem with facebook-connent-plugin for phonegap

try to remove files in bin/class/com/facebook/android directory ! -> and rebuild

To switch from vertical split to horizontal split fast in Vim

Following Mark Rushakoff's tip above, here is my mapping:

" vertical to horizontal ( | -> -- )
noremap <c-w>-  <c-w>t<c-w>K
" horizontal to vertical ( -- -> | )
noremap <c-w>\|  <c-w>t<c-w>H
noremap <c-w>\  <c-w>t<c-w>H
noremap <c-w>/  <c-w>t<c-w>H

Edit: use Ctrl-w r to swap two windows if they are not in the good order.

Right way to split an std::string into a vector<string>

vector<string> split(string str, string token){
    vector<string>result;
    while(str.size()){
        int index = str.find(token);
        if(index!=string::npos){
            result.push_back(str.substr(0,index));
            str = str.substr(index+token.size());
            if(str.size()==0)result.push_back(str);
        }else{
            result.push_back(str);
            str = "";
        }
    }
    return result;
}

split("1,2,3",",") ==> ["1","2","3"]

split("1,2,",",") ==> ["1","2",""]

split("1token2token3","token") ==> ["1","2","3"]

Why can't overriding methods throw exceptions broader than the overridden method?

What explanation do we attribute to the below

class BaseClass {

    public  void print() {
        System.out.println("In Parent Class , Print Method");
    }

    public static void display() {
        System.out.println("In Parent Class, Display Method");
    }

}


class DerivedClass extends BaseClass {

    public  void print() throws Exception {
        System.out.println("In Derived Class, Print Method");
    }

    public static void display() {
        System.out.println("In Derived Class, Display Method");
    }
}

Class DerivedClass.java throws a compile time exception when the print method throws a Exception , print () method of baseclass does not throw any exception

I am able to attribute this to the fact that Exception is narrower than RuntimeException , it can be either No Exception (Runtime error ), RuntimeException and their child exceptions

Accessing SQL Database in Excel-VBA

Is that a proper connection string?
Where is the SQL Server instance located?

You will need to verify that you are able to conenct to SQL Server using the connection string, you specified above.

EDIT: Look at the State property of the recordset to see if it is Open?
Also, change the CursorLocation property to adUseClient before opening the recordset.

How to convert a string variable containing time to time_t type in c++?

With C++11 you can now do

struct std::tm tm;
std::istringstream ss("16:35:12");
ss >> std::get_time(&tm, "%H:%M:%S"); // or just %T in this case
std::time_t time = mktime(&tm);

see std::get_time and strftime for reference

How can I properly handle 404 in ASP.NET MVC?

I have gone through all articles but nothing works for me: My requirement user type anything in your url custom 404 page should show.I thought it is very straight forward.But you should understand handling of 404 properly:

 <system.web>
    <customErrors mode="On" redirectMode="ResponseRewrite">
      <error statusCode="404" redirect="~/PageNotFound.aspx"/>
    </customErrors>
  </system.web>
<system.webServer>
    <httpErrors errorMode="Custom">
      <remove statusCode="404"/>
      <error statusCode="404" path="/PageNotFound.html" responseMode="ExecuteURL"/>
    </httpErrors>
</system.webServer>

I found this article very helpfull.should be read at once.Custome error page-Ben Foster

Force browser to clear cache

Do you want to clear the cache, or just make sure your current (changed?) page is not cached?

If the latter, it should be as simple as

<META HTTP-EQUIV="Pragma" CONTENT="no-cache">

Redirect non-www to www in .htaccess

The following example works on both ssl and non-ssl and is much faster as you use just one rule to manage http and https

RewriteEngine on


RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTPS}s on(s)|offs()
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R]

[Tested]

This will redirect

http

to

https

to

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

Getting JSONObject from JSONArray

{"syncresponse":{"synckey":"2011-09-30 14:52:00","createdtrs":[],"modtrs":[],"deletedtrs":[{"companyid":"UTB17","username":"DA","date":"2011-09-26","reportid":"31341"}]

The get companyid, username, date;

jsonObj.syncresponse.deletedtrs[0].companyid
jsonObj.syncresponse.deletedtrs[0].username
jsonObj.syncresponse.deletedtrs[0].date

What is a good pattern for using a Global Mutex in C#?

There is a race condition in the accepted answer when 2 processes running under 2 different users trying to initialize the mutex at the same time. After the first process initializes the mutex, if the second process tries to initialize the mutex before the first process sets the access rule to everyone, an unauthorized exception will be thrown by the second process.

See below for corrected answer:

using System.Runtime.InteropServices;   //GuidAttribute
using System.Reflection;                //Assembly
using System.Threading;                 //Mutex
using System.Security.AccessControl;    //MutexAccessRule
using System.Security.Principal;        //SecurityIdentifier

static void Main(string[] args)
{
    // get application GUID as defined in AssemblyInfo.cs
    string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();

    // unique id for global mutex - Global prefix means it is global to the machine
    string mutexId = string.Format( "Global\\{{{0}}}", appGuid );

    bool createdNew;
        // edited by Jeremy Wiebe to add example of setting up security for multi-user usage
        // edited by 'Marc' to work also on localized systems (don't use just "Everyone") 
        var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
        var securitySettings = new MutexSecurity();
        securitySettings.AddAccessRule(allowEveryoneRule);

        using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings))
        {

        // edited by acidzombie24
        var hasHandle = false;
        try
        {
            try
            {
                // note, you may want to time out here instead of waiting forever
                // edited by acidzombie24
                // mutex.WaitOne(Timeout.Infinite, false);
                hasHandle = mutex.WaitOne(5000, false);
                if (hasHandle == false)
                    throw new TimeoutException("Timeout waiting for exclusive access");
            }
            catch (AbandonedMutexException)
            {
                // Log the fact the mutex was abandoned in another process, it will still get aquired
                hasHandle = true;
            }

            // Perform your work here.
        }
        finally
        {
            // edited by acidzombie24, added if statemnet
            if(hasHandle)
                mutex.ReleaseMutex();
        }
    }
}

How to add an element at the end of an array?

one-liner with streams

Stream.concat(Arrays.stream( array ), Stream.of( newElement )).toArray();

Disabling of EditText in Android

In my case I needed my EditText to scroll text if no. of lines exceed maxLines when its disabled. This implementation worked perfectly for me.

private void setIsChatEditTextEditable(boolean value)
{
    if(value)
    {
        mEdittext.setCursorVisible(true);
        mEdittext.setSelection(chat_edittext.length());
       // use new EditText(getApplicationContext()).getKeyListener()) if required below
        mEdittext.setKeyListener(new AppCompatEditText(getApplicationContext()).getKeyListener());  
    }
    else
    {
        mEdittext.setCursorVisible(false);
        mEdittext.setKeyListener(null);
    }
}

Moving from position A to position B slowly with animation

I don't understand why other answers are about relative coordinates change, not absolute like OP asked in title.

$("#Friends").animate( {top:
  "-=" + (parseInt($("#Friends").css("top")) - 100) + "px"
} );

Alternative to mysql_real_escape_string without connecting to DB

Well, according to the mysql_real_escape_string function reference page: "mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which escapes the following characters: \x00, \n, \r, \, ', " and \x1a."

With that in mind, then the function given in the second link you posted should do exactly what you need:

function mres($value)
{
    $search = array("\\",  "\x00", "\n",  "\r",  "'",  '"', "\x1a");
    $replace = array("\\\\","\\0","\\n", "\\r", "\'", '\"', "\\Z");

    return str_replace($search, $replace, $value);
}

ASP.NET set hiddenfield a value in Javascript

My understanding is if you set controls.Visible = false during initial page load, it doesn't get rendered in the client response. My suggestion to solve your problem is

Don't use placeholder, judging from the scenario, you don't really need a placeholder, unless you need to dynamically add controls on the server side. Use div, without runat=server. You can always controls the visiblity of that div using css. If you need to add controls dynamically later, use placeholder, but don't set visible = false. Placeholder won't have any display anyway, Set the visibility of that placeholder using css. Here's how to do it programmactically :

placeholderId.Attributes["style"] = "display:none";

Anyway, as other have stated, your problems occurs because once you set control.visible = false, it doesn't get rendered in the client response.

Tokenizing strings in C

You can simplify the code by introducing an extra variable.

#include <string.h>
#include <stdio.h>

int main()
{
    char str[100], *s = str, *t = NULL;

    strcpy(str, "a space delimited string");
    while ((t = strtok(s, " ")) != NULL) {
        s = NULL;
        printf(":%s:\n", t);
    }
    return 0;
}

maven compilation failure

It also matters the order of the dependencies. I've had the same issue. And basically I had to put first the scope test and then scope compile dependencies in the pom.xml. If I put first the scope compile and then the scope test it will fail.

Why does Math.Round(2.5) return 2 instead of 3?

You should check MSDN for Math.Round:

The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding to nearest, or banker's rounding.

You can specify the behavior of Math.Round using an overload:

Math.Round(2.5, 0, MidpointRounding.AwayFromZero); // gives 3

Math.Round(2.5, 0, MidpointRounding.ToEven); // gives 2

What is the difference between DAO and Repository patterns?

OK, think I can explain better what I've put in comments :). So, basically, you can see both those as the same, though DAO is a more flexible pattern than Repository. If you want to use both, you would use the Repository in your DAO-s. I'll explain each of them below:

REPOSITORY:

It's a repository of a specific type of objects - it allows you to search for a specific type of objects as well as store them. Usually it will ONLY handle one type of objects. E.g. AppleRepository would allow you to do AppleRepository.findAll(criteria) or AppleRepository.save(juicyApple). Note that the Repository is using Domain Model terms (not DB terms - nothing related to how data is persisted anywhere).

A repository will most likely store all data in the same table, whereas the pattern doesn't require that. The fact that it only handles one type of data though, makes it logically connected to one main table (if used for DB persistence).

DAO - data access object (in other words - object used to access data)

A DAO is a class that locates data for you (it is mostly a finder, but it's commonly used to also store the data). The pattern doesn't restrict you to store data of the same type, thus you can easily have a DAO that locates/stores related objects.

E.g. you can easily have UserDao that exposes methods like

Collection<Permission> findPermissionsForUser(String userId)
User findUser(String userId)
Collection<User> findUsersForPermission(Permission permission)

All those are related to User (and security) and can be specified under then same DAO. This is not the case for Repository.

Finally

Note that both patterns really mean the same (they store data and they abstract the access to it and they are both expressed closer to the domain model and hardly contain any DB reference), but the way they are used can be slightly different, DAO being a bit more flexible/generic, while Repository is a bit more specific and restrictive to a type only.

What is the reason for a red exclamation mark next to my project in Eclipse?

I too faced this strange situation. What I got to know is that, earlier I ran my spring projects with Spring version 1.5.4 and later for one project I chose version 2.0.1. That's when I got this error. When I visited POM and changed Spring version to 1.5.4 manually, the error was gone. What I guess is that, maven downloads the required JARs according to the Spring version specified. If you change the version, maven won't download JARs if those JARs are already downloaded for previous Spring version and found in .m2 source folder found as C: -> Users -> "Logged-In-User-Name" -> .m2 path.

What I did again was to keep the Spring version as it is (as 2.0.1), I opened the Problems view as said earlier and I deleted the JARs which were said as not found in the Problems view by visiting .m2 folder (the Paths were mentioned in the Problems view for were the JARs are). I then updated the maven and all problems were gone.

That's how I conclude that the problem was with JARs which were downloaded for the previous Spring versions in .m2 folder.

Git Bash doesn't see my PATH

I meet this problem when I try to use mingw to compile the xgboost lib in Win10. Finally I found the solution.

Create a file named as .bashrc in your home directory (usually the C:\Users\username). Then add the path to it. Remember to use quotes if your path contains blank, and remember to use /c/ instead of C:/

For example:

PATH=$PATH:"/c/Program Files/mingw-w64/x86_64-7.2.0-posix-seh-rt_v5-rev1/mingw64/bin"

How to print / echo environment variables?

This works too, with the semi-colon.

NAME=sam; echo $NAME

Implement Stack using Two Queues

import java.util.LinkedList;
import java.util.Queue;


public class StackQueue {

    static Queue<Integer> Q1 = new LinkedList<Integer>();
    static Queue<Integer> Q2 = new LinkedList<Integer>();
    public static void main(String args[]) {



        push(24);
        push(34);
        push(4);
        push(10);
        push(1);
        push(43);
        push(21);
        System.out.println("Popped element is  "+pop());
        System.out.println("Popped element is  "+pop());
        System.out.println("Popped element is  "+pop());


    }

    public static void push(int data) {

        Q1.add(data);

    }

    public static int pop() {

        if(Q1.isEmpty()) {
        System.out.println("Cannot pop elements ,  Stack is Empty !!"); 
        return -1;
        }
        else
        {
        while(Q1.size() > 1) {
            Q2.add(Q1.remove());
        }
        int element = Q1.remove();
        Queue<Integer> temp = new LinkedList<Integer>();
        temp = Q1;
        Q1 = Q2;
        Q2 = temp;
        return element;
        }
    }
}

In SQL, is UPDATE always faster than DELETE+INSERT?

Just tried updating 43 fields on a table with 44 fields, the remaining field was the primary clustered key.

The update took 8 seconds.

A Delete + Insert is faster than the minimum time interval that the "Client Statistics" reports via SQL Management Studio.

Peter

MS SQL 2008

Get Path from another app (WhatsApp)

You can try this it will help for you.You can't get path from WhatsApp directly.If you need an file path first copy file and send new file path. Using the code below

 public static String getFilePathFromURI(Context context, Uri contentUri) {
    String fileName = getFileName(contentUri);
    if (!TextUtils.isEmpty(fileName)) {
        File copyFile = new File(TEMP_DIR_PATH  + fileName+".jpg");
        copy(context, contentUri, copyFile);
        return copyFile.getAbsolutePath();
    }
    return null;
}

public static String getFileName(Uri uri) {
    if (uri == null) return null;
    String fileName = null;
    String path = uri.getPath();
    int cut = path.lastIndexOf('/');
    if (cut != -1) {
        fileName = path.substring(cut + 1);
    }
    return fileName;
}

public static void copy(Context context, Uri srcUri, File dstFile) {
    try {
        InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
        if (inputStream == null) return;
        OutputStream outputStream = new FileOutputStream(dstFile);
        IOUtils.copy(inputStream, outputStream);
        inputStream.close();
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Then IOUtils class is like below

public class IOUtils {



private static final int BUFFER_SIZE = 1024 * 2;

private IOUtils() {
    // Utility class.
}

public static int copy(InputStream input, OutputStream output) throws Exception, IOException {
    byte[] buffer = new byte[BUFFER_SIZE];

    BufferedInputStream in = new BufferedInputStream(input, BUFFER_SIZE);
    BufferedOutputStream out = new BufferedOutputStream(output, BUFFER_SIZE);
    int count = 0, n = 0;
    try {
        while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
            out.write(buffer, 0, n);
            count += n;
        }
        out.flush();
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            Log.e(e.getMessage(), e.toString());
        }
        try {
            in.close();
        } catch (IOException e) {
            Log.e(e.getMessage(), e.toString());
        }
    }
    return count;
}


}

Why is printing "B" dramatically slower than printing "#"?

I performed tests on Eclipse vs Netbeans 8.0.2, both with Java version 1.8; I used System.nanoTime() for measurements.

Eclipse:

I got the same time on both cases - around 1.564 seconds.

Netbeans:

  • Using "#": 1.536 seconds
  • Using "B": 44.164 seconds

So, it looks like Netbeans has bad performance on print to console.

After more research I realized that the problem is line-wrapping of the max buffer of Netbeans (it's not restricted to System.out.println command), demonstrated by this code:

for (int i = 0; i < 1000; i++) {
    long t1 = System.nanoTime();
    System.out.print("BBB......BBB"); \\<-contain 1000 "B"
    long t2 = System.nanoTime();
    System.out.println(t2-t1);
    System.out.println("");
}

The time results are less then 1 millisecond every iteration except every fifth iteration, when the time result is around 225 millisecond. Something like (in nanoseconds):

BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
.
.
.

And so on..

Summary:

  1. Eclipse works perfectly with "B"
  2. Netbeans has a line-wrapping problem that can be solved (because the problem does not occur in eclipse)(without adding space after B ("B ")).

Send string to stdin

You can also use read like this

echo "enter your name"
read name
echo $name

How to close the current fragment by using Button like the back button?

From Fragment A, to go to B, replace A with B and use addToBackstack() before commit().

Now From Fragment B, to go to C, first use popBackStackImmediate(), this will bring back A. Now replace A with C, just like the first transaction.

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

The object 'DF__*' is dependent on column '*' - Changing int to double

As constraint has unpredictable name, you can write special script(DropConstraint) to remove it without knowing it's name (was tested at EF 6.1.3):

public override void Up()
{    
    DropConstraint();
    AlterColumn("dbo.MyTable", "Rating", c => c.Double(nullable: false));
}

private void DropConstraint()
{
    Sql(@"DECLARE @var0 nvarchar(128)
          SELECT @var0 = name
          FROM sys.default_constraints
          WHERE parent_object_id = object_id(N'dbo.MyTable')
          AND col_name(parent_object_id, parent_column_id) = 'Rating';
          IF @var0 IS NOT NULL
              EXECUTE('ALTER TABLE [dbo].[MyTable] DROP CONSTRAINT [' + @var0 + ']')");
}

public override void Down()
{            
    AlterColumn("dbo.MyTable", "Rating", c => c.Int(nullable: false));    
}

How to use sed to remove all double quotes within a file

For replacing in place you can also do:

sed -i '' 's/\"//g' file.txt

or in Linux

sed -i 's/\"//g' file.txt

How can I run dos2unix on an entire directory?

If it's a large directory you may want to consider running with multiple processors:

find . -type f -print0 | xargs -0 -n 1 -P 4 dos2unix 

This will pass 1 file at a time, and use 4 processors.

How to add a where clause in a MySQL Insert statement?

UPDATE users SET username='&username', password='&password' where id='&id'

This query will ask you to enter the username,password and id dynamically

Xcode 'CodeSign error: code signing is required'

Maybe your mac's date and time are incorrect. Just correct them.

Make error: missing separator

This is a syntax error in your Makefile. It's quite hard to be more specific than that, without seeing the file itself, or relevant portion(s) thereof.

jQuery AutoComplete Trigger Change Event

I was trying to do the same, but without keeping a variable of autocomplete. I walk throught this calling change handler programatically on the select event, you only need to worry about the actual value of input.

$("#CompanyList").autocomplete({ 
    source: context.companies, 
    change: handleCompanyChanged,
    select: function(event,ui){
        $("#CompanyList").trigger('blur');
        $("#CompanyList").val(ui.item.value);
        handleCompanyChanged();
    }
});

How to generate javadoc comments in Android Studio

You can install JavaDoc plugin from Settings->Plugin->Browse repositories.

get plugin documentation from the below link

JavaDoc plugin document

enter image description here

How to prevent scrollbar from repositioning web page?

Simply setting the width of your container element like this will do the trick

width: 100vw;

This will make that element ignore the scrollbar and it works with background color or images.

Converts scss to css

If you click on the title CSS (SCSS) in CodePen (don't change the pre-processor with the gear) it will switch to the compiled CSS view.

Codepen Screenshot of Compiled Preview

Determining the size of an Android view at runtime

Use the ViewTreeObserver on the View to wait for the first layout. Only after the first layout will getWidth()/getHeight()/getMeasuredWidth()/getMeasuredHeight() work.

ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
  viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
      view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
      viewWidth = view.getWidth();
      viewHeight = view.getHeight();
    }
  });
}

How to solve javax.net.ssl.SSLHandshakeException Error?

Whenever we are trying to connect to URL,

if server at the other site is running on https protocol and is mandating that we should communicate via information provided in certificate then we have following option:

1) ask for the certificate(download the certificate), import this certificate in trustore. Default trustore java uses can be found in \Java\jdk1.6.0_29\jre\lib\security\cacerts, then if we retry to connect to the URL connection would be accepted.

2) In normal business cases, we might be connecting to internal URLS in organizations and we know that they are correct. In such cases, you trust that it is the correct URL, In such cases above, code can be used which will not mandate to store the certificate to connect to particular URL.

for the point no 2 we have to follow below steps :

1) write below method which sets HostnameVerifier for HttpsURLConnection which returns true for all cases meaning we are trusting the trustStore.

  // trusting all certificate 
 public void doTrustToCertificates() throws Exception {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
                        return;
                    }

                    public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
                        return;
                    }
                }
        };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) {
                    System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
                }
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }

2) write below method, which calls doTrustToCertificates before trying to connect to URL

    // connecting to URL
    public void connectToUrl(){
     doTrustToCertificates();//  
     URL url = new URL("https://www.example.com");
     HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 
     System.out.println("ResponseCode ="+conn.getResponseCode());
   }

This call will return response code = 200 means connection is successful.

For more detail and sample example you can refer to URL.

Is there a java setting for disabling certificate validation?

In Axis webservice and if you have to disable the certificate checking then use below code:

AxisProperties.setProperty("axis.socketSecureFactory","org.apache.axis.components.net.SunFakeTrustSocketFactory");

How to check Elasticsearch cluster health?

You can check elasticsearch cluster health by using (CURL) and Cluster API provieded by elasticsearch:

$ curl -XGET 'localhost:9200/_cluster/health?pretty'

This will give you the status and other related data you need.

{
 "cluster_name" : "xxxxxxxx",
 "status" : "green",
 "timed_out" : false,
 "number_of_nodes" : 2,
 "number_of_data_nodes" : 2,
 "active_primary_shards" : 15,
 "active_shards" : 12,
 "relocating_shards" : 0,
 "initializing_shards" : 0,
 "unassigned_shards" : 0,
 "delayed_unassigned_shards" : 0,
 "number_of_pending_tasks" : 0,
 "number_of_in_flight_fetch" : 0
}

Angular JS - angular.forEach - How to get key of the object?

var obj = {name: 'Krishna', gender: 'male'};
angular.forEach(obj, function(value, key) {
    console.log(key + ': ' + value);
});

yields the attributes of obj with their respective values:

name: Krishna
gender: male

Missing `server' JVM (Java\jre7\bin\server\jvm.dll.)

To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm­­.dll, please install or use the JRE or JDK that contains these missing components.

Follow these steps:

Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)

After that, go to C:/Program files/java/jre7/bin

Here, create an folder called Server

Now go into the C:/Program files/java/jre7/bin/client folder

Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server folder

Which Architecture patterns are used on Android?

I tried using both the model–view–controller (MVC) and model–view–presenter architectural patterns for doing android development. My findings are model–view–controller works fine, but there are a couple of "issues". It all comes down to how you perceive the Android Activity class. Is it a controller, or is it a view?

The actual Activity class doesn't extend Android's View class, but it does, however, handle displaying a window to the user and also handle the events of that window (onCreate, onPause, etc.).

This means, that when you are using an MVC pattern, your controller will actually be a pseudo view–controller. Since it is handling displaying a window to the user, with the additional view components you have added to it with setContentView, and also handling events for at least the various activity life cycle events.

In MVC, the controller is supposed to be the main entry point. Which is a bit debatable if this is the case when applying it to Android development, since the activity is the natural entry point of most applications.

Because of this, I personally find that the model–view–presenter pattern is a perfect fit for Android development. Since the view's role in this pattern is:

  • Serving as a entry point
  • Rendering components
  • Routing user events to the presenter

This allows you to implement your model like so:

View - this contains your UI components, and handles events for them.

Presenter - this will handle communication between your model and your view, look at it as a gateway to your model. Meaning, if you have a complex domain model representing, God knows what, and your view only needs a very small subset of this model, the presenters job is to query the model and then update the view. For example, if you have a model containing a paragraph of text, a headline and a word-count. But in a given view, you only need to display the headline in the view. Then the presenter will read the data needed from the model, and update the view accordingly.

Model - this should basically be your full domain model. Hopefully it will help making your domain model more "tight" as well, since you won't need special methods to deal with cases as mentioned above.

By decoupling the model from the view all together (through use of the presenter), it also becomes much more intuitive to test your model. You can have unit tests for your domain model, and unit tests for your presenters.

Try it out. I personally find it a great fit for Android development.

Counting repeated characters in a string in Python

Grand Performance Comparison

Scroll to the end for a TL;DR graph

Since I had "nothing better to do" (understand: I had just a lot of work), I decided to do a little performance contest. I assembled the most sensible or interesting answers and did some simple timeit in CPython 3.5.1 on them. I tested them with only one string, which is a typical input in my case:

>>> s = 'ZDXMZKMXFDKXZFKZ'
>>> len(s)
16

Be aware that results might vary for different inputs, be it different length of the string or different number of distinct characters, or different average number of occurrences per character.


Don't reinvent the wheel

Python has made it simple for us. The collections.Counter class does exactly what we want and a lot more. Its usage is by far the simplest of all the methods mentioned here.

taken from @oefe, nice find

>>> timeit('Counter(s)', globals=locals())
8.208566107001388

Counter goes the extra mile, which is why it takes so long.

¿Dictionary, comprende?

Let's try using a simple dict instead. First, let's do it declaratively, using dict comprehension.

I came up with this myself...

>>> timeit('{c: s.count(c) for c in s}', globals=locals())
4.551155784000002

This will go through s from beginning to end, and for each character it will count the number of its occurrences in s. Since s contains duplicate characters, the above method searches s several times for the same character. The result is naturally always the same. So let's count the number of occurrences just once for each character.

I came up with this myself, and so did @IrshadBhat

>>> timeit('{c: s.count(c) for c in set(s)}', globals=locals())
3.1484066140001232

Better. But we still have to search through the string to count the occurrences. One search for each distinct character. That means we're going to read the string more than once. We can do better than that! But for that, we have to get off our declarativist high horse and descend into an imperative mindset.

Exceptional code

AKA Gotta catch 'em all!

inspired by @anthony

>>> timeit('''
... d = {}
... for c in s:
...   try:
...     d[c] += 1
...   except KeyError:
...     d[c] = 1
... ''', globals=locals())
3.7060273620008957

Well, it was worth a try. If you dig into the Python source (I can't say with certainty because I have never really done that), you will probably find that when you do except ExceptionType, Python has to check whether the exception raised is actually of ExceptionType or some other type. Just for the heck of it, let's see how long will it take if we omit that check and catch all exceptions.

made by @anthony

>>> timeit('''
... d = {}
... for c in s:
...   try:
...     d[c] += 1
...   except:
...     d[c] = 1
... ''', globals=locals())
3.3506563019982423

It does save some time, so one might be tempted to use this as some sort of optimization.
Don't do that! Or actually do. Do it now:

INTERLUDE 1

import time
while True:
  try:
    time.sleep(1)
  except:
    print("You're trapped in your own trap!")

You see? It catches KeyboardInterrupt, besides other things. In fact, it catches all the exceptions there are. Including ones you might not have even heard about, like SystemExit.

INTERLUDE 2

import sys
try:
  print("Goodbye. I'm going to die soon.")
  sys.exit()
except:
  print('BACK FROM THE DEAD!!!')

Now back to counting letters and numbers and other characters.

Playing catch-up

Exceptions aren't the way to go. You have to try hard to catch up with them, and when you finally do, they just throw up on you and then raise their eyebrows like it's your fault. Luckily brave fellows have paved our way so we can do away with exceptions, at least in this little exercise.

The dict class has a nice method – get – which allows us to retrieve an item from a dictionary, just like d[k]. Except when the key k is not in the dictionary, it can return a default value. Let's use that method instead of fiddling with exceptions.

credit goes to @Usman

>>> timeit('''
... d = {}
... for c in s:
...   d[c] = d.get(c, 0) + 1
... ''', globals=locals())
3.2133633289995487

Almost as fast as the set-based dict comprehension. On larger inputs, this one would probably be even faster.

Use the right tool for the job

For at least mildly knowledgeable Python programmer, the first thing that comes to mind is probably defaultdict. It does pretty much the same thing as the version above, except instead of a value, you give it a value factory. That might cause some overhead, because the value has to be "constructed" for each missing key individually. Let's see how it performs.

hope @AlexMartelli won't crucify me for from collections import defaultdict

>>> timeit('''
... dd = defaultdict(int)
... for c in s:
...   dd[c] += 1
... ''', globals=locals())
3.3430528169992613

Not that bad. I'd say the increase in execution time is a small tax to pay for the improved readability. However, we also favor performance, and we will not stop here. Let's take it further and prepopulate the dictionary with zeros. Then we won't have to check every time if the item is already there.

hats off to @sqram

>>> timeit('''
... d = dict.fromkeys(s, 0)
... for c in s:
...   d[c] += 1
... ''', globals=locals())
2.6081761489986093

That's good. Over three times as fast as Counter, yet still simple enough. Personally, this is my favorite in case you don't want to add new characters later. And even if you do, you can still do it. It's just less convenient than it would be in other versions:

d.update({ c: 0 for c in set(other_string) - d.keys() })


Practicality beats purity (except when it's not really practical)

Now a bit different kind of counter. @IdanK has come up with something interesting. Instead of using a hash table (a.k.a. dictionary a.k.a. dict), we can avoid the risk of hash collisions and consequent overhead of their resolution. We can also avoid the overhead of hashing the key, and the extra unoccupied table space. We can use a list. The ASCII values of characters will be indices and their counts will be values. As @IdanK has pointed out, this list gives us constant time access to a character's count. All we have to do is convert each character from str to int using the built-in function ord. That will give us an index into the list, which we will then use to increment the count of the character. So what we do is this: we initialize the list with zeros, do the job, and then convert the list into a dict. This dict will only contain those characters which have non-zero counts, in order to make it compliant with other versions.

As a side note, this technique is used in a linear-time sorting algorithm known as count sort or counting sort. It's very efficient, but the range of values being sorted is limited, since each value has to have its own counter. To sort a sequence of 32-bit integers, 4.3 billion counters would be needed.

>>> timeit('''
... counts = [0 for _ in range(256)]
... for c in s:
...   counts[ord(c)] += 1
... d = {chr(i): count for i,count in enumerate(counts) if count != 0}
... ''', globals=locals())
25.438595562001865

Ouch! Not cool! Let's try and see how long it takes when we omit building the dictionary.

>>> timeit('''
... counts = [0 for _ in range(256)]
... for c in s:
...   counts[ord(c)] += 1
... ''', globals=locals())
10.564866792999965

Still bad. But wait, what's [0 for _ in range(256)]? Can't we write it more simply? How about [0] * 256? That's cleaner. But will it perform better?

>>> timeit('''
... counts = [0] * 256
... for c in s:
...   counts[ord(c)] += 1
... ''', globals=locals())
3.290163638001104

Considerably. Now let's put the dictionary back in.

>>> timeit('''
... counts = [0] * 256
... for c in s:
...   counts[ord(c)] += 1
... d = {chr(i): count for i,count in enumerate(counts) if count != 0}
... ''', globals=locals())
18.000623562998953

Almost six times slower. Why does it take so long? Because when we enumerate(counts), we have to check every one of the 256 counts and see if it's zero. But we already know which counts are zero and which are not.

>>> timeit('''
... counts = [0] * 256
... for c in s:
...   counts[ord(c)] += 1
... d = {c: counts[ord(c)] for c in set(s)}
... ''', globals=locals())
5.826531438000529

It probably won't get much better than that, at least not for such a small input. Plus it's only usable for 8-bit EASCII characters. ? ?????!

And the winner is...

>>> timeit('''
... d = {}
... for c in s:
...   if c in d:
...     d[c] += 1
...   else:
...     d[c] = 1
... ''', globals=locals())
1.8509794599995075

Yep. Even if you have to check every time whether c is in d, for this input it's the fastest way. No pre-population of d will make it faster (again, for this input). It's a lot more verbose than Counter or defaultdict, but also more efficient.


That's all folks

This little exercise teaches us a lesson: when optimizing, always measure performance, ideally with your expected inputs. Optimize for the common case. Don't presume something is actually more efficient just because its asymptotic complexity is lower. And last but not least, keep readability in mind. Try to find a compromise between "computer-friendly" and "human-friendly".



UPDATE

I have been informed by @MartijnPieters of the function collections._count_elements available in Python 3.

Help on built-in function _count_elements in module _collections:

_count_elements(...)
    _count_elements(mapping, iterable) -> None

    Count elements in the iterable, updating the mappping

This function is implemented in C, so it should be faster, but this extra performance comes at a price. The price is incompatibility with Python 2 and possibly even future versions, since we're using a private function.

From the documentation:

[...] a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

That said, if you still want to save those 620 nanoseconds per iteration:

>>> timeit('''
... d = {}
... _count_elements(d, s)
... ''', globals=locals())
1.229239897998923



UPDATE 2: Large strings

I thought it might be a good idea to re-run the tests on some larger input, since a 16 character string is such a small input that all the possible solutions were quite comparably fast (1,000 iterations in under 30 milliseconds).

I decided to use the complete works of Shakespeare as a testing corpus, which turned out to be quite a challenge (since it's over 5MiB in size ). I just used the first 100,000 characters of it, and I had to limit the number of iterations from 1,000,000 to 1,000.

import urllib.request
url = 'https://ocw.mit.edu/ans7870/6/6.006/s08/lecturenotes/files/t8.shakespeare.txt'
s = urllib.request.urlopen(url).read(100_000)

collections.Counter was really slow on a small input, but the tables have turned

Counter(s)

=> 7.63926783799991

Naïve T(n2) time dictionary comprehension simply doesn't work

{c: s.count(c) for c in s}

=> 15347.603935000052s (tested on 10 iterations; adjusted for 1000)

Smart T(n) time dictionary comprehension works fine

{c: s.count(c) for c in set(s)}

=> 8.882608592999986

Exceptions are clumsy and slow

d = {}
for c in s:
  try:
    d[c] += 1
  except KeyError:
    d[c] = 1

=> 21.26615508399982

Omitting the exception type check doesn't save time (since the exception is only thrown a few times)

d = {}
for c in s:
  try:
    d[c] += 1
  except:
    d[c] = 1

=> 21.943328911999743

dict.get looks nice but runs slow

d = {}
for c in s:
  d[c] = d.get(c, 0) + 1

=> 28.530086210000007

collections.defaultdict isn't very fast either

dd = defaultdict(int)
for c in s:
  dd[c] += 1

=> 19.43012963199999

dict.fromkeys requires reading the (very long) string twice

d = dict.fromkeys(s, 0)
for c in s:
  d[c] += 1

=> 22.70960557699999

Using list instead of dict is neither nice nor fast

counts = [0 for _ in range(256)]
for c in s:
  counts[ord(c)] += 1

d = {chr(i): count for i,count in enumerate(counts) if count != 0}

=> 26.535474792000002

Leaving out the final conversion to dict doesn't help

counts = [0 for _ in range(256)]
for c in s:
  counts[ord(c)] += 1

=> 26.27811567400005

It doesn't matter how you construct the list, since it's not the bottleneck

counts = [0] * 256
for c in s:
  counts[ord(c)] += 1

=> 25.863524940000048


counts = [0] * 256
for c in s:
  counts[ord(c)] += 1

d = {chr(i): count for i,count in enumerate(counts) if count != 0}

=> 26.416733378000004

If you convert list to dict the "smart" way, it's even slower (since you iterate over the string twice)

counts = [0] * 256
for c in s:
  counts[ord(c)] += 1

d = {c: counts[ord(c)] for c in set(s)}

=> 29.492915620000076

The dict.__contains__ variant may be fast for small strings, but not so much for big ones

d = {}
for c in s:
  if c in d:
    d[c] += 1
  else:
    d[c] = 1

=> 23.773295123000025

collections._count_elements is about as fast as collections.Counter (which uses _count_elements internally)

d = {}
_count_elements(d, s)

=> 7.5814381919999505


Final verdict: Use collections.Counter unless you cannot or don't want to :)



Appendix: NumPy

The numpy package provides a method numpy.unique which accomplishes (almost) precisely what we want.

The way this method works is very different from all the above methods:

  • It first sorts a copy of the input using Quicksort, which is an O(n2) time operation in the worst case, albeit O(n log n) on average and O(n) in the best case.

  • Then it creates a "mask" array containing True at indices where a run of the same values begins, viz. at indices where the value differs from the previous value. Repeated values produce False in the mask. Example: [5,5,5,8,9,9] produces a mask [True, False, False, True, True, False].

  • This mask is then used to extract the unique values from the sorted input - unique_chars in the code below. In our example, they would be [5, 8, 9].

  • Positions of the True values in the mask are taken into an array, and the length of the input is appended at the end of this array. For the above example, this array would be [0, 3, 4, 6].

  • For this array, differences between its elements are calculated, eg. [3, 1, 2]. These are the respective counts of the elements in the sorted array - char_counts in the code below.

  • Finally, we create a dictionary by zipping unique_chars and char_counts: {5: 3, 8: 1, 9: 2}.


import numpy as np

def count_chars(s):
  # The following statement needs to be changed for different input types.
  # Our input `s` is actually of type `bytes`, so we use `np.frombuffer`.
  # For inputs of type `str`, change `np.frombuffer` to `np.fromstring`
  #  or transform the input into a `bytes` instance.
  arr = np.frombuffer(s, dtype=np.uint8)

  unique_chars, char_counts = np.unique(arr, return_counts=True)

  return dict(zip(unique_chars, char_counts))

For the test input (first 100,000 characters of the complete works of Shakespeare), this method performs better than any other tested here. But note that on a different input, this approach might yield worse performance than the other methods. Pre-sortedness of the input and number of repetitions per element are important factors affecting the performance.

count_chars(s)

=> 2.960809530000006


If you are thinking about using this method because it's over twice as fast as collections.Counter, consider this:

  • collections.Counter has linear time complexity. numpy.unique is linear at best, quadratic at worst.

  • The speedup is not really that significant - you save ~3.5 milliseconds per iteration on an input of length 100,000.

  • Using numpy.unique obviously requires numpy.

That considered, it seems reasonable to use Counter unless you need to be really fast. And in that case, you better know what you're doing or else you'll end up being slower with numpy than without it.



Appendix 2: A somewhat useful plot

I ran the 13 different methods above on prefixes of the complete works of Shakespeare and made an interactive plot. Note that in the plot, both prefixes and durations are displayed in logarithmic scale (the used prefixes are of exponentially increasing length). Click on the items in the legend to show/hide them in the plot.

Interactive plot (click!)

Click to open!

Maven Could not resolve dependencies, artifacts could not be resolved

The artifactId for all the dependencies that failed to download are incorrect - for some reason they are prefixed with com.springsource. Cut/paste issue?

You can try replacing them as follows.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.transaction</groupId>
    <artifactId>jta</artifactId>
    <version>1.1.0</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.5.6</version>
</dependency>

You may also want to add the maven central repository for these artifacts in case they are not available in the specified repositories.

<repository>
    <id>maven2</id>
    <url>http://repo1.maven.org/maven2</url>
</repository>

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

In typescript, if you want to use the node.js package cors

/**
* app.ts
* If you use the cors library
*/

import * as express from "express";
[...]
import * as cors from 'cors';

class App {
   public express: express.Application;

   constructor() {
       this.express = express();
       [..]
       this.handleCORSErrors();
   }

   private handleCORSErrors(): any {
       const corsOptions: cors.CorsOptions = {
           origin: 'http://example.com',
           optionsSuccessStatus: 200
       };
       this.express.use(cors(corsOptions));
   }
}

export default new App().express;

If you don't want to use third part libraries for cors error handling, you need to change the handleCORSErrors() method.

/**
* app.ts
* If you do not use the cors library
*/

import * as express from "express";
[...]

class App {
   public express: express.Application;

   constructor() {
       this.express = express();
       [..]
       this.handleCORSErrors();
   }

   private handleCORSErrors(): any {
       this.express.use((req, res, next) => {
           res.header("Access-Control-Allow-Origin", "*");
           res.header(
               "Access-Control-ALlow-Headers",
               "Origin, X-Requested-With, Content-Type, Accept, Authorization"
           );
           if (req.method === "OPTIONS") {
               res.header(
                   "Access-Control-Allow-Methods",
                   "PUT, POST, PATCH, GET, DELETE"
               );
               return res.status(200).json({});
           } 
           next(); // send the request to the next middleware
       });
    }
}

export default new App().express;

For using the app.ts file

/**
* server.ts
*/
import * as http from "http";
import app from "./app";

const server: http.Server = http.createServer(app);

const PORT: any = process.env.PORT || 3000;
server.listen(PORT);

How to override !important?

This can help too

td[style] {height: 50px !important;}

This will override any inline style

What is Func, how and when is it used

Func<T1,R> and the other predefined generic Func delegates (Func<T1,T2,R>, Func<T1,T2,T3,R> and others) are generic delegates that return the type of the last generic parameter.

If you have a function that needs to return different types, depending on the parameters, you can use a Func delegate, specifying the return type.

How do I remove a single breakpoint with GDB?

Try these (reference):

clear linenum
clear filename:linenum

How to master AngularJS?

The video AngularJS Fundamentals In 60-ish Minutes provides a very good introduction and overview.

I would also highly recomend the AngularJS book from O'Reilly, mentioned by @Atropo.

CFLAGS, CCFLAGS, CXXFLAGS - what exactly do these variables control?

Minimal example

And just to make what Mizux said as a minimal example:

main_c.c

#include <stdio.h>

int main(void) {
    puts("hello");
}

main_cpp.cpp

#include <iostream>

int main(void) {
    std::cout << "hello" << std::endl;
}

Then, without any Makefile:

make CFLAGS='-g -O3' \
     CXXFLAGS='-ggdb3 -O0' \
     CPPFLAGS='-DX=1 -DY=2' \
     CCFLAGS='--asdf' \
     main_c \
     main_cpp

runs:

cc -g -O3 -DX=1 -DY=2   main_c.c   -o main_c
g++ -ggdb3 -O0 -DX=1 -DY=2   main_cpp.cpp   -o main_cpp

So we understand that:

  • make had implicit rules to make main_c and main_cpp from main_c.c and main_cpp.cpp
  • CFLAGS and CPPFLAGS were used as part of the implicit rule for .c compilation
  • CXXFLAGS and CPPFLAGS were used as part of the implicit rule for .cpp compilation
  • CCFLAGS is not used

Those variables are only used in make's implicit rules automatically: if compilation had used our own explicit rules, then we would have to explicitly use those variables as in:

main_c: main_c.c
    $(CC) $(CFLAGS) $(CPPFLAGS) -o $@ $<

main_cpp: main_c.c
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -o $@ $<

to achieve a similar affect to the implicit rules.

We could also name those variables however we want: but since Make already treats them magically in the implicit rules, those make good name choices.

Tested in Ubuntu 16.04, GNU Make 4.1.

How to stop IIS asking authentication for default website on localhost

What worked for me is ,,,

Click Start>control panel>Administrative Tools>Internet Information Services

Expand the left tree, right-click your WebSite>Properties

Click on Directory Security, then in "Anonymous access and authentication control" click on Edit

Enable Anonymous access>browse> enter the credentials of the admin (like Administrator) (check names),> Click OK

Apply the settings and it should work fine.

Fixed header, footer with scrollable content

Now we've got CSS grid. Welcome to 2019.

_x000D_
_x000D_
/* Required */_x000D_
body {_x000D_
   margin: 0;_x000D_
   height: 100%;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
   height: 100vh;_x000D_
   display: grid;_x000D_
   grid-template-rows: 30px 1fr 30px;_x000D_
}_x000D_
_x000D_
#content {_x000D_
   overflow-y: scroll;_x000D_
}_x000D_
_x000D_
/* Optional */_x000D_
#wrapper > * {_x000D_
   padding: 5px;_x000D_
}_x000D_
_x000D_
#header {_x000D_
   background-color: #ff0000ff;_x000D_
}_x000D_
_x000D_
#content {_x000D_
   background-color: #00ff00ff;_x000D_
}_x000D_
_x000D_
#footer {_x000D_
   background-color: #0000ffff;_x000D_
}
_x000D_
<body>_x000D_
   <div id="wrapper">_x000D_
      <div id="header">Header Content</div>_x000D_
      <div id="content">_x000D_
         Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
      </div>_x000D_
      <div id="footer">Footer Content</div>_x000D_
   </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Why can't Python parse this JSON data?

"Ultra JSON" or simply "ujson" can handle having [] in your JSON file input. If you're reading a JSON input file into your program as a list of JSON elements; such as, [{[{}]}, {}, [], etc...] ujson can handle any arbitrary order of lists of dictionaries, dictionaries of lists.

You can find ujson in the Python package index and the API is almost identical to Python's built-in json library.

ujson is also much faster if you're loading larger JSON files. You can see the performance details in comparison to other Python JSON libraries in the same link provided.

Update cordova plugins in one command

Here's a bash script I use, works on OSX 10.11.3.

#!/bin/bash

PLUGINS=$(cordova plugin list | awk '{print $1}')

for PLUGIN in $PLUGINS; do
    cordova plugin rm $PLUGIN --save && cordova plugin add $PLUGIN --save
done

This may help if there are conflicts, per shan's comment. The difference is the addition of the --force flag when removing.

#!/bin/bash

PLUGINS=$(cordova plugin list | awk '{print $1}')

for PLUGIN in $PLUGINS; do
    cordova plugin rm $PLUGIN --force --save && cordova plugin add $PLUGIN --save
done

jquery datatables default sort

You can use the fnSort function, see the details here:

http://datatables.net/api#fnSort

Create JSON object dynamically via JavaScript (Without concate strings)

This topic, especially the answer of Xotic750 was very helpful to me. I wanted to generate a json variable to pass it to a php script using ajax. My values were stored into two arrays, and i wanted them in json format. This is a generic example:

valArray1 = [121, 324, 42, 31];
valArray2 = [232, 131, 443];
myJson = {objArray1: {}, objArray2: {}};
for (var k = 1; k < valArray1.length; k++) {
    var objName = 'obj' + k;
    var objValue = valArray1[k];
    myJson.objArray1[objName] = objValue;
}
for (var k = 1; k < valArray2.length; k++) {
    var objName = 'obj' + k;
    var objValue = valArray2[k];
    myJson.objArray2[objName] = objValue;
}
console.log(JSON.stringify(myJson));

The result in the console Log should be something like this:

{
   "objArray1": {
        "obj1": 121,
        "obj2": 324,
        "obj3": 42,
        "obj4": 31
   },
   "objArray2": {
        "obj1": 232,
        "obj2": 131,
        "obj3": 443
  }
}

Manipulate a url string by adding GET parameters

Basic method

$query = parse_url($url, PHP_URL_QUERY);

// Returns a string if the URL has parameters or NULL if not
if ($query) {
    $url .= '&category=1';
} else {
    $url .= '?category=1';
}

More advanced

$url = 'http://example.com/search?keyword=test&category=1&tags[]=fun&tags[]=great';

$url_parts = parse_url($url);
// If URL doesn't have a query string.
if (isset($url_parts['query'])) { // Avoid 'Undefined index: query'
    parse_str($url_parts['query'], $params);
} else {
    $params = array();
}

$params['category'] = 2;     // Overwrite if exists
$params['tags'][] = 'cool';  // Allows multiple values

// Note that this will url_encode all values
$url_parts['query'] = http_build_query($params);

// If you have pecl_http
echo http_build_url($url_parts);

// If not
echo $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'] . '?' . $url_parts['query'];

You should put this in a function at least, if not a class.

Installing Bootstrap 3 on Rails App

I use https://github.com/yabawock/bootstrap-sass-rails

Which is pretty much straight forward install, fast gem updates and followups and quick fixes in case is needed.

How to refresh a Page using react-route Link

You can use this

<a onClick={() => {window.location.href="/something"}}>Something</a>

Sublime Text 3 how to change the font size of the file sidebar?

If you are using the default theme. Just goto Preferences-> Default File Preferences A new tab pops up. At about line number you could see the font [font-name] [font-size]

Edit the font-size according to your wish and save.

How to convert date to string and to date again?

For converting date to string check this thread

Convert java.util.Date to String

And for converting string to date try this,

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class StringToDate
{
    public static void main(String[] args) throws ParseException
    {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
        String strDate = "14/03/2003 08:05:10";     
        System.out.println("Date - " + sdf.parse(strDate));
    }
}

pip3: command not found but python3-pip is already installed

Probably pip3 is installed in /usr/local/bin/ which is not in the PATH of the sudo (root) user. Use this instead

sudo /usr/local/bin/pip3 install virtualenv

How to convert MySQL time to UNIX timestamp using PHP?

$time_PHP = strtotime( $datetime_SQL );

When is "java.io.IOException:Connection reset by peer" thrown?

java.io.IOException: Connection reset by peer

In my case, the problem was with PUT requests (GET and POST were passing successfully).

Communication went through VPN tunnel and ssh connection. And there was a firewall with default restrictions on PUT requests... PUT requests haven't been passing throughout, to the server...

Problem was solved after exception was added to the firewall for my IP address.

How to calculate the number of occurrence of a given character in each row of a column of strings?

s <- "aababacababaaathhhhhslsls jsjsjjsaa ghhaalll"
p <- "a"
s2 <- gsub(p,"",s)
numOcc <- nchar(s) - nchar(s2)

May not be the efficient one but solve my purpose.

How do I make flex box work in safari?

It works when you set the display value of your menu items from display: inline-block; to display: block;

See your updated code here:

#menu {
    clear: both;
    height: auto;
    font-family: Arial, Tahoma, Verdana;
    font-size: 1em;
    /*padding:10px;*/
    margin: 5px;
    display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */
    display: -moz-box;    /* OLD - Firefox 19- (buggy but mostly works) */
    display: -ms-flexbox;  /* TWEENER - IE 10 */
    display: -webkit-flex; /* NEW - Chrome */
    display: flex;         /* NEW, Spec - Opera 12.1, Firefox 20+ */
    justify-content: center;
    -webkit-box-align: center;
    -webkit-flex-align: center;
    -ms-flex-align: center;
    -webkit-align-items: center;
    align-items: center;fffff
    font-style: normal;
    font-weight: 400px;
}

#menu a:link {
    display: block; //here you need to change the display property
    width: 100px;
    height: 50px;
    padding: 5px;
    background-color: yellow;
    /*border: 1px solid #cccccc;*/
    margin: 5px;
    display: flex;
    flex-grow: 1;
    align-items: center;
    text-align: center;
    justify-content: center;
    font-weight: bold;
    color: #1689D6;
    font-size: 85%;
}
#menu a:visited {
    //no display property here                                                                       
    width: 100px;
    height: 50px;
    padding: 5px;
    background-color: yellow;
    /*border: 1px solid #cccccc;*/
    margin: 5px;
    display: flex;
    flex-grow: 1;
    align-items: center;
    text-align: center;
    justify-content: center;
    font-weight: bold;
    color: #1689D6;
    font-size: 85%;
}
#menu a:hover {
    //no display property here                                                                               
    color: #fff;
    width: 100px;
    height: 50px;
    padding: 5px;
    background-color: red;
    /*border: 1px solid #cccccc;*/
    margin: 5px;
    display: flex;
    flex-grow: 1;
    align-items: center;
    text-align: center;
    justify-content: center;
    font-weight: bold;
    font-size: 85%;
}
#menu a:active {
    //no display property here                                                                               
    color: #fff;
    width: 100px;
    height: 50px;
    padding-top: 5px;
    padding-right: 5px;
    padding-left: 5px;
    padding-bottom: 5px;
    background-color: red;
    /*border: 1px solid #cccccc;*/
    margin: 5px;
    display: flex;
    flex-grow: 1;
    align-items: center;
    text-align: center;
    justify-content: center;
    font-style: normal;
    font-weight: bold;
    font-size: 85%;
}

How to define the basic HTTP authentication using cURL correctly?

as header

AUTH=$(echo -ne "$BASIC_AUTH_USER:$BASIC_AUTH_PASSWORD" | base64 --wrap 0)

curl \
  --header "Content-Type: application/json" \
  --header "Authorization: Basic $AUTH" \
  --request POST \
  --data  '{"key1":"value1", "key2":"value2"}' \
  https://example.com/

Use Font Awesome Icons in CSS

To use font awesome using css follow below steps -

step 1 - Add Fonts of FontAwesome in CSS

/*Font Awesome Fonts*/
@font-face {
    font-family: 'FontAwesome';
    //in url add your folder path of FontAwsome Fonts
    src: url('font-awesome/fontawesome-webfont.ttf') format('truetype');
}

Step - 2 Use below css to apply font on class element of HTML

.sorting_asc:after {
    content: "\f0de"; /* this is your text. You can also use UTF-8 character codes as I do here */
    font-family: FontAwesome;
    padding-left: 10px !important;
    vertical-align: middle;
}

And finally, use "sorting_asc" class to apply the css on desired HTML tag/element.

varbinary to string on SQL Server

"Converting a varbinary to a varchar" can mean different things.

If the varbinary is the binary representation of a string in SQL Server (for example returned by casting to varbinary directly or from the DecryptByPassPhrase or DECOMPRESS functions) you can just CAST it

declare @b varbinary(max)
set @b = 0x5468697320697320612074657374

select cast(@b as varchar(max)) /*Returns "This is a test"*/

This is the equivalent of using CONVERT with a style parameter of 0.

CONVERT(varchar(max), @b, 0)

Other style parameters are available with CONVERT for different requirements as noted in other answers.

How to check if android checkbox is checked within its onClick method (declared in XML)?

You can try this code:

public void itemClicked(View v) {
 //code to check if this checkbox is checked!
 if(((Checkbox)v).isChecked()){
   // code inside if
 }
}

How to configure the web.config to allow requests of any length

It will also generate error when you pass large string in ajax call parameter.

so for that alway use type post in ajax will resolve your issue 100% and no need to set the length in web.config.

// var UserId= array of 1000 userids

$.ajax({ global: false, url: SitePath + "/User/getAussizzMembersData", "data": { UserIds: UserId}, "type": "POST", "dataType": "JSON" }}

How to center a subview of UIView

In c# or Xamarin.ios, we can use like this

imageView.Center = new CGPoint(tempView.Frame.Size.Width / 2, tempView.Frame.Size.Height / 2);

How to filter by IP address in Wireshark?

Actually for some reason wireshark uses two different kind of filter syntax one on display filter and other on capture filter. Display filter is only useful to find certain traffic just for display purpose only. its like you are interested in all trafic but for now you just want to see specific.

but if you are interested only in certian traffic and does not care about other at all then you use the capture filter.

The Syntax for display filter is (as mentioned earlier)

ip.addr = x.x.x.x or ip.src = x.x.x.x or ip.dst = x.x.x.x

but above syntax won't work in capture filters, following are the filters

host x.x.x.x

see more example on wireshark wiki page

How to set 'X-Frame-Options' on iframe?

you can do it in tomcat instance level config file (web.xml) need to add the 'filter' and filter-mapping' in web.xml config file. this will add the [X-frame-options = DENY] in all the page as it is a global setting.

<filter>
        <filter-name>httpHeaderSecurity</filter-name>
        <filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
        <async-supported>true</async-supported>
        <init-param>
          <param-name>antiClickJackingEnabled</param-name>
          <param-value>true</param-value>
        </init-param>
        <init-param>
          <param-name>antiClickJackingOption</param-name>
          <param-value>DENY</param-value>
        </init-param>
    </filter>

  <filter-mapping> 
    <filter-name>httpHeaderSecurity</filter-name> 
    <url-pattern>/*</url-pattern>
</filter-mapping>

Messagebox with input field

You can reference Microsoft.VisualBasic.dll.

Then using the code below.

Microsoft.VisualBasic.Interaction.InputBox("Question?","Title","Default Text");

Alternatively, by adding a using directive allowing for a shorter syntax in your code (which I'd personally prefer).

using Microsoft.VisualBasic;
...
Interaction.InputBox("Question?","Title","Default Text");

Or you can do what Pranay Rana suggests, that's what I would've done too...

How to listen to route changes in react router v4?

In some cases you might use render attribute instead of component, in this way:

class App extends React.Component {

    constructor (props) {
        super(props);
    }

    onRouteChange (pageId) {
        console.log(pageId);
    }

    render () {
        return  <Switch>
                    <Route path="/" exact render={(props) => { 
                        this.onRouteChange('home');
                        return <HomePage {...props} />;
                    }} />
                    <Route path="/checkout" exact render={(props) => { 
                        this.onRouteChange('checkout');
                        return <CheckoutPage {...props} />;
                    }} />
                </Switch>
    }
}

Notice that if you change state in onRouteChange method, this could cause 'Maximum update depth exceeded' error.

Linux command to check if a shell script is running or not

Give an option to ps to display all the processes, an example is:

ps -A | grep "myshellscript.sh"

Check http://www.cyberciti.biz/faq/show-all-running-processes-in-linux/ for more info

And as Basile Starynkevitch mentioned in the comment pgrep is another solution.

Delete an element from a dictionary

Here's another variation using list comprehension:

original_d = {'a': None, 'b': 'Some'}
d = dict((k,v) for k, v in original_d.iteritems() if v)
# result should be {'b': 'Some'}

The approach is based on an answer from this post: Efficient way to remove keys with empty strings from a dict

Calculating moving average

The slider package can be used for this. It has an interface that has been specifically designed to feel similar to purrr. It accepts any arbitrary function, and can return any type of output. Data frames are even iterated over row wise. The pkgdown site is here.

library(slider)

x <- 1:3

# Mean of the current value + 1 value before it
# returned as a double vector
slide_dbl(x, ~mean(.x, na.rm = TRUE), .before = 1)
#> [1] 1.0 1.5 2.5


df <- data.frame(x = x, y = x)

# Slide row wise over data frames
slide(df, ~.x, .before = 1)
#> [[1]]
#>   x y
#> 1 1 1
#> 
#> [[2]]
#>   x y
#> 1 1 1
#> 2 2 2
#> 
#> [[3]]
#>   x y
#> 1 2 2
#> 2 3 3

The overhead of both slider and data.table's frollapply() should be pretty low (much faster than zoo). frollapply() looks to be a little faster for this simple example here, but note that it only takes numeric input, and the output must be a scalar numeric value. slider functions are completely generic, and you can return any data type.

library(slider)
library(zoo)
library(data.table)

x <- 1:50000 + 0L

bench::mark(
  slider = slide_int(x, function(x) 1L, .before = 5, .complete = TRUE),
  zoo = rollapplyr(x, FUN = function(x) 1L, width = 6, fill = NA),
  datatable = frollapply(x, n = 6, FUN = function(x) 1L),
  iterations = 200
)
#> # A tibble: 3 x 6
#>   expression      min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 slider      19.82ms   26.4ms     38.4    829.8KB     19.0
#> 2 zoo        177.92ms  211.1ms      4.71    17.9MB     24.8
#> 3 datatable    7.78ms   10.9ms     87.9    807.1KB     38.7

How to get the height of a body element

Set

html { height: 100%; }
body { min-height: 100%; }

instead of height: 100%.

The result jQuery returns is correct, because you've set the height of the body to 100%, and that's probably the height of the viewport. These three DIVs were causing an overflow, because there weren't enough space for them in the BODY element. To see what I mean, set a border to the BODY tag and check where the border ends.

How to connect to LocalDB in Visual Studio Server Explorer?

Scenario: Windows 8.1, VS2013 Ultimate, SQL Express Installed and running, SQL Server Browser Disabled. This worked for me:

  1. First I enabled SQL Server Browser under services.
  2. In Visual Studio: Open the Package Manager Console then type: Enable-Migrations; Then Type Enable-Migrations -ContextTypeName YourContextDbName that created the Migrations folder in VS.
  3. Inside the Migrations folder you will find the "Configuration.cs" file, turn on automatic migrations by: AutomaticMigrationsEnabled = true;
  4. Run your application again, the environment creates a DefaultConnection and you will see the new tables from your context. This new connection points to the localdb. The created connection string shows: Data Source=(LocalDb)\v11.0 ... (more parameters and path to the created mdf file)

You can now create a new connection with Server name: (LocalDb)\v11.0 (hit refresh) Connect to a database: Select your new database under the dropdown.

I hope it helps.

How to get N rows starting from row M from sorted table in T-SQL

Probably good for small results, works in all versions of TSQL:

SELECT 
        * 
FROM
     (SELECT TOP (N) * 
      FROM 
            (SELECT TOP (M + N - 1) 
             FROM 
                   Table
             ORDER BY 
                      MyColumn) qasc
      ORDER BY 
               MyColumn DESC) qdesc
 ORDER BY 
         MyColumn

Run a single test method with maven

The test parameter mentioned by tobrien allows you to specify a method using a # before the method name. This should work for JUnit and TestNG. I've never tried it, just read it on the Surefire Plugin page:

Specify this parameter to run individual tests by file name, overriding the includes/excludes parameters. Each pattern you specify here will be used to create an include pattern formatted like **/${test}.java, so you can just type "-Dtest=MyTest" to run a single test called "foo/MyTest.java". This parameter overrides the includes/excludes parameters, and the TestNG suiteXmlFiles parameter. since 2.7.3 You can execute a limited number of method in the test with adding #myMethod or #my*ethod. Si type "-Dtest=MyTest#myMethod" supported for junit 4.x and testNg

Convert one date format into another in PHP

strtotime will work that out. the dates are just not the same and all in us-format.

<?php
$e1 = strtotime("2013-07-22T12:00:03Z");
echo date('y.m.d H:i', $e1);
echo "2013-07-22T12:00:03Z";

$e2 = strtotime("2013-07-23T18:18:15Z");
echo date ('y.m.d H:i', $e2);
echo "2013-07-23T18:18:15Z";

$e1 = strtotime("2013-07-21T23:57:04Z");
echo date ('y.m.d H:i', $e2);
echo "2013-07-21T23:57:04Z";
?>

What is the difference between SessionState and ViewState?

Session is used mainly for storing user specific data [ session specific data ]. In the case of session you can use the value for the whole session until the session expires or the user abandons the session. Viewstate is the type of data that has scope only in the page in which it is used. You canot have viewstate values accesible to other pages unless you transfer those values to the desired page. Also in the case of viewstate all the server side control datas are transferred to the server as key value pair in __Viewstate and transferred back and rendered to the appropriate control in client when postback occurs.

Is it possible to append to innerHTML without destroying descendants' event listeners?

I created my markup to insert as a string since it's less code and easier to read than working with the fancy dom stuff.

Then I made it innerHTML of a temporary element just so I could take the one and only child of that element and attach to the body.

var html = '<div>';
html += 'Hello div!';
html += '</div>';

var tempElement = document.createElement('div');
tempElement.innerHTML = html;
document.getElementsByTagName('body')[0].appendChild(tempElement.firstChild);

How can javascript upload a blob?

Try this

var fd = new FormData();
fd.append('fname', 'test.wav');
fd.append('data', soundBlob);
$.ajax({
    type: 'POST',
    url: '/upload.php',
    data: fd,
    processData: false,
    contentType: false
}).done(function(data) {
       console.log(data);
});

You need to use the FormData API and set the jQuery.ajax's processData and contentType to false.

How to remove lines in a Matplotlib plot

(using the same example as the guy above)

from matplotlib import pyplot
import numpy
a = numpy.arange(int(1e3))
fig = pyplot.Figure()
ax  = fig.add_subplot(1, 1, 1)
lines = ax.plot(a)

for i, line in enumerate(ax.lines):
    ax.lines.pop(i)
    line.remove()

The HTTP request is unauthorized with client authentication scheme 'Ntlm'. The authentication header received from the server was 'Negotiate,NTLM'

If both your client and service is installed on the same machine, and you are facing this problem with the correct (read: tried and tested elsewhere) client and service configurations, then this might be worth checking.

Check host entries in your host file

%windir%/system32/drivers/etc/hosts

Check to see if you are accessing your web service with a hostname, and that same hostname has been associated with an IP address in the hosts file mentioned above. If yes, NTLM/Windows credentials will NOT be passed from the client to the service as any request for that hostname will be routed again at the machine level.

Try either of the following

  • Remove the host entry of that hostname from the hosts file
  • OR
  • If removing host entry is not possible, then try accessing your service with another hostname. You might also try with IP address instead of hostname

Edit: Somehow the above situation is relevant on a load-balanced scenario. However, if removing the host entries is not possible, then disabling loop back check on the machine will help. Refer method 2 in the article https://support.microsoft.com/en-us/kb/896861

Write lines of text to a file in R

What about a simple write.table()?

text = c("Hello", "World")
write.table(text, file = "output.txt", col.names = F, row.names = F, quote = F)

The parameters col.names = FALSE and row.names = FALSE make sure to exclude the row and column names in the txt, and the parameter quote = FALSE excludes those quotation marks at the beginning and end of each line in the txt. To read the data back in, you can use text = readLines("output.txt").

How Can I Truncate A String In jQuery?

From: jQuery text truncation (read more style)

Try this:

var title = "This is your title";

var shortText = jQuery.trim(title).substring(0, 10)
    .split(" ").slice(0, -1).join(" ") + "...";

And you can also use a plugin:

As a extension of String

String.prototype.trimToLength = function(m) {
  return (this.length > m) 
    ? jQuery.trim(this).substring(0, m).split(" ").slice(0, -1).join(" ") + "..."
    : this;
};

Use as

"This is your title".trimToLength(10);

List file names based on a filename pattern and file content?

Grep DOES NOT use "wildcards" for search – that's shell globbing, like *.jpg. Grep uses "regular expressions" for pattern matching. While in the shell '*' means "anything", in grep it means "match the previous item zero or more times".

More information and examples here: http://www.regular-expressions.info/reference.html

To answer of your question - you can find files matching some pattern with grep:

find /somedir -type f -print | grep 'LMN2011' # that will show files whose names contain LMN2011

Then you can search their content (case insensitive):

find /somedir -type f -print | grep -i 'LMN2011' | xargs grep -i 'LMN20113456'

If the paths can contain spaces, you should use the "zero end" feature:

find /somedir -type f -print0 | grep -iz 'LMN2011' | xargs -0 grep -i 'LMN20113456'

Local file access with JavaScript

If you're deploying on Windows, the Windows Script Host offers a very useful JScript API to the file system and other local resources. Incorporating WSH scripts into a local web application may not be as elegant as you might wish, however.

What is the most effective way for float and double comparison?

Qt implements two functions, maybe you can learn from them:

static inline bool qFuzzyCompare(double p1, double p2)
{
    return (qAbs(p1 - p2) <= 0.000000000001 * qMin(qAbs(p1), qAbs(p2)));
}

static inline bool qFuzzyCompare(float p1, float p2)
{
    return (qAbs(p1 - p2) <= 0.00001f * qMin(qAbs(p1), qAbs(p2)));
}

And you may need the following functions, since

Note that comparing values where either p1 or p2 is 0.0 will not work, nor does comparing values where one of the values is NaN or infinity. If one of the values is always 0.0, use qFuzzyIsNull instead. If one of the values is likely to be 0.0, one solution is to add 1.0 to both values.

static inline bool qFuzzyIsNull(double d)
{
    return qAbs(d) <= 0.000000000001;
}

static inline bool qFuzzyIsNull(float f)
{
    return qAbs(f) <= 0.00001f;
}

How can I inspect the file system of a failed `docker build`?

Docker caches the entire filesystem state after each successful RUN line.

Knowing that:

  • to examine the latest state before your failing RUN command, comment it out in the Dockerfile (as well as any and all subsequent RUN commands), then run docker build and docker run again.
  • to examine the state after the failing RUN command, simply add || true to it to force it to succeed; then proceed like above (keep any and all subsequent RUN commands commented out, run docker build and docker run)

Tada, no need to mess with Docker internals or layer IDs, and as a bonus Docker automatically minimizes the amount of work that needs to be re-done.

Rails: select unique values from a column

This works too.

Model.pluck("DISTINCT rating")

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

If you are using eclipse, you should modify the context.xml, from the server project created in your eclipse package explorer. When using tomcat in eclipse it is the only one valid, the others are ignored or overwriten

maxFileSize and acceptFileTypes in blueimp file upload plugin do not work. Why?

This works for me in firefox

$('#fileupload').fileupload({

    dataType: 'json',
    //acceptFileTypes: /(\.|\/)(xml|pdf)$/i,
    //maxFileSize: 15000000,

    add: function (e, data) {
        var uploadErrors = [];

        var acceptFileTypes = /\/(pdf|xml)$/i;
        if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
            uploadErrors.push('File type not accepted');
        }

        console.log(data.originalFiles[0]['size']) ;
        if (data.originalFiles[0]['size'] > 5000000) {
            uploadErrors.push('Filesize too big');
        }
        if(uploadErrors.length > 0) {
            alert(uploadErrors.join("\n"));
        } else {
            data.context = $('<p/>').text('Uploading...').appendTo(document.body);
            data.submit();
        }

    },
    done: function (e, data) {
        data.context.text('Success!.');
    }
});

vim - How to delete a large block of text without counting the lines?

Go to the starting line and type ma (mark "a"). Then go to the last line and enter d'a (delete to mark "a").

That will delete all lines from the current to the marked one (inclusive). It's also compatible with vi as well as vim, on the off chance that your environment is not blessed with the latter.

Is it possible to declare a variable in Gradle usable in Java?

How can you insert String result of function into buildConfigField

Here's an example of build date in human-readable format set:

def getDate() {
    return new SimpleDateFormat("dd MMMM yyyy", new Locale("ru")).format(new Date())
}

def buildDate = getDate()

defaultConfig {
    buildConfigField "String", "BUILD_DATE", "\"$buildDate\""
}

Can a normal Class implement multiple interfaces?

Yes, it is possible. This is the catch: java does not support multiple inheritance, i.e. class cannot extend more than one class. However class can implement multiple interfaces.

JavaScript array to CSV

ES6:

let csv = test_array.map(row=>row.join(',')).join('\n') 
//test_array being your 2D array

How can I output a UTF-8 CSV in PHP that Excel will read properly?

Converting already utf-8 encoded text by using mb_convert_encoding is not needed. Just add three characters in front of the original content:

$newContent = chr(239) . chr(187) . chr(191) . $originalContent

For me this resolved the problem of special characters in csv files.

How to add trendline in python matplotlib dot (scatter) graphs?

as explained here

With help from numpy one can calculate for example a linear fitting.

# plot the data itself
pylab.plot(x,y,'o')

# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])

How can I simulate a click to an anchor tag?

None of the above solutions address the generic intention of the original request. What if we don't know the id of the anchor? What if it doesn't have an id? What if it doesn't even have an href parameter (e.g. prev/next icon in a carousel)? What if we want to apply the action to multiple anchors with different models in an agnostic fashion? Here's an example that does something instead of a click, then later simulates the click (for any anchor or other tag):

var clicker = null;
$('a').click(function(e){ 
    clicker=$(this); // capture the clicked dom object
    /* ... do something ... */
    e.preventDefault(); // prevent original click action
});
clicker[0].click(); // this repeats the original click. [0] is necessary.

How can I remove all objects but one from the workspace in R?

The following will remove all the objects from your console

rm(list = ls())

Java: Difference between the setPreferredSize() and setSize() methods in components

IIRC ...

setSize sets the size of the component.

setPreferredSize sets the preferred size. The Layoutmanager will try to arrange that much space for your component.

It depends on whether you're using a layout manager or not ...

How do I run a Python script from C#?

I am having problems with stdin/stout - when payload size exceeds several kilobytes it hangs. I need to call Python functions not only with some short arguments, but with a custom payload that could be big.

A while ago, I wrote a virtual actor library that allows to distribute task on different machines via Redis. To call Python code, I added functionality to listen for messages from Python, process them and return results back to .NET. Here is a brief description of how it works.

It works on a single machine as well, but requires a Redis instance. Redis adds some reliability guarantees - payload is stored until a worked acknowledges completion. If a worked dies, the payload is returned to a job queue and then is reprocessed by another worker.

Create numpy matrix filled with NaNs

Are you familiar with numpy.nan?

You can create your own method such as:

def nans(shape, dtype=float):
    a = numpy.empty(shape, dtype)
    a.fill(numpy.nan)
    return a

Then

nans([3,4])

would output

array([[ NaN,  NaN,  NaN,  NaN],
       [ NaN,  NaN,  NaN,  NaN],
       [ NaN,  NaN,  NaN,  NaN]])

I found this code in a mailing list thread.

Android : How to read file in bytes?

Since the accepted BufferedInputStream#read isn't guaranteed to read everything, rather than keeping track of the buffer sizes myself, I used this approach:

    byte bytes[] = new byte[(int) file.length()];
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
    DataInputStream dis = new DataInputStream(bis);
    dis.readFully(bytes);

Blocks until a full read is complete, and doesn't require extra imports.

How to style a checkbox using CSS

It seems you can change the colour of the checkbox in grayscale by using CSS only.

The following converts the checkboxes from black to gray (which was about what I wanted):

input[type="checkbox"] {
    opacity: .5;
}

Why is using the JavaScript eval function a bad idea?

If you spot the use of eval() in your code, remember the mantra “eval() is evil.”

This function takes an arbitrary string and executes it as JavaScript code. When the code in question is known beforehand (not determined at runtime), there’s no reason to use eval(). If the code is dynamically generated at runtime, there’s often a better way to achieve the goal without eval(). For example, just using square bracket notation to access dynamic properties is better and simpler:

// antipattern
var property = "name";
alert(eval("obj." + property));

// preferred
var property = "name";
alert(obj[property]);

Using eval() also has security implications, because you might be executing code (for example coming from the network) that has been tampered with. This is a common antipattern when dealing with a JSON response from an Ajax request. In those cases it’s better to use the browsers’ built-in methods to parse the JSON response to make sure it’s safe and valid. For browsers that don’t support JSON.parse() natively, you can use a library from JSON.org.

It’s also important to remember that passing strings to setInterval(), setTimeout(), and the Function() constructor is, for the most part, similar to using eval() and therefore should be avoided.

Behind the scenes, JavaScript still has to evaluate and execute the string you pass as programming code:

// antipatterns
setTimeout("myFunc()", 1000);
setTimeout("myFunc(1, 2, 3)", 1000);

// preferred
setTimeout(myFunc, 1000);
setTimeout(function () {
myFunc(1, 2, 3);
}, 1000);

Using the new Function() constructor is similar to eval() and should be approached with care. It could be a powerful construct but is often misused. If you absolutely must use eval(), you can consider using new Function() instead.

There is a small potential benefit because the code evaluated in new Function() will be running in a local function scope, so any variables defined with var in the code being evaluated will not become globals automatically.

Another way to prevent automatic globals is to wrap the eval() call into an immediate function.

Change color of Label in C#

You can try this with Color.FromArgb:

Random rnd = new Random();
lbl.ForeColor = Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255));

Why doesn't height: 100% work to expand divs to the screen height?

if you want, for example, a left column (height 100%) and the content (height auto) you can use absolute :

#left_column {
    float:left;
    position: absolute;
    max-height:100%;
    height:auto !important;
    height: 100%;
    overflow: hidden;

    width : 180px; /* for example */
}

#left_column div {
    height: 2000px;
}

#right_column {
    float:left;
    height:100%;
    margin-left : 180px; /* left column's width */
}

in html :

  <div id="content">
      <div id="left_column">
        my navigation content
        <div></div>
      </div>

      <div id="right_column">
        my content
      </div>
   </div>

How to set table name in dynamic SQL query?

Building on a previous answer by @user1172173 that addressed SQL Injection vulnerabilities, see below:

CREATE PROCEDURE [dbo].[spQ_SomeColumnByCustomerId](
@CustomerId int,
@SchemaName varchar(20),
@TableName nvarchar(200)) AS
SET Nocount ON
DECLARE @SQLQuery AS NVARCHAR(500)
DECLARE @ParameterDefinition AS NVARCHAR(100)
DECLARE @Table_ObjectId int;
DECLARE @Schema_ObjectId int;
DECLARE @Schema_Table_SecuredFromSqlInjection NVARCHAR(125)

SET @Table_ObjectId = OBJECT_ID(@TableName)
SET @Schema_ObjectId = SCHEMA_ID(@SchemaName)
SET @Schema_Table_SecuredFromSqlInjection = SCHEMA_NAME(@Schema_ObjectId) + '.' + OBJECT_NAME(@Table_ObjectId)

SET @SQLQuery = N'SELECT TOP 1 ' + @Schema_Table_SecuredFromSqlInjection + '.SomeColumn 
FROM dbo.Customer 
INNER JOIN ' + @Schema_Table_SecuredFromSqlInjection + ' 
ON dbo.Customer.Customerid = ' + @Schema_Table_SecuredFromSqlInjection + '.CustomerId 
WHERE dbo.Customer.CustomerID = @CustomerIdParam 
ORDER BY ' + @Schema_Table_SecuredFromSqlInjection + '.SomeColumn DESC' 
SET @ParameterDefinition =  N'@CustomerIdParam INT'

EXECUTE sp_executesql @SQLQuery, @ParameterDefinition, @CustomerIdParam = @CustomerId; RETURN

Converting Columns into rows with their respective data in sql server

i solved the query this way

SELECT
    ca.ID, ca.[Name]
FROM [Emp2]
CROSS APPLY (
      Values
         ('ID' , cast(ID as varchar)),
         ('[Name]' , Name)

  ) as CA (ID, Name)

output look like

  ID     Name
------ --------------------------------------------------
ID     1
[Name] Joy
ID     2
[Name] jean
ID     4
[Name] paul

Detect iPhone/iPad purely by css

iPhone & iPod touch:

<link rel="stylesheet" media="only screen and (max-device-width: 480px)" href="../iphone.css" type="text/css" />

iPhone 4 & iPod touch 4G:

<link rel="stylesheet" media="only screen and (-webkit-min-device-pixel-ratio: 2)" type="text/css" href="../iphone4.css" />

iPad:

<link rel="stylesheet" media="only screen and (max-device-width: 1024px)" href="../ipad.css" type="text/css" />

setting y-axis limit in matplotlib

Try this . Works for subplots too .

axes = plt.gca()
axes.set_xlim([xmin,xmax])
axes.set_ylim([ymin,ymax])

Java JSON serialization - best practice

Well, when writing it out to file, you do know what class T is, so you can store that in dump. Then, when reading it back in, you can dynamically call it using reflection.

public JSONObject dump() throws JSONException {
    JSONObject result = new JSONObject();
    JSONArray a = new JSONArray();
    for(T i : items){
        a.put(i.dump());
        // inside this i.dump(), store "class-name"
    }
    result.put("items", a);
    return result;
}

public void load(JSONObject obj) throws JSONException {
    JSONArray arrayItems = obj.getJSONArray("items");
    for (int i = 0; i < arrayItems.length(); i++) {
        JSONObject item = arrayItems.getJSONObject(i);
        String className = item.getString("class-name");
        try {
            Class<?> clazzy = Class.forName(className);
            T newItem = (T) clazzy.newInstance();
            newItem.load(obj);
            items.add(newItem);
        } catch (InstantiationException e) {
            // whatever
        } catch (IllegalAccessException e) {
            // whatever
        } catch (ClassNotFoundException e) {
            // whatever
        }
    }

jQuery ui datepicker with Angularjs

Unfortunately, vicont's answer did not work for me, so I searched for another solution which is as elegant and works for nested attributes in the ng-model as well. It uses $parse and accesses the ng-model through the attrs in the linking function instead of requiring it:

myApp.directive('myDatepicker', function ($parse) {
    return function (scope, element, attrs, controller) {
      var ngModel = $parse(attrs.ngModel);
      $(function(){
        element.datepicker({
            ...
            onSelect:function (dateText, inst) {
                scope.$apply(function(scope){
                    // Change binded variable
                    ngModel.assign(scope, dateText);
                });
            }
        });
     });
    } 
});

Source: ANGULAR.JS BINDING TO JQUERY UI (DATEPICKER EXAMPLE)

Global variable Python classes

What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut or via an instance e.g. shape.lolwut but be careful while setting it as it will set an instance level attribute not class attribute

class Shape(object):
    lolwut = 1

shape = Shape()

print Shape.lolwut,  # 1
print shape.lolwut,  # 1

# setting shape.lolwut would not change class attribute lolwut 
# but will create it in the instance
shape.lolwut = 2

print Shape.lolwut,  # 1
print shape.lolwut,  # 2

# to change class attribute access it via class
Shape.lolwut = 3

print Shape.lolwut,  # 3
print shape.lolwut   # 2 

output:

1 1 1 2 3 2

Somebody may expect output to be 1 1 2 2 3 3 but it would be incorrect

Parsing JSON Array within JSON Object

private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }

 String jsonText = readAll(inputofyourjsonstream);
 JSONObject json = new JSONObject(jsonText);
 JSONArray arr = json.getJSONArray("sources");

Your arr would looks like: [ { "id":1001, "name":"jhon" }, { "id":1002, "name":"jhon" } ] You can use:

arr.getJSONObject(index)

to get the objects inside of the array.

The view didn't return an HttpResponse object. It returned None instead

I had the same error using an UpdateView

I had this:

if form.is_valid() and form2.is_valid():
    form.save()
    form2.save()
    return HttpResponseRedirect(self.get_success_url())

and I solved just doing:

if form.is_valid() and form2.is_valid():
    form.save()
    form2.save()
    return HttpResponseRedirect(reverse_lazy('adopcion:solicitud_listar'))

Transpose a data frame

Take advantage of as.matrix:

# keep the first column 
names <-  df.aree[,1]

# Transpose everything other than the first column
df.aree.T <- as.data.frame(as.matrix(t(df.aree[,-1])))

# Assign first column as the column names of the transposed dataframe
colnames(df.aree.T) <- names

Splitting String with delimiter

How are you calling split? It works like this:

def values = '1182-2'.split('-')
assert values[0] == '1182'
assert values[1] == '2'

Cannot resolve symbol 'AppCompatActivity'

none of below solved my issue

  • Restart Android
  • File >> Synch Project with Gradle Files
  • Build >> Clean Project
  • Build >> Rebuild Project
  • File >> Invalidate Caches / Restart

Instead, I solved it by updating the version of appcompat & design dependencies to the recent version To do so: go to build.grade (Module:app) >> dependencies section and then hit ALT + ENTER on both appcompat & design dependencies then select the shown version in my case it's 24.2.1 as shown in the picture enter image description here

Problems installing the devtools package

I found solution by seeing errors by R-Studio when I tried to install devtools package...Basically Error is because of dependence libraries not installed in linux Look at ANTICONF ERROR Below

Installing package into ‘/home/hafiz/R/x86_64-pc-linux-gnu-library/3.6’
(as ‘lib’ is unspecified)
also installing the dependencies ‘curl’, ‘gh’, ‘openssl’, ‘xml2’, ‘usethis’, ‘covr’, ‘httr’, ‘roxygen2’, ‘rversions’


trying URL 'https://cloud.r-project.org/src/contrib/curl_4.3.tar.gz'
Content type 'application/x-gzip' length 673779 bytes (657 KB)
==================================================
downloaded 657 KB

trying URL 'https://cloud.r-project.org/src/contrib/gh_1.1.0.tar.gz'
Content type 'application/x-gzip' length 29043 bytes (28 KB)
==================================================
downloaded 28 KB

trying URL 'https://cloud.r-project.org/src/contrib/openssl_1.4.2.tar.gz'
Content type 'application/x-gzip' length 1204168 bytes (1.1 MB)
==================================================
downloaded 1.1 MB

trying URL 'https://cloud.r-project.org/src/contrib/xml2_1.3.2.tar.gz'
Content type 'application/x-gzip' length 271876 bytes (265 KB)
==================================================
downloaded 265 KB

trying URL 'https://cloud.r-project.org/src/contrib/usethis_1.6.1.tar.gz'
Content type 'application/x-gzip' length 255052 bytes (249 KB)
==================================================
downloaded 249 KB

trying URL 'https://cloud.r-project.org/src/contrib/covr_3.5.0.tar.gz'
Content type 'application/x-gzip' length 146148 bytes (142 KB)
==================================================
downloaded 142 KB

trying URL 'https://cloud.r-project.org/src/contrib/httr_1.4.2.tar.gz'
Content type 'application/x-gzip' length 159950 bytes (156 KB)
==================================================
downloaded 156 KB

trying URL 'https://cloud.r-project.org/src/contrib/roxygen2_7.1.1.tar.gz'
Content type 'application/x-gzip' length 254118 bytes (248 KB)
==================================================
downloaded 248 KB

trying URL 'https://cloud.r-project.org/src/contrib/rversions_2.0.2.tar.gz'
Content type 'application/x-gzip' length 41558 bytes (40 KB)
==================================================
downloaded 40 KB

trying URL 'https://cloud.r-project.org/src/contrib/devtools_2.3.1.tar.gz'
Content type 'application/x-gzip' length 373604 bytes (364 KB)
==================================================
downloaded 364 KB

* installing *source* package ‘curl’ ...
** package ‘curl’ successfully unpacked and MD5 sums checked
** using staged installation
Package libcurl was not found in the pkg-config search path.
Perhaps you should add the directory containing `libcurl.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libcurl' found
Package libcurl was not found in the pkg-config search path.
Perhaps you should add the directory containing `libcurl.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libcurl' found
Using PKG_CFLAGS=
Using PKG_LIBS=-lcurl
------------------------- ANTICONF ERROR ---------------------------
Configuration failed because libcurl was not found. Try installing:
  deb: **libcurl4-openssl-dev** (Debian, Ubuntu, etc)
 * rpm: libcurl-devel (Fedora, CentOS, RHEL)
 * csw: libcurl_dev (Solaris)
If libcurl is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a libcurl.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'
--------------------------------------------------------------------
ERROR: configuration failed for package ‘curl’
* removing ‘/home/hafiz/R/x86_64-pc-linux-gnu-library/3.6/curl’
Warning in install.packages :
  installation of package ‘curl’ had non-zero exit status
* installing *source* package ‘openssl’ ...
** package ‘openssl’ successfully unpacked and MD5 sums checked
** using staged installation
Using PKG_CFLAGS=
--------------------------- [ANTICONF] --------------------------------
Configuration failed because openssl was not found. Try installing:
  deb: **libssl-dev** (Debian, Ubuntu, etc)
 * rpm: openssl-devel (Fedora, CentOS, RHEL)
 * csw: libssl_dev (Solaris)
 * brew: [email protected] (Mac OSX)
If openssl is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a openssl.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'
-------------------------- [ERROR MESSAGE] ---------------------------
tools/version.c:1:10: fatal error: openssl/opensslv.h: No such file or directory
    1 | #include <openssl/opensslv.h>
      |          ^~~~~~~~~~~~~~~~~~~~
compilation terminated.
--------------------------------------------------------------------
ERROR: configuration failed for package ‘openssl’
* removing ‘/home/hafiz/R/x86_64-pc-linux-gnu-library/3.6/openssl’
Warning in install.packages :
  installation of package ‘openssl’ had non-zero exit status
* installing *source* package ‘xml2’ ...
** package ‘xml2’ successfully unpacked and MD5 sums checked
** using staged installation
Package libxml-2.0 was not found in the pkg-config search path.
Perhaps you should add the directory containing `libxml-2.0.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libxml-2.0' found
Package libxml-2.0 was not found in the pkg-config search path.
Perhaps you should add the directory containing `libxml-2.0.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libxml-2.0' found
Using PKG_CFLAGS=
Using PKG_LIBS=-lxml2
------------------------- ANTICONF ERROR ---------------------------
Configuration failed because libxml-2.0 was not found. Try installing:
 deb: **libxml2-dev** (Debian, Ubuntu, etc)
 * rpm: libxml2-devel (Fedora, CentOS, RHEL)
 * csw: libxml2_dev (Solaris)
If libxml-2.0 is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a libxml-2.0.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'
--------------------------------------------------------------------
ERROR: configuration failed for package ‘xml2’
* removing ‘/home/hafiz/R/x86_64-pc-linux-gnu-library/3.6/xml2’
Warning in install.packages :
  installation of package ‘xml2’ had non-zero exit status
ERROR: dependencies ‘curl’, ‘openssl’ are not available for package ‘httr’
* removing ‘/home/hafiz/R/x86_64-pc-linux-gnu-library/3.6/httr’
Warning in install.packages :
  installation of package ‘httr’ had non-zero exit status
ERROR: dependency ‘xml2’ is not available for package ‘roxygen2’
* removing ‘/home/hafiz/R/x86_64-pc-linux-gnu-library/3.6/roxygen2’
Warning in install.packages :
  installation of package ‘roxygen2’ had non-zero exit status
ERROR: dependencies ‘curl’, ‘xml2’ are not available for package ‘rversions’
* removing ‘/home/hafiz/R/x86_64-pc-linux-gnu-library/3.6/rversions’
Warning in install.packages :
  installation of package ‘rversions’ had non-zero exit status
ERROR: dependency ‘httr’ is not available for package ‘gh’
* removing ‘/home/hafiz/R/x86_64-pc-linux-gnu-library/3.6/gh’
Warning in install.packages :
  installation of package ‘gh’ had non-zero exit status
ERROR: dependency ‘httr’ is not available for package ‘covr’
* removing ‘/home/hafiz/R/x86_64-pc-linux-gnu-library/3.6/covr’
Warning in install.packages :
  installation of package ‘covr’ had non-zero exit status
ERROR: dependencies ‘curl’, ‘gh’ are not available for package ‘usethis’
* removing ‘/home/hafiz/R/x86_64-pc-linux-gnu-library/3.6/usethis’
Warning in install.packages :
  installation of package ‘usethis’ had non-zero exit status
ERROR: dependencies ‘usethis’, ‘covr’, ‘httr’, ‘roxygen2’, ‘rversions’ are not available for package ‘devtools’
* removing ‘/home/hafiz/R/x86_64-pc-linux-gnu-library/3.6/devtools’
Warning in install.packages :
  installation of package ‘devtools’ had non-zero exit status

The downloaded source packages are in
    ‘/tmp/Rtmpexapon/downloaded_packages’

look at bold libraries which are missing libssl-dev libxml2-dev

just you need to install these libraries in ubuntu terminal or

whatever operating system you are using you will find relative errors w r t operating system see errors in details.. R-studio mentioned relative library package name against operating system

for ubuntu i did this

sudo apt-get install libssl-dev

**sudo apt-get install libxml2-dev **

sudo apt-get install libcurl4-openssl-dev