Programs & Examples On #Integer overflow

Integer overflow occurs when the result of an operation is larger than the maximal value that can be represented by the underlying integer type.

How do I detect unsigned integer multiply overflow?

Warning: GCC can optimize away an overflow check when compiling with -O2. The option -Wall will give you a warning in some cases like

if (a + b < a) { /* Deal with overflow */ }

but not in this example:

b = abs(a);
if (b < 0) { /* Deal with overflow */ }

The only safe way is to check for overflow before it occurs, as described in the CERT paper, and this would be incredibly tedious to use systematically.

Compiling with -fwrapv solves the problem, but disables some optimizations.

We desperately need a better solution. I think the compiler should issue a warning by default when making an optimization that relies on overflow not occurring. The present situation allows the compiler to optimize away an overflow check, which is unacceptable in my opinion.

How does Java handle integer underflows and overflows and how would you check for it?

It doesn't do anything -- the under/overflow just happens.

A "-1" that is the result of a computation that overflowed is no different from the "-1" that resulted from any other information. So you can't tell via some status or by inspecting just a value whether it's overflowed.

But you can be smart about your computations in order to avoid overflow, if it matters, or at least know when it will happen. What's your situation?

What is offsetHeight, clientHeight, scrollHeight?

Offset Means "the amount or distance by which something is out of line". Margin or Borders are something which makes the actual height or width of an HTML element "out of line". It will help you to remember that :

  • offsetHeight is a measurement in pixels of the element's CSS height, including border, padding and the element's horizontal scrollbar.

On the other hand, clientHeight is something which is you can say kind of the opposite of OffsetHeight. It doesn't include the border or margins. It does include the padding because it is something that resides inside of the HTML container, so it doesn't count as extra measurements like margin or border. So :

  • clientHeight property returns the viewable height of an element in pixels, including padding, but not the border, scrollbar or margin.

ScrollHeight is all the scrollable area, so your scroll will never run over your margin or border, so that's why scrollHeight doesn't include margin or borders but yeah padding does. So:

  • scrollHeight value is equal to the minimum height the element would require in order to fit all the content in the viewport without using a vertical scrollbar. The height is measured in the same way as clientHeight: it includes the element's padding, but not its border, margin or horizontal scrollbar.

C++ error: undefined reference to 'clock_gettime' and 'clock_settime'

Add -lrt to the end of g++ command line. This links in the librt.so "Real Time" shared library.

How to emulate GPS location in the Android Emulator?

If you are using eclipse then using Emulator controller you can manually set latitude and longitude and run your map based app in emulator

Error renaming a column in MySQL

EDIT

You can rename fields using:

ALTER TABLE xyz CHANGE manufacurerid manufacturerid INT

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

Get screenshot on Windows with Python?

import pyautogui

s = pyautogui.screenshot()
s.save(r'C:\\Users\\NAME\\Pictures\\s.png')

calculating the difference in months between two dates

The problem with months is that it isn't really a simple measure - they aren't constant size. You would need to define your rules for what you want to include, and work from there. For example 1 Jan to 1 Feb - you could argue 2 months are involved there, or you could say that is one month. Then what about "1 Jan 20:00" to "1 Feb 00:00" - that isn't quite an entire full month. Is that 0? 1? what about the other way around (1 Jan 00:00 to 1 Feb 20:00)... 1? 2?

First define the rules, then you'll have to code it yourself, I'm afraid...

How to send HTTP request in java?

Apache HttpComponents. The examples for the two modules - HttpCore and HttpClient will get you started right away.

Not that HttpUrlConnection is a bad choice, HttpComponents will abstract a lot of the tedious coding away. I would recommend this, if you really want to support a lot of HTTP servers/clients with minimum code. By the way, HttpCore could be used for applications (clients or servers) with minimum functionality, whereas HttpClient is to be used for clients that require support for multiple authentication schemes, cookie support etc.

What is the __del__ method, How to call it?

As mentioned earlier, the __del__ functionality is somewhat unreliable. In cases where it might seem useful, consider using the __enter__ and __exit__ methods instead. This will give a behaviour similar to the with open() as f: pass syntax used for accessing files. __enter__ is automatically called when entering the scope of with, while __exit__ is automatically called when exiting it. See this question for more details.

Forking / Multi-Threaded Processes | Bash

With GNU Parallel you can do:

cat file | parallel 'foo {}; foo2 {}; foo3 {}'

This will run one job on each cpu core. To run 50 do:

cat file | parallel -j 50 'foo {}; foo2 {}; foo3 {}'

Watch the intro videos to learn more:

http://www.youtube.com/playlist?list=PL284C9FF2488BC6D1

Bootstrap: Position of dropdown menu relative to navbar item

Not sure about how other people solve this problem or whether Bootstrap has any configuration for this.

I found this thread that provides a solution:

https://github.com/twbs/bootstrap/issues/1411

One of the post suggests the use of

<ul class="dropdown-menu" style="right: 0; left: auto;">

I tested and it works.

Hope to know whether Bootstrap provides config for doing this, not via the above css.

Cheers.

how to check which version of nltk, scikit learn installed?

You can find NLTK version simply by doing:

In [1]: import nltk

In [2]: nltk.__version__
Out[2]: '3.2.5'

And similarly for scikit-learn,

In [3]: import sklearn

In [4]: sklearn.__version__
Out[4]: '0.19.0'

I'm using python3 here.

Best Practice for Forcing Garbage Collection in C#

Look at it this way - is it more efficient to throw out the kitchen garbage when the garbage can is at 10% or let it fill up before taking it out?

By not letting it fill up, you are wasting your time walking to and from the garbage bin outside. This analogous to what happens when the GC thread runs - all the managed threads are suspended while it is running. And If I am not mistaken, the GC thread can be shared among multiple AppDomains, so garbage collection affects all of them.

Of course, you might encounter a situation where you won't be adding anything to the garbage can anytime soon - say, if you're going to take a vacation. Then, it would be a good idea to throw out the trash before going out.

This MIGHT be one time that forcing a GC can help - if your program idles, the memory in use is not garbage-collected because there are no allocations.

How to update array value javascript?

"But i want to know a better way to do this, if there is one ?"

Yes, since you seem to already have the original object, there's no reason to fetch it again from the Array.

  function Update(keyValue, newKey, newValue)
  {
    keyValue.Key = newKey;
    keyValue.Value = newValue; 
  }

Change NULL values in Datetime format to empty string

This also works:

REPLACE(ISNULL(CONVERT(DATE, @date), ''), '1900-01-01', '') AS 'Your Date Field'

Bulk Insert to Oracle using .NET

A really fast way to solve this problem is to make a database link from the Oracle database to the MySQL database. You can create database links to non-Oracle databases. After you have created the database link you can retrieve your data from the MySQL database with a ... create table mydata as select * from ... statement. This is called heterogeneous connectivity. This way you don't have to do anything in your .net application to move the data.

Another way is to use ODP.NET. In ODP.NET you can use the OracleBulkCopy-class.

But I don't think that inserting 160k records in an Oracle table with System.Data.OracleClient should take 25 minutes. I think you commit too many times. And do you bind your values to the insert statement with parameters or do you concatenate your values. Binding is much faster.

NodeJS w/Express Error: Cannot GET /

You need to add a return to the index.html file.

app.use(express.static(path.join(__dirname, 'build')));

app.get('*', function(req, res) {res.sendFile(path.join(__dirname + '/build/index.html')); });

how get yesterday and tomorrow datetime in c#

DateTime tomorrow = DateTime.Today.AddDays(1);
DateTime yesterday = DateTime.Today.AddDays(-1);

How to delete last item in list?

list.pop() removes and returns the last element of the list.

SFTP in Python? (platform independent)

PyFilesystem with its sshfs is one option. It uses Paramiko under the hood and provides a nicer paltform independent interface on top.

import fs

sf = fs.open_fs("sftp://[user[:password]@]host[:port]/[directory]")
sf.makedir('my_dir')

or

from fs.sshfs import SSHFS
sf = SSHFS(...

How to access cookies in AngularJS?

Here's a simple example using $cookies. After clicking on button, the cookie is saved, and then restored after page is reloaded.

app.html:

<html ng-app="app">
<head>
    <meta charset="utf-8" />
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-cookies.js"></script>
    <script src="app.js"></script>
</head>
<body ng-controller="appController as vm">

    <input type="text" ng-model="vm.food" placeholder="Enter food" />

    <p>My favorite food is {{vm.food}}.</p>

    <p>Open new window, then press Back button.</p>
    <button ng-click="vm.openUrl()">Open</button>
</body>
</html>

app.js:

(function () {
    "use strict";

    angular.module('app', ['ngCookies'])
    .controller('appController', ['$cookies', '$window', function ($cookies, $window) {
        var vm = this;

        //get cookie
        vm.food = $cookies.get('myFavorite');

        vm.openUrl = function () {
            //save cookie
            $cookies.put('myFavorite', vm.food);
            $window.open("http://www.google.com", "_self");
        };
    }]);

})();

How to remove item from a python list in a loop?

hymloth and sven's answers work, but they do not modify the list (the create a new one). If you need the object modification you need to assign to a slice:

x[:] = [value for value in x if len(value)==2]

However, for large lists in which you need to remove few elements, this is memory consuming, but it runs in O(n).

glglgl's answer suffers from O(n²) complexity, because list.remove is O(n).

Depending on the structure of your data, you may prefer noting the indexes of the elements to remove and using the del keywork to remove by index:

to_remove = [i for i, val in enumerate(x) if len(val)==2]
for index in reversed(to_remove): # start at the end to avoid recomputing offsets
    del x[index]

Now del x[i] is also O(n) because you need to copy all elements after index i (a list is a vector), so you'll need to test this against your data. Still this should be faster than using remove because you don't pay for the cost of the search step of remove, and the copy step cost is the same in both cases.

[edit] Very nice in-place, O(n) version with limited memory requirements, courtesy of @Sven Marnach. It uses itertools.compress which was introduced in python 2.7:

from itertools import compress

selectors = (len(s) == 2 for s in x)
for i, s in enumerate(compress(x, selectors)): # enumerate elements of length 2
    x[i] = s # move found element to beginning of the list, without resizing
del x[i+1:]  # trim the end of the list

See full command of running/stopped container in Docker

Moving Dylan's comment into a full-blown answer because TOO USEFUL:

docker run --rm -v /var/run/docker.sock:/var/run/docker.sock assaflavie/runlike YOUR-CONTAINER

What does it do? Runs https://github.com/lavie/runlike inside a container, gets you the complete docker run command, then removes the container for you.

Display UIViewController as Popup in iPhone

You can use EzPopup (https://github.com/huynguyencong/EzPopup), it is a Swift pod and very easy to use:

// init YourViewController
let contentVC = ...

// Init popup view controller with content is your content view controller
let popupVC = PopupViewController(contentController: contentVC, popupWidth: 100, popupHeight: 200)

// show it by call present(_ , animated:) method from a current UIViewController
present(popupVC, animated: true)

Is there any ASCII character for <br>?

No, there isn't.

<br> is an HTML ELEMENT. It can't be replaced by a text node or part of a text node.

You can create a new-line effect using CR/LF inside a <pre> element like below:

_x000D_
_x000D_
<pre>Line 1_x000D_
Line 2</pre>
_x000D_
_x000D_
_x000D_

But this is not the same as a <br>.

Doctrine 2 ArrayCollection filter method

The Boris Guéry answer's at this post, may help you: Doctrine 2, query inside entities

$idsToFilter = array(1,2,3,4);

$member->getComments()->filter(
    function($entry) use ($idsToFilter) {
       return in_array($entry->getId(), $idsToFilter);
    }
); 

Populating a razor dropdownlist from a List<object> in MVC

You can separate out your business logic into a viewmodel, so your view has cleaner separation.

First create a viewmodel to store the Id the user will select along with a list of items that will appear in the DropDown.

ViewModel:

public class UserRoleViewModel
{
    // Display Attribute will appear in the Html.LabelFor
    [Display(Name = "User Role")]
    public int SelectedUserRoleId { get; set; }
    public IEnumerable<SelectListItem> UserRoles { get; set; }
}

References:

Inside the controller create a method to get your UserRole list and transform it into the form that will be presented in the view.

Controller:

private IEnumerable<SelectListItem> GetRoles()
{
    var dbUserRoles = new DbUserRoles();
    var roles = dbUserRoles
                .GetRoles()
                .Select(x =>
                        new SelectListItem
                            {
                                Value = x.UserRoleId.ToString(),
                                Text = x.UserRole
                            });

    return new SelectList(roles, "Value", "Text");
}

public ActionResult AddNewUser()
{
    var model = new UserRoleViewModel
                    {
                        UserRoles = GetRoles()
                    };
    return View(model);
}

References:

Now that the viewmodel is created the presentation logic is simplified

View:

@model UserRoleViewModel

@Html.LabelFor(m => m.SelectedUserRoleId)
@Html.DropDownListFor(m => m.SelectedUserRoleId, Model.UserRoles)

References:

This will produce:

<label for="SelectedUserRoleId">User Role</label>
<select id="SelectedUserRoleId" name="SelectedUserRoleId">
    <option value="1">First Role</option>
    <option value="2">Second Role</option>
    <option value="3">Etc...</option>
</select>

How do I create a view controller file after creating a new view controller?

To add new ViewController once you have have an existing ViewController, follow below step:

  1. Click on background of Main.storyboard.

  2. Search and select ViewController from object library at the utility window.

  3. Drag and drop it in background to create a new ViewController.

How to prevent "The play() request was interrupted by a call to pause()" error?

The cleanest and simplest solution:

var p = video.play();
if (p !== undefined) p.catch(function(){});

Cannot find java. Please use the --jdkhome switch

With the Netbeans 10, commenting out the netbeans_jdkhome setting in .../etc/netbeans.conf doesn't do the job anymore. It is necessary to specify the right directory depending of 32/64 bitness.

E.g. for 64 bit application: netbeans_jdkhome="C:\Program Files\AdoptOpenJDK\jdk8u202-b08"

SQL NVARCHAR and VARCHAR Limits

declare @p varbinary(max)
set @p = 0x
declare @local table (col text)

SELECT   @p = @p + 0x3B + CONVERT(varbinary(100), Email)
 FROM tbCarsList
 where email <> ''
 group by email
 order by email

 set @p = substring(@p, 2, 100000)

 insert @local values(cast(@p as varchar(max)))
 select DATALENGTH(col) as collen, col from @local

result collen > 8000, length col value is more than 8000 chars

What is the strict aliasing rule?

Type punning via pointer casts (as opposed to using a union) is a major example of breaking strict aliasing.

Delete all lines starting with # or ; in Notepad++

In Notepad++, you can use the Mark tab in the Find dialogue to Bookmark all lines matching your query which can be regex or normal (wildcard).

Then use Search > Bookmark > Remove Bookmarked Lines.

How to deploy a war file in Tomcat 7

Perform the following steps:

  • Stop the Tomcat
  • Right Click on Project and click on "Clean and Build"
  • Go to your project Directory and inside Dist Folder you will get war file that you copy on your tomcat
  • webApp Folder
  • Start the tomcat
  • automatic war file extract and run your project

How can I check if a checkbox is checked?

Use this below simple code: https://jsfiddle.net/Divyesh_Patel/v7a4h3kr/7/

_x000D_
_x000D_
<input type="checkbox" id="check">_x000D_
<a href="#" onclick="check()">click</a>_x000D_
<button onclick="check()">_x000D_
button_x000D_
</button>_x000D_
<script>_x000D_
 function check() {_x000D_
      if (document.getElementById('check').checked) {_x000D_
            alert("checked");_x000D_
        } else {_x000D_
            alert("You didn't check it! Let me check it for you.");_x000D_
        }_x000D_
       _x000D_
    }_x000D_
_x000D_
</script>
_x000D_
_x000D_
_x000D_

How can you check for a #hash in a URL using JavaScript?

var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);

Mocking static methods with Mockito

You can do it with a little bit of refactoring:

public class MySQLDatabaseConnectionFactory implements DatabaseConnectionFactory {

    @Override public Connection getConnection() {
        try {
            return _getConnection(...some params...);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //method to forward parameters, enabling mocking, extension, etc
    Connection _getConnection(...some params...) throws SQLException {
        return DriverManager.getConnection(...some params...);
    }
}

Then you can extend your class MySQLDatabaseConnectionFactory to return a mocked connection, do assertions on the parameters, etc.

The extended class can reside within the test case, if it's located in the same package (which I encourage you to do)

public class MockedConnectionFactory extends MySQLDatabaseConnectionFactory {

    Connection _getConnection(...some params...) throws SQLException {
        if (some param != something) throw new InvalidParameterException();

        //consider mocking some methods with when(yourMock.something()).thenReturn(value)
        return Mockito.mock(Connection.class);
    }
}

How can I get the corresponding table header (th) from a table cell (td)?

You can do it by using the td's index:

var tdIndex = $td.index() + 1;
var $th = $('#table tr').find('th:nth-child(' + tdIndex + ')');

How to have image and text side by side

You're already doing it correctly, it just that the <h4>Facebook</h4> tag is taking too much vertical margin. You can remove it by using the style margin:0px on the <h4> tag.

For your future convenience, you can put border (border:1px solid black) on your elements to see which part you actually get it wrong.

standard_init_linux.go:190: exec user process caused "no such file or directory" - Docker

Use notepad++, go to edit -> EOL conversion -> change from CRLF to LF.

Why I can't change directories using "cd"?

This combines the answer by Serge with an unrelated answer by David. It changes the directory, and then instead of forcing a bash shell, it launches the user's default shell. It however requires both getent and /etc/passwd to detect the default shell.

#!/usr/bin/env bash
cd desired/directory
USER_SHELL=$(getent passwd <USER> | cut -d : -f 7)
$USER_SHELL

Of course this still has the same deficiency of creating a nested shell.

Angular, content type is not being sent with $http

$http({
    url: 'http://localhost:8080/example/teste',
    dataType: 'json',
    method: 'POST',
    data: '',
    headers: {
        "Content-Type": "application/json"
    }

}).success(function(response){
    $scope.response = response;
}).error(function(error){
    $scope.error = error;
});

Try like this.

What should I set JAVA_HOME environment variable on macOS X 10.6?

It is recommended to check default terminal shell before set JAVA_HOME environment variable, via following commands:

$ echo $SHELL
/bin/bash

If your default terminal is /bin/bash (Bash), then you should use @hygull method

If your default terminal is /bin/zsh (Z Shell), then you should set these environment variable in ~/.zshenv file with following contents:

export JAVA_HOME="$(/usr/libexec/java_home)"

Similarly, any other terminal type not mentioned above, you should set environment variable in its respective terminal env file.

This method tested working in macOS Mojave Version 10.14.6.

How can I create a unique constraint on my column (SQL Server 2008 R2)?

One thing not clearly covered is that microsoft sql is creating in the background an unique index for the added constraint

create table Customer ( id int primary key identity (1,1) , name nvarchar(128) ) 

--Commands completed successfully.

sp_help Customer

---> index
--index_name    index_description   index_keys
--PK__Customer__3213E83FCC4A1DFA    clustered, unique, primary key located on PRIMARY   id

---> constraint
--constraint_type   constraint_name delete_action   update_action   status_enabled  status_for_replication  constraint_keys
--PRIMARY KEY (clustered)   PK__Customer__3213E83FCC4A1DFA  (n/a)   (n/a)   (n/a)   (n/a)   id


---- now adding the unique constraint

ALTER TABLE Customer ADD CONSTRAINT U_Name UNIQUE(Name)

-- Commands completed successfully.

sp_help Customer

---> index
---index_name   index_description   index_keys
---PK__Customer__3213E83FCC4A1DFA   clustered, unique, primary key located on PRIMARY   id
---U_Name   nonclustered, unique, unique key located on PRIMARY name

---> constraint
---constraint_type  constraint_name delete_action   update_action   status_enabled  status_for_replication  constraint_keys
---PRIMARY KEY (clustered)  PK__Customer__3213E83FCC4A1DFA  (n/a)   (n/a)   (n/a)   (n/a)   id
---UNIQUE (non-clustered)   U_Name  (n/a)   (n/a)   (n/a)   (n/a)   name

as you can see , there is a new constraint and a new index U_Name

How to log out user from web site using BASIC authentication?

Here's a very simple Javascript example using jQuery:

function logout(to_url) {
    var out = window.location.href.replace(/:\/\//, '://log:out@');

    jQuery.get(out).error(function() {
        window.location = to_url;
    });
}

This log user out without showing him the browser log-in box again, then redirect him to a logged out page

How do I execute a program from Python? os.system fails due to spaces in path

Here's a different way of doing it.

If you're using Windows the following acts like double-clicking the file in Explorer, or giving the file name as an argument to the DOS "start" command: the file is opened with whatever application (if any) its extension is associated with.

filepath = 'textfile.txt'
import os
os.startfile(filepath)

Example:

import os
os.startfile('textfile.txt')

This will open textfile.txt with Notepad if Notepad is associated with .txt files.

Android add placeholder text to EditText

This how to make input password that has hint which not converted to * !!.

On XML :

android:inputType="textPassword"
android:gravity="center"
android:ellipsize="start"
android:hint="Input Password !."

thanks to : mango and rjrjr for the insight :D.

Getting time and date from timestamp with php

$mydatetime = "2012-04-02 02:57:54";
$datetimearray = explode(" ", $mydatetime);
$date = $datetimearray[0];
$time = $datetimearray[1];
$reformatted_date = date('d-m-Y',strtotime($date));
$reformatted_time = date('Gi.s',strtotime($time));

Declare and Initialize String Array in VBA

The problem here is that the length of your array is undefined, and this confuses VBA if the array is explicitly defined as a string. Variants, however, seem to be able to resize as needed (because they hog a bunch of memory, and people generally avoid them for a bunch of reasons).

The following code works just fine, but it's a bit manual compared to some of the other languages out there:

Dim SomeArray(3) As String

SomeArray(0) = "Zero"
SomeArray(1) = "One"
SomeArray(2) = "Two"
SomeArray(3) = "Three"

Can a unit test project load the target application's app.config file?

If you application is using setting such as Asp.net ConnectionString you need to add the attribute HostType to your method, else they wont load even if you have an App.Config file.

[TestMethod]
[HostType("ASP.NET")] // will load the ConnectionString from the App.Config file
public void Test() {

}

Dynamic height for DIV

This worked for me as-
HTML-

    <div style="background-color: #535; width: 100%; height: 80px;">
        <div class="center">
            Test <br>
            kumar adnioas<br>
            sanjay<br>
            1990
        </div>
    </div> 

CSS-

.center {
    position: relative;
    left: 50%;
    top: 50%;
    height: 82%;
    transform: translate(-50%, -50%);
    transform: -webkit-translate(-50%, -50%);
    transform: -ms-translate(-50%, -50%);
   }  

Hope will help you too.

How to ignore PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException?

I also came across the same issue. I was trying to build the project with a clean install goal. I simply changed it to clean package -o in the run configuration. Then I re-built the project and it worked for me.

TypeScript for ... of with index / key?

.forEach already has this ability:

const someArray = [9, 2, 5];
someArray.forEach((value, index) => {
    console.log(index); // 0, 1, 2
    console.log(value); // 9, 2, 5
});

But if you want the abilities of for...of, then you can map the array to the index and value:

for (const { index, value } of someArray.map((value, index) => ({ index, value }))) {
    console.log(index); // 0, 1, 2
    console.log(value); // 9, 2, 5
}

That's a little long, so it may help to put it in a reusable function:

function toEntries<T>(a: T[]) {
    return a.map((value, index) => [index, value] as const);
}

for (const [index, value] of toEntries(someArray)) {
    // ..etc..
}

Iterable Version

This will work when targeting ES3 or ES5 if you compile with the --downlevelIteration compiler option.

function* toEntries<T>(values: T[] | IterableIterator<T>) {
    let index = 0;
    for (const value of values) {
        yield [index, value] as const;
        index++;
    }
}

Array.prototype.entries() - ES6+

If you are able to target ES6+ environments then you can use the .entries() method as outlined in Arnavion's answer.

Adding CSRFToken to Ajax request

From JSP

<form method="post" id="myForm" action="someURL">
    <input name="csrfToken" value="5965f0d244b7d32b334eff840...etc" type="hidden">    
</form>

This is the simplest way that worked for me after struggling for 3hrs, just get the token from input hidden field like this and while doing the AJAX request to just need to pass this token in header as follows:-

From Jquery

var token =  $('input[name="csrfToken"]').attr('value'); 

From plain Javascript

var token = document.getElementsByName("csrfToken").value;

Final AJAX Request

$.ajax({
      url: route.url,
      data : JSON.stringify(data),
      method : 'POST',
      headers: {
                    'X-CSRF-Token': token 
               },
      success: function (data) { ...      },
      error: function (data) { ...  }

});

Now you don't need to disable crsf security in web config, and also this will not give you 405( Method Not Allowed) error on console.

Hope this will help people..!!

Copy files without overwrite

robocopy src dst /MIR /XX

/XX : eXclude "eXtra" files and dirs (present in destination but not source). This will prevent any deletions from the destination. (this is the default)

Auto Generate Database Diagram MySQL

I believe DB Designer does something like that. And I think they even have a free version.

edit Never mind. Michael's link is much better.

MySQL equivalent of DECODE function in Oracle

Try this:

Select Name, ELT(Age-12,'Thirteen','Fourteen','Fifteen','Sixteen',
   'Seventeen','Eighteen','Nineteen','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult') AS AgeBracket FROM Person

PHP strtotime +1 month adding an extra month

today is 29th of January, +1 month means 29th of Fabruary, but because February consists of 28 days this year, it overlaps to the next day which is March 1st

instead try

strtotime('next month')

Php multiple delimiters in explode

I do it this way...

public static function multiExplode($delims, $string, $special = '|||') {

    if (is_array($delims) == false) {
        $delims = array($delims);
    }

    if (empty($delims) == false) {
        foreach ($delims as $d) {
            $string = str_replace($d, $special, $string);
        }
    }

    return explode($special, $string);
}

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

Import Google Play Services library in Android Studio

I got the same problem. I just tried to rebuild, clean and restart but no luck. Then I just remove

compile 'com.google.android.gms:play-services:8.3.0'

from build.gradle and resync. After that I put it again and resync. Next to that, I clean the project and the problem is gone!!

I hope it will help any of you facing the same.

Error importing Seaborn module in Python

pip install seaborn 

is also solved my problem in windows 10

How to make a <div> always full screen?

I don't have IE Josh, could you please test this for me. Thanks.

<html>
<head>
    <title>Hellomoto</title>
    <style text="text/javascript">
        .hellomoto
        {
            background-color:#ccc;
            position:absolute;
            top:0px;
            left:0px;
            width:100%;
            height:100%;
            overflow:auto;
        }
        body
        {
            background-color:#ff00ff;
            padding:0px;
            margin:0px;
            width:100%;
            height:100%;
            overflow:hidden;
        }
        .text
        {
            background-color:#cc00cc;
            height:800px;
            width:500px;
        }
    </style>
</head>
<body>
<div class="hellomoto">
    <div class="text">hellomoto</div>
</div>
</body>
</html>

MVC3 EditorFor readOnly

I know the question states MVC 3, but it was 2012, so just in case:

As of MVC 5.1 you can now pass HTML attributes to EditorFor like so:

@Html.EditorFor(x => x.Name, new { htmlAttributes = new { @readonly = "", disabled = "" } })

The located assembly's manifest definition does not match the assembly reference

In your AssemblyVersion in AssemblyInfo.cs file, use a fixed version number instead of specifying *. The * will change the version number on each compilation. That was the issue for this exception in my case.

var.replace is not a function

You should probably do some validations before you actually execute your function :

function trim(str) {
    if(typeof str !== 'string') {
        throw new Error('only string parameter supported!');
    }

    return str.replace(/^\s+|\s+$/g,'');
}

How can I represent an 'Enum' in Python?

def enum( *names ):

    '''
    Makes enum.
    Usage:
        E = enum( 'YOUR', 'KEYS', 'HERE' )
        print( E.HERE )
    '''

    class Enum():
        pass
    for index, name in enumerate( names ):
        setattr( Enum, name, index )
    return Enum

simple vba code gives me run time error 91 object variable or with block not set

Also you are trying to set value2 using Set keyword, which is not required. You can directly use rng.value2 = 1

below test code for ref.

Sub test()
    Dim rng As Range
    Set rng = Range("A1")
    rng.Value2 = 1
End Sub

How to Insert Double or Single Quotes

Why not just use a custom format for the cell you need to quote?

If you set a custom format to the cell column, all values will take on that format.

For numbers....like a zip code....it would be this '#' For string text, it would be this '@'

You save the file as csv format, and it will have all the quotes wrapped around the cell data as needed.

Webpack - webpack-dev-server: command not found

The script webpack-dev-server is already installed inside ./node_modules directory. You can either install it again globally by

sudo npm install -g webpack-dev-server

or run it like this

./node_modules/webpack-dev-server/bin/webpack-dev-server.js -d --config webpack.dev.config.js --content-base public/ --progress --colors

. means look it in current directory.

How can I get the current user's username in Bash?

Use the standard Unix/Linux/BSD/MacOS command logname to retrieve the logged in user. This ignores the environment as well as sudo, as these are unreliable reporters. It will always print the logged in user's name and then exit. This command has been around since about 1981.

My-Mac:~ devin$ logname
devin
My-Mac:~ devin$ sudo logname
Password:
devin
My-Mac:~ devin$ sudo su -
My-Mac:~ root# logname
devin
My-Mac:~ root# echo $USER
root

Any way to select without causing locking in MySQL?

Use

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED.

Version 5.0 Docs are here.

Version 5.1 Docs are here.

How to install pip3 on Windows?

There is another way to install the pip3: just reinstall 3.6.

Set object property using reflection

You can also do:

Type type = target.GetType();

PropertyInfo prop = type.GetProperty("propertyName");

prop.SetValue (target, propertyValue, null);

where target is the object that will have its property set.

php codeigniter count rows

Try This :) I created my on model of count all results

in library_model

function count_all_results($column_name = array(),$where=array(), $table_name = array())
{
        $this->db->select($column_name);
        // If Where is not NULL
        if(!empty($where) && count($where) > 0 )
        {
            $this->db->where($where);
        }
        // Return Count Column
        return $this->db->count_all_results($table_name[0]);//table_name array sub 0
}

Your Controller will look like this

public function my_method()
{
  $data = array(
     $countall = $this->model->your_method_model()
  );
   $this->load->view('page',$data);
}

Then Simple Call The Library Model In Your Model

function your_method_model()
{
        return $this->library_model->count_all_results(
               ['id'],
               ['where],
               ['table name']
           );
}

Run two async tasks in parallel and collect results in .NET 4.5

While your Sleep method is async, Thread.Sleep is not. The whole idea of async is to reuse a single thread, not to start multiple threads. Because you've blocked using a synchronous call to Thread.Sleep, it's not going to work.

I'm assuming that Thread.Sleep is a simplification of what you actually want to do. Can your actual implementation be coded as async methods?

If you do need to run multiple synchronous blocking calls, look elsewhere I think!

How do you serialize a model instance in Django?

Use list, it will solve problem

Step1:

 result=YOUR_MODELE_NAME.objects.values('PROP1','PROP2').all();

Step2:

 result=list(result)  #after getting data from model convert result to list

Step3:

 return HttpResponse(json.dumps(result), content_type = "application/json")

check if command was successful in a batch file

Goodness I had a hard time finding the answer to this... Here it is:

cd thisDoesntExist
if %errorlevel% == 0 (
  echo Oh, I guess it does
  echo Huh.
)

How do I calculate the normal vector of a line segment?

If we define dx = x2 - x1 and dy = y2 - y1, then the normals are (-dy, dx) and (dy, -dx).

Note that no division is required, and so you're not risking dividing by zero.

How can I read command line parameters from an R script?

Try library(getopt) ... if you want things to be nicer. For example:

spec <- matrix(c(
        'in'     , 'i', 1, "character", "file from fastq-stats -x (required)",
        'gc'     , 'g', 1, "character", "input gc content file (optional)",
        'out'    , 'o', 1, "character", "output filename (optional)",
        'help'   , 'h', 0, "logical",   "this help"
),ncol=5,byrow=T)

opt = getopt(spec);

if (!is.null(opt$help) || is.null(opt$in)) {
    cat(paste(getopt(spec, usage=T),"\n"));
    q();
}

What is Inversion of Control?

Let to say that we make some meeting in some hotel.

Many people, many carafes of water, many plastic cups.

When somebody want to drink, she fill cup, drink and throw cup on the floor.

After hour or something we have a floor covered of plastic cups and water.

Let invert control.

The same meeting in the same place, but instead of plastic cups we have a waiter with one glass cup (Singleton)

and she all of time offers to guests drinking.

When somebody want to drink, she get from waiter glass, drink and return it back to waiter.

Leaving aside the question of the hygienic, last form of drinking process control is much more effective and economic.

And this is exactly what the Spring (another IoC container, for example: Guice) does. Instead of let to application create what it need using new keyword (taking plastic cup), Spring IoC container all of time offer to application the same instance (singleton) of needed object(glass of water).

Think about yourself as organizer of such meeting. You need the way to message to hotel administration that

meeting members will need glass of water but not piece of cake.

Example:-

public class MeetingMember {

    private GlassOfWater glassOfWater;

    ...

    public void setGlassOfWater(GlassOfWater glassOfWater){
        this.glassOfWater = glassOfWater;
    }
    //your glassOfWater object initialized and ready to use...
    //spring IoC  called setGlassOfWater method itself in order to
    //offer to meetingMember glassOfWater instance

}

Useful links:-

How can I de-install a Perl module installed via `cpan`?

  1. Install App::cpanminus from CPAN (use: cpan App::cpanminus for this).
  2. Type cpanm --uninstall Module::Name (note the "m") to uninstall the module with cpanminus.

This should work.

Is there a Subversion command to reset the working copy?

To remove untracked files

I was able to list all untracked files reported by svn st in bash by doing:

echo $(svn st | grep -P "^\?" | cut -c 9-)

If you are feeling lucky, you could replace echo with rm to delete untracked files. Or copy the files you want to delete by hand, if you are feeling a less lucky.


(I used @abe-voelker 's answer to revert the remaining files: https://stackoverflow.com/a/6204601/1695680)

Batch script to find and replace a string in text file without creating an extra output file for storing the modified file

@echo off 
    setlocal enableextensions disabledelayedexpansion

    set "search=%1"
    set "replace=%2"

    set "textFile=Input.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%search%=%replace%!
        endlocal
    )

for /f will read all the data (generated by the type comamnd) before starting to process it. In the subprocess started to execute the type, we include a redirection overwritting the file (so it is emptied). Once the do clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.

How to get current screen width in CSS?

Based on your requirement i think you are wanted to put dynamic fields in CSS file, however that is not possible as CSS is a static language. However you can simulate the behaviour by using Angular.

Please refer to the below example. I'm here showing only one component.

login.component.html

import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

    @Component({
      selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.css']
    })
    export class LoginComponent implements OnInit {

      cssProperty:any;
      constructor(private sanitizer: DomSanitizer) { 
        console.log(window.innerWidth);
        console.log(window.innerHeight);
        this.cssProperty = 'position:fixed;top:' + Math.floor(window.innerHeight/3.5) + 'px;left:' + Math.floor(window.innerWidth/3) + 'px;';
        this.cssProperty = this.sanitizer.bypassSecurityTrustStyle(this.cssProperty);
      }

    ngOnInit() {

      }

    }

login.component.ts

<div class="home">
    <div class="container" [style]="cssProperty">
        <div class="card">
            <div class="card-header">Login</div>
            <div class="card-body">Please login</div>
            <div class="card-footer">Login</div>
        </div>
    </div>
</div>

login.component.css

.card {
    max-width: 400px;
}
.card .card-body {
    min-height: 150px;
}
.home {
    background-color: rgba(171, 172, 173, 0.575);
}

How to set the env variable for PHP?

You May use set keyword for set the path

set path=%path%;c:/wamp/bin/php/php5.3.0

if all the path are set in path variables

If you want to see all path list. you can use

set %path%

you need to append your php path behind this path.

This is how you can set environment variable.

How to query all the GraphQL type fields without writing a long query?

Package graphql-type-json supports custom-scalars type JSON. Use it can show all the field of your json objects. Here is the link of the example in ApolloGraphql Server. https://www.apollographql.com/docs/apollo-server/schema/scalars-enums/#custom-scalars

WebView and HTML5 <video>

This approach works well very till 2.3 And by adding hardwareaccelerated=true it even works from 3.0 to ICS One problem i am facing currently is upon second launch of media player application is getting crashed because i have not stopped playback and released Media player. As VideoSurfaceView object, which we get in onShowCustomView function from 3.0 OS, are specific to browser and not a VideoView object as in, till 2.3 OS How can i access it and stopPlayback and release resources?

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.

Finding non-numeric rows in dataframe in pandas?

I'm thinking something like, just give an idea, to convert the column to string, and work with string is easier. however this does not work with strings containing numbers, like bad123. and ~ is taking the complement of selection.

df['a'] = df['a'].astype(str)
df[~df['a'].str.contains('0|1|2|3|4|5|6|7|8|9')]
df['a'] = df['a'].astype(object)

and using '|'.join([str(i) for i in range(10)]) to generate '0|1|...|8|9'

or using np.isreal() function, just like the most voted answer

df[~df['a'].apply(lambda x: np.isreal(x))]

Value cannot be null. Parameter name: source

This exception will be returned if you attempt to count values in a null collection.

For example the below works when Errors is not null, however if Errors is null then the Value cannot be null. Parameter name: source exception occurs.

if (graphQLResponse.Errors.Count() > 0)

This exception can be avoided by checking for null instead.

if (graphQLResponse.Errors != null)

Disable / Check for Mock Location (prevent gps spoofing)

It seems that the only way to do this is to prevent Location Spoofing preventing MockLocations. The down side is there are some users who use Bluetooth GPS devices to get a better signal, they won't be able to use the app as they are required to use the mock locations.

To do this, I did the following :

// returns true if mock location enabled, false if not enabled.
if (Settings.Secure.getString(getContentResolver(),
       Settings.Secure.ALLOW_MOCK_LOCATION).equals("0")) 
       return false; 
       else return true;

Remove Primary Key in MySQL

Find the table in SQL manager right click it and select design, then right click the little key icon and select remove primary key.

Define make variable at rule execution time

In your example, the TMP variable is set (and the temporary directory created) whenever the rules for out.tar are evaluated. In order to create the directory only when out.tar is actually fired, you need to move the directory creation down into the steps:

out.tar : 
    $(eval TMP := $(shell mktemp -d))
    @echo hi $(TMP)/hi.txt
    tar -C $(TMP) cf $@ .
    rm -rf $(TMP)

The eval function evaluates a string as if it had been typed into the makefile manually. In this case, it sets the TMP variable to the result of the shell function call.

edit (in response to comments):

To create a unique variable, you could do the following:

out.tar : 
    $(eval $@_TMP := $(shell mktemp -d))
    @echo hi $($@_TMP)/hi.txt
    tar -C $($@_TMP) cf $@ .
    rm -rf $($@_TMP)

This would prepend the name of the target (out.tar, in this case) to the variable, producing a variable with the name out.tar_TMP. Hopefully, that is enough to prevent conflicts.

JavaScript: Object Rename Key

You can try lodash _.mapKeys.

_x000D_
_x000D_
var user = {_x000D_
  name: "Andrew",_x000D_
  id: 25,_x000D_
  reported: false_x000D_
};_x000D_
_x000D_
var renamed = _.mapKeys(user, function(value, key) {_x000D_
  return key + "_" + user.id;_x000D_
});_x000D_
_x000D_
console.log(renamed);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
_x000D_
_x000D_
_x000D_

Saving images in Python at a very high quality

In case you are working with seaborn plots, instead of Matplotlib, you can save a .png image like this:

Let's suppose you have a matrix object (either Pandas or NumPy), and you want to take a heatmap:

import seaborn as sb

image = sb.heatmap(matrix)   # This gets you the heatmap
image.figure.savefig("C:/Your/Path/ ... /your_image.png")   # This saves it

This code is compatible with the latest version of Seaborn. Other code around Stack Overflow worked only for previous versions.

Another way I like is this. I set the size of the next image as follows:

plt.subplots(figsize=(15,15))

And then later I plot the output in the console, from which I can copy-paste it where I want. (Since Seaborn is built on top of Matplotlib, there will not be any problem.)

How should strace be used?

Strace can be used as a debugging tool, or as a primitive profiler.

As a debugger, you can see how given system calls were called, executed and what they return. This is very important, as it allows you to see not only that a program failed, but WHY a program failed. Usually it's just a result of lousy coding not catching all the possible outcomes of a program. Other times it's just hardcoded paths to files. Without strace you get to guess what went wrong where and how. With strace you get a breakdown of a syscall, usually just looking at a return value tells you a lot.

Profiling is another use. You can use it to time execution of each syscalls individually, or as an aggregate. While this might not be enough to fix your problems, it will at least greatly narrow down the list of potential suspects. If you see a lot of fopen/close pairs on a single file, you probably unnecessairly open and close files every execution of a loop, instead of opening and closing it outside of a loop.

Ltrace is strace's close cousin, also very useful. You must learn to differenciate where your bottleneck is. If a total execution is 8 seconds, and you spend only 0.05secs on system calls, then stracing the program is not going to do you much good, the problem is in your code, which is usually a logic problem, or the program actually needs to take that long to run.

The biggest problem with strace/ltrace is reading their output. If you don't know how the calls are made, or at least the names of syscalls/functions, it's going to be difficult to decipher the meaning. Knowing what the functions return can also be very beneficial, especially for different error codes. While it's a pain to decipher, they sometimes really return a pearl of knowledge; once I saw a situation where I ran out of inodes, but not out of free space, thus all the usual utilities didn't give me any warning, I just couldn't make a new file. Reading the error code from strace's output pointed me in the right direction.

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

I agree with the above comments about overriding toString() on your own classes (and about automating that process as much as possible).

For classes you didn't define, you could write a ToStringHelper class with an overloaded method for each library class you want to have handled to your own tastes:

public class ToStringHelper {
    //... instance configuration here (e.g. punctuation, etc.)
    public toString(List m) {
        // presentation of List content to your liking
    }
    public toString(Map m) {
        // presentation of Map content to your liking
    }
    public toString(Set m) {
        // presentation of Set content to your liking
    }
    //... etc.
}

EDIT: Responding to the comment by xukxpvfzflbbld, here's a possible implementation for the cases mentioned previously.

package com.so.demos;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class ToStringHelper {

    private String separator;
    private String arrow;

    public ToStringHelper(String separator, String arrow) {
        this.separator = separator;
        this.arrow = arrow;
    }

   public String toString(List<?> l) {
        StringBuilder sb = new StringBuilder("(");
        String sep = "";
        for (Object object : l) {
            sb.append(sep).append(object.toString());
            sep = separator;
        }
        return sb.append(")").toString();
    }

    public String toString(Map<?,?> m) {
        StringBuilder sb = new StringBuilder("[");
        String sep = "";
        for (Object object : m.keySet()) {
            sb.append(sep)
              .append(object.toString())
              .append(arrow)
              .append(m.get(object).toString());
            sep = separator;
        }
        return sb.append("]").toString();
    }

    public String toString(Set<?> s) {
        StringBuilder sb = new StringBuilder("{");
        String sep = "";
        for (Object object : s) {
            sb.append(sep).append(object.toString());
            sep = separator;
        }
        return sb.append("}").toString();
    }

}

This isn't a full-blown implementation, but just a starter.

Can I edit an iPad's host file?

I would imagine you could do it by setting up a transparent proxy, using something like charles and re-direct traffic that way

Error QApplication: no such file or directory

you have to add QT +=widgets in the .pro file before the first execution, if you execute before adding this line its not gonna working, so yo need to start file's creation from the beginning.

What does "dereferencing" a pointer mean?

Dereferencing a pointer means getting the value that is stored in the memory location pointed by the pointer. The operator * is used to do this, and is called the dereferencing operator.

int a = 10;
int* ptr = &a;

printf("%d", *ptr); // With *ptr I'm dereferencing the pointer. 
                    // Which means, I am asking the value pointed at by the pointer.
                    // ptr is pointing to the location in memory of the variable a.
                    // In a's location, we have 10. So, dereferencing gives this value.

// Since we have indirect control over a's location, we can modify its content using the pointer. This is an indirect way to access a.

 *ptr = 20;         // Now a's content is no longer 10, and has been modified to 20.

Nested Recycler view height doesn't wrap its content

Here I have found a solution: https://code.google.com/p/android/issues/detail?id=74772

It is in no way my solution. I have just copied it from there, but I hope it will help someone as much as it helped me when implementing horizontal RecyclerView and wrap_content height (should work also for vertical one and wrap_content width)

The solution is to extend the LayoutManager and override its onMeasure method as @yigit suggested.

Here is the code in case the link dies:

public static class MyLinearLayoutManager extends LinearLayoutManager {

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

    private int[] mMeasuredDimension = new int[2];

    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
                          int widthSpec, int heightSpec) {
        final int widthMode = View.MeasureSpec.getMode(widthSpec);
        final int heightMode = View.MeasureSpec.getMode(heightSpec);
        final int widthSize = View.MeasureSpec.getSize(widthSpec);
        final int heightSize = View.MeasureSpec.getSize(heightSpec);

        measureScrapChild(recycler, 0,
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                mMeasuredDimension);

        int width = mMeasuredDimension[0];
        int height = mMeasuredDimension[1];

        switch (widthMode) {
            case View.MeasureSpec.EXACTLY:
            case View.MeasureSpec.AT_MOST:
                width = widthSize;
                break;
            case View.MeasureSpec.UNSPECIFIED:
        }

        switch (heightMode) {
            case View.MeasureSpec.EXACTLY:
            case View.MeasureSpec.AT_MOST:
                height = heightSize;
                break;
            case View.MeasureSpec.UNSPECIFIED:
        }

        setMeasuredDimension(width, height);
    }

    private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                                   int heightSpec, int[] measuredDimension) {
        View view = recycler.getViewForPosition(position);
        if (view != null) {
            RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
            int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                    getPaddingLeft() + getPaddingRight(), p.width);
            int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                    getPaddingTop() + getPaddingBottom(), p.height);
            view.measure(childWidthSpec, childHeightSpec);
            measuredDimension[0] = view.getMeasuredWidth();
            measuredDimension[1] = view.getMeasuredHeight();
            recycler.recycleView(view);
        }
    }
}

How to convert a Collection to List?

Java 10 introduced List#copyOf which returns unmodifiable List while preserving the order:

List<Integer> list = List.copyOf(coll);

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

This is not an error message but a warning. It is very clearly explained in their website as :

This warning, i.e. not an error, message is reported when no SLF4J providers could be found on the class path. Placing one (and only one) of slf4j-nop.jar slf4j-simple.jar, slf4j-log4j12.jar, slf4j-jdk14.jar or logback-classic.jar on the class path should solve the problem. Note that these providers must target slf4j-api 1.8 or later.

In the absence of a provider, SLF4J will default to a no-operation (NOP) logger provider.

https://www.slf4j.org/codes.html#StaticLoggerBinder

mvn clean install vs. deploy vs. release

The clean, install and deploy phases are valid lifecycle phases and invoking them will trigger all the phases preceding them, and the goals bound to these phases.

mvn clean install

This command invokes the clean phase and then the install phase sequentially:

  • clean: removes files generated at build-time in a project's directory (target by default)
  • install: installs the package into the local repository, for use as a dependency in other projects locally.

mvn deploy

This command invokes the deploy phase:

  • deploy: copies the final package to the remote repository for sharing with other developers and projects.

mvn release

This is not a valid phase nor a goal so this won't do anything. But if refers to the Maven Release Plugin that is used to automate release management. Releasing a project is done in two steps: prepare and perform. As documented:

Preparing a release goes through the following release phases:

  • Check that there are no uncommitted changes in the sources
  • Check that there are no SNAPSHOT dependencies
  • Change the version in the POMs from x-SNAPSHOT to a new version (you will be prompted for the versions to use)
  • Transform the SCM information in the POM to include the final destination of the tag
  • Run the project tests against the modified POMs to confirm everything is in working order
  • Commit the modified POMs
  • Tag the code in the SCM with a version name (this will be prompted for)
  • Bump the version in the POMs to a new value y-SNAPSHOT (these values will also be prompted for)
  • Commit the modified POMs

And then:

Performing a release runs the following release phases:

  • Checkout from an SCM URL with optional tag
  • Run the predefined Maven goals to release the project (by default, deploy site-deploy)

See also

How do I get the coordinates of a mouse click on a canvas element?

Modern browser's now handle this for you. Chrome, IE9, and Firefox support the offsetX/Y like this, passing in the event from the click handler.

function getRelativeCoords(event) {
    return { x: event.offsetX, y: event.offsetY };
}

Most modern browsers also support layerX/Y, however Chrome and IE use layerX/Y for the absolute offset of the click on the page including margin, padding, etc. In Firefox, layerX/Y and offsetX/Y are equivalent, but offset didn't previously exist. So, for compatibility with slightly older browsers, you can use:

function getRelativeCoords(event) {
    return { x: event.offsetX || event.layerX, y: event.offsetY || event.layerY };
}

Is it not possible to stringify an Error using JSON.stringify?

JSON.stringify(err, Object.getOwnPropertyNames(err))

seems to work

[from a comment by /u/ub3rgeek on /r/javascript] and felixfbecker's comment below

Angular2 handling http response

Update alpha 47

As of alpha 47 the below answer (for alpha46 and below) is not longer required. Now the Http module handles automatically the errores returned. So now is as easy as follows

http
  .get('Some Url')
  .map(res => res.json())
  .subscribe(
    (data) => this.data = data,
    (err) => this.error = err); // Reach here if fails

Alpha 46 and below

You can handle the response in the map(...), before the subscribe.

http
  .get('Some Url')
  .map(res => {
    // If request fails, throw an Error that will be caught
    if(res.status < 200 || res.status >= 300) {
      throw new Error('This request has failed ' + res.status);
    } 
    // If everything went fine, return the response
    else {
      return res.json();
    }
  })
  .subscribe(
    (data) => this.data = data, // Reach here if res.status >= 200 && <= 299
    (err) => this.error = err); // Reach here if fails

Here's a plnkr with a simple example.

Note that in the next release this won't be necessary because all status codes below 200 and above 299 will throw an error automatically, so you won't have to check them by yourself. Check this commit for more info.

How do I use InputFilter to limit characters in an EditText in Android?

to prevent words in edittext. create a class that u could use anytime.

public class Wordfilter implements InputFilter
{
    @Override
    public CharSequence filter(CharSequence source, int start, int end,Spanned dest, int dstart, int dend) {
        // TODO Auto-generated method stub
        boolean append = false;
        String text = source.toString().substring(start, end);
        StringBuilder str = new StringBuilder(dest.toString());
        if(dstart == str.length())
        {
            append = true;
            str.append(text);
        }
        else
            str.replace(dstart, dend, text);
        if(str.toString().contains("aaaaaaaaaaaa/*the word here*/aaaaaaaa"))
        {
            if(append==true)
                return "";
            else
                return dest.subSequence(dstart, dend);
        }
        return null;
    }
}

What is the difference between typeof and instanceof and when should one be used vs. the other?

Coming from a strict OO upbringing I'd go for

callback instanceof Function

Strings are prone to either my awful spelling or other typos. Plus I feel it reads better.

What does the "More Columns than Column Names" error mean?

It uses commas as separators. So you can either set sep="," or just use read.csv:

x <- read.csv(file="http://www.irs.gov/file_source/pub/irs-soi/countyinflow1011.csv")
dim(x)
## [1] 113593      9

The error is caused by spaces in some of the values, and unmatched quotes. There are no spaces in the header, so read.table thinks that there is one column. Then it thinks it sees multiple columns in some of the rows. For example, the first two lines (header and first row):

State_Code_Dest,County_Code_Dest,State_Code_Origin,County_Code_Origin,State_Abbrv,County_Name,Return_Num,Exmpt_Num,Aggr_AGI
00,000,96,000,US,Total Mig - US & For,6973489,12948316,303495582

And unmatched quotes, for example on line 1336 (row 1335) which will confuse read.table with the default quote argument (but not read.csv):

01,089,24,033,MD,Prince George's County,13,30,1040

How to get relative path of a file in visual studio?

I think using this will be the easiest

new Uri("pack://application:,,/FolderIcon/" + youImageICO);

or this code will work on any machine that if your folder is in your root project if you want to change it... just change this section @"..\"

public static string bingPathToAppDir(string localPath)
{
    string currentDir = Environment.CurrentDirectory;
    DirectoryInfo directory = new DirectoryInfo(
        Path.GetFullPath(Path.Combine(currentDir, @"..\..\" + localPath)));
    return directory.ToString();
}

jQuery textbox change event

$('#input').on("input",function () {alert('changed');});

works for me.

Check if one list contains element from the other

faster way will require additional space .

For example:

  1. put all items in one list into a HashSet ( you have to implement the hash function by yourself to use object.getAttributeSame() )

  2. Go through the other list and check if any item is in the HashSet.

In this way each object is visited at most once. and HashSet is fast enough to check or insert any object in O(1).

How to get the first item from an associative PHP array?

Fake loop that breaks on the first iteration:

$key = $value = NULL;
foreach ($array as $key => $value) {
    break;
}

echo "$key = $value\n";

Or use each() (warning: deprecated as of PHP 7.2.0):

reset($array);
list($key, $value) = each($array);

echo "$key = $value\n";

Recommended way of making React component/div draggable

I would like to add a 3rd Scenario

The moving position is not saved in any way. Think of it as a mouse movement - your cursor is not a React-component, right?

All you do, is to add a prop like "draggable" to your component and a stream of the dragging events that will manipulate the dom.

setXandY: function(event) {
    // DOM Manipulation of x and y on your node
},

componentDidMount: function() {
    if(this.props.draggable) {
        var node = this.getDOMNode();
        dragStream(node).onValue(this.setXandY);  //baconjs stream
    };
},

In this case, a DOM manipulation is an elegant thing (I never thought I'd say this)

Multiline TextBox multiple newline

When page IsPostback, the following code work correctly. But when page first loading, there is not multiple newline in the textarea. Bug

textBox1.Text = "Line1\r\n\r\n\r\nLine2";

Clearing <input type='file' /> using jQuery

What? In your validation function, just put

document.onlyform.upload.value="";

Assuming upload is the name:

<input type="file" name="upload" id="csv_doc"/>

I'm using JSP, not sure if that makes a difference...

Works for me, and I think it's way easier.

How to create multiple page app using react

Preface

This answer uses the dynamic routing approach embraced in react-router v4+. Other answers may reference the previously-used "static routing" approach that has been abandoned by react-router.

Solution

react-router is a great solution. You create your pages as Components and the router swaps out the pages according to the current URL. In other words, it replaces your original page with your new page dynamically instead of asking the server for a new page.

For web apps I recommend you read these two things first:

Summary of the general approach:

1 - Add react-router-dom to your project:

Yarn

yarn add react-router-dom

or NPM

npm install react-router-dom

2 - Update your index.js file to something like:

import { BrowserRouter } from 'react-router-dom';

ReactDOM.render((
  <BrowserRouter>
    <App /> {/* The various pages will be displayed by the `Main` component. */}
  </BrowserRouter>
  ), document.getElementById('root')
);

3 - Create a Main component that will show your pages according to the current URL:

import React from 'react';
import { Switch, Route } from 'react-router-dom';

import Home from '../pages/Home';
import Signup from '../pages/Signup';

const Main = () => {
  return (
    <Switch> {/* The Switch decides which component to show based on the current URL.*/}
      <Route exact path='/' component={Home}></Route>
      <Route exact path='/signup' component={Signup}></Route>
    </Switch>
  );
}

export default Main;

4 - Add the Main component inside of the App.js file:

function App() {
  return (
    <div className="App">
      <Navbar />
      <Main />
    </div>
  );
}

5 - Add Links to your pages.

(You must use Link from react-router-dom instead of just a plain old <a> in order for the router to work properly.)

import { Link } from "react-router-dom";
...
<Link to="/signup">
  <button variant="outlined">
    Sign up
  </button>
</Link>

How to check if memcache or memcached is installed for PHP?

I know this is an old thread, but there's another way that I've found useful for any extension.

Run

php -m | grep <module_name>

In this particular case:

php -m | grep memcache

If you want to list all PHP modules then:

php -m

Depending on your system you'd get an output similar to this:

[PHP Modules]
apc
bcmath
bz2
... lots of other modules ...
mbstring
memcache
 ... and still more modules ...
zip
zlib

[Zend Modules]

You can see that memcache is in this list.

The shortest possible output from git log containing author and date

tig is a possible alternative to using the git log command, available on the major open source *nix distributions.

On debian or ubuntu try installing and running as follows:

$ sudo apt-get install tig

For mac users, brew to the rescue :

$ brew install tig

(tig gets installed)

$ tig

(log is displayed in pager as follows, with current commit's hash displayed at the bottom)

2010-03-17 01:07 ndesigner      changes to sponsors list
2010-03-17 00:19 rcoder         Raise 404 when an invalid year is specified.
2010-03-17 00:06 rcoder         Sponsors page now shows sponsors' level.
-------------------------- skip some lines ---------------------------------
[main] 531f35e925f53adeb2146dcfc9c6a6ef24e93619 - commit 1 of 32 (100%)

Since markdown doesn't support text coloring, imagine: column 1: blue; column 2: green; column 3: default text color. Last line, highlighted. Hit Q or q to exit.


tig justifies the columns without ragged edges, which an ascii tab (%x09) doesn't guarantee.

For a short date format hit capital D (note: lowercase d opens a diff view.) Configure it permanently by adding show-date = short to ~/.tigrc; or in a [tig] section in .git/configure or ~/.gitconfig.

To see an entire change:

  • hit Enter. A sub pane will open in the lower half of the window.
  • use k, j keys to scroll the change in the sub pane.
  • at the same time, use the up, down keys to move from commit to commit.

Since tig is separate from git and apparently *nix specific, it probably requires cygwin to install on windows. But for fedora I believe the install commands are $ su, (enter root password), # yum install tig. For freebsd try % su, (enter root password), # pkg_add -r tig.


By the way, tig is good for a lot more than a quick view of the log: Screenshots & Manual

Get the current date in java.sql.Date format

In order to get "the current date" (as in today's date), you can use LocalDate.now() and pass that into the java.sql.Date method valueOf(LocalDate).

import java.sql.Date;
...
Date date = Date.valueOf(LocalDate.now());

Most efficient way to map function over numpy array

I've tested all suggested methods plus np.array(map(f, x)) with perfplot (a small project of mine).

Message #1: If you can use numpy's native functions, do that.

If the function you're trying to vectorize already is vectorized (like the x**2 example in the original post), using that is much faster than anything else (note the log scale):

enter image description here

If you actually need vectorization, it doesn't really matter much which variant you use.

enter image description here


Code to reproduce the plots:

import numpy as np
import perfplot
import math


def f(x):
    # return math.sqrt(x)
    return np.sqrt(x)


vf = np.vectorize(f)


def array_for(x):
    return np.array([f(xi) for xi in x])


def array_map(x):
    return np.array(list(map(f, x)))


def fromiter(x):
    return np.fromiter((f(xi) for xi in x), x.dtype)


def vectorize(x):
    return np.vectorize(f)(x)


def vectorize_without_init(x):
    return vf(x)


perfplot.show(
    setup=np.random.rand,
    n_range=[2 ** k for k in range(20)],
    kernels=[f, array_for, array_map, fromiter, vectorize, vectorize_without_init],
    xlabel="len(x)",
)

What does %>% function mean in R?

%>% is similar to pipe in Unix. For example, in

a <- combined_data_set %>% group_by(Outlet_Identifier) %>% tally()

the output of combined_data_set will go into group_by and its output will go into tally, then the final output is assigned to a.

This gives you handy and easy way to use functions in series without creating variables and storing intermediate values.

WARNING: sanitizing unsafe style value url

You have to wrap the entire url statement in the bypassSecurityTrustStyle:

<div class="header" *ngIf="image" [style.background-image]="image"></div>

And have

this.image = this.sanitization.bypassSecurityTrustStyle(`url(${element.image})`);

Otherwise it is not seen as a valid style property

How to use an existing database with an Android application

If you already have a database, keep it in your asset folder and copy it in your application. For more detail, see Android database basics.

Getting "Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?" when installing lxml through pip

Install lxml from http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml for your python version. It's a precompiled WHL with required modules/dependencies.

The site lists several packages, when e.g. using Win32 Python 3.9, use lxml-4.5.2-cp39-cp39-win32.whl.

Download the file, and then install with:

pip install C:\path\to\downloaded\file\lxml-4.5.2-cp39-cp39-win32.whl

how to re-format datetime string in php?

try this

$datetime = "20130409163705"; 
print_r(date_parse_from_format("Y-m-d H-i-s", $datetime));

the output:

[year] => 2013
[month] => 4
[day] => 9
[hour] => 16
[minute] => 37
[second] => 5

PHP Include for HTML?

Here is the step by step process to include php code in html file ( Tested )

If PHP is working there is only one step left to use PHP scripts in files with *.html or *.htm extensions as well. The magic word is ".htaccess". Please see the Wikipedia definition of .htaccess to learn more about it. According to Wikipedia it is "a directory-level configuration file that allows for decentralized management of web server configuration."

You can probably use such a .htaccess configuration file for your purpose. In our case you want the webserver to parse HTML files like PHP files.

First, create a blank text file and name it ".htaccess". You might ask yourself why the file name starts with a dot. On Unix-like systems this means it is a dot-file is a hidden file. (Note: If your operating system does not allow file names starting with a dot just name the file "xyz.htaccess" temporarily. As soon as you have uploaded it to your webserver in a later step you can rename the file online to ".htaccess") Next, open the file with a simple text editor like the "Editor" in MS Windows. Paste the following line into the file: AddType application/x-httpd-php .html .htm If this does not work, please remove the line above from your file and paste this alternative line into it, for PHP5: AddType application/x-httpd-php5 .html .htm Now upload the .htaccess file to the root directory of your webserver. Make sure that the name of the file is ".htaccess". Your webserver should now parse *.htm and *.html files like PHP files.

You can try if it works by creating a HTML-File like the following. Name it "php-in-html-test.htm", paste the following code into it and upload it to the root directory of your webserver:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
     <HTML>
 <HEAD>
 <TITLE>Use PHP in HTML files</TITLE>
 </HEAD>

   <BODY>
    <h1>
    <?php echo "It works!"; ?>
    </h1>
  </BODY>
 </HTML>

Try to open the file in your browser by typing in: http://www.your-domain.com/php-in-html-test.htm (once again, please replace your-domain.com by your own domain...) If your browser shows the phrase "It works!" everything works fine and you can use PHP in .*html and *.htm files from now on. However, if not, please try to use the alternative line in the .htaccess file as we showed above. If is still does not work please contact your hosting provider.

How can I check if an element exists in the visible DOM?

Check element exist or not

const elementExists = document.getElementById("find-me");
if(elementExists){
    console.log("have this element");
}else{
    console.log("this element doesn't exist");
}

C/C++ macro string concatenation

If they're both strings you can just do:

#define STR3 STR1 STR2

This then expands to:

#define STR3 "s" "1"

and in the C language, separating two strings with space as in "s" "1" is exactly equivalent to having a single string "s1".

Does HTML5 <video> playback support the .avi format?

There are three formats with a reasonable level of support: H.264 (MPEG-4 AVC), OGG Theora (VP3) and WebM (VP8). See the wiki linked by Sam for which browsers support which; you will typically need at least one of those plus Flash fallback.

Whilst most browsers won't touch AVI, there are some browser builds that expose all the multimedia capabilities of the underlying OS to <video>. These browser will indeed be able to play AVI, as long as they have matching codecs installed (AVI can contain about a million different video and audio formats). In particular Safari on OS X with QuickTime, or Konqi with GStreamer.

Personally I think this is an absolutely disastrous idea, as it exposes a very large codec codebase to the net, a codebase that was mostly not written to be resistant to network attacks. One of the worst drawbacks of media player plugins was the huge number of security holes they made available to every web page exploit. Let's not make this mistake again.

Provide schema while reading csv file as a dataframe

In pyspark 2.4 onwards, you can simply use header parameter to set the correct header:

data = spark.read.csv('data.csv', header=True)

Similarly, if using scala you can use header parameter as well.

Does IE9 support console.log, and is it a real function?

A simple solution to this console.log problem is to define the following at the beginning of your JS code:

if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function () { };

This works for me in all browsers. This creates a dummy function for console.log when the debugger is not active. When the debugger is active, the method console.log is defined and executes normally.

Difference between Convert.ToString() and .ToString()

Convert.ToString(strName) will handle null-able values and strName.Tostring() will not handle null value and throw an exception.

So It is better to use Convert.ToString() then .ToString();

How to use select/option/NgFor on an array of objects in Angular2

I'm no expert with DOM or Javascript/Typescript but I think that the DOM-Tags can't handle real javascript object somehow. But putting the whole object in as a string and parsing it back to an Object/JSON worked for me:

interface TestObject {
  name:string;
  value:number;
}

@Component({
  selector: 'app',
  template: `
      <h4>Select Object via 2-way binding</h4>

      <select [ngModel]="selectedObject | json" (ngModelChange)="updateSelectedValue($event)">
        <option *ngFor="#o of objArray" [value]="o | json" >{{o.name}}</option>
      </select>

      <h4>You selected:</h4> {{selectedObject }}
  `,
  directives: [FORM_DIRECTIVES]
})
export class App {
  objArray:TestObject[];
  selectedObject:TestObject;
  constructor(){
    this.objArray = [{name: 'foo', value: 1}, {name: 'bar', value: 1}];
    this.selectedObject = this.objArray[1];
  }
  updateSelectedValue(event:string): void{
    this.selectedObject = JSON.parse(event);
  }
}

setting system property

You need the path of the plugins directory of your local GATE install. So if Gate is installed in "/home/user/GATE_Developer_8.1", the code looks like this:

System.setProperty("gate.home", "/home/user/GATE_Developer_8.1/plugins");

You don't have to set gate.home from the command line. You can set it in your application, as long as you set it BEFORE you call Gate.init().

Installing jQuery?

There is no installation required. Just add jQuery to your application folder and give a reference to the js file.

<script type="text/javascript" src="jQuery.js"></script>

if jQuery is in the same folder of your referenced file.

Remove a symlink to a directory

use the "unlink" command and make sure not to have the / at the end

$ unlink mySymLink

unlink() deletes a name from the file system. If that name was the last link to a file and no processes have the file open the file is deleted and the space it was using is made available for reuse. If the name was the last link to a file but any processes still have the file open the file will remain in existence until the last file descriptor referring to it is closed.

I think this may be problematic if I'm reading it correctly.

If the name referred to a symbolic link the link is removed.

If the name referred to a socket, fifo or device the name for it is removed but processes which have the object open may continue to use it.

https://linux.die.net/man/2/unlink

How to center Font Awesome icons horizontally?

Add your own flavour of the font awesome style

[class^="icon-"], [class*=" icon-"] {
    display: inline-block;
    width: 100%;
}

which along with your

td i {
    text-align:center;
}

should center just the icons.

Border length smaller than div width?

I have case to have some bottom border between pictures in div container and the best one line code was - border-bottom-style: inset;

Styling input buttons for iPad and iPhone

Use the below css

_x000D_
_x000D_
input[type="submit"] {_x000D_
  font-size: 20px;_x000D_
  background: pink;_x000D_
  border: none;_x000D_
  padding: 10px 20px;_x000D_
}_x000D_
.flat-btn {_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
   appearance: none;_x000D_
   border-radius: 0;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
  margin: 25px 0 10px;_x000D_
  font-size: 20px;_x000D_
}
_x000D_
<h2>iOS Styled Button!</h2>_x000D_
<input type="submit" value="iOS Styled Button!" />_x000D_
_x000D_
<h2>No More Style! Button!</h2>_x000D_
<input class="flat-btn" type="submit" value="No More Style! Button!" />
_x000D_
_x000D_
_x000D_

New Line Issue when copying data from SQL Server 2012 to Excel

I found a workaround for the problem; instead of copy-pasting by hand, use Excel to connect to your database and import the complete table. Then remove the data you are not interested in.

Here are the steps (for Excel 2010)

  1. Go to menu Data > Get external data: From other sources > From SQL Server
  2. Type the sql server name (and credentials if you don't have Windows authentication on your server) and connect.
  3. Select the database and table that contains the data with the newlines and click 'Finish'.
  4. Select the destination worksheet and click 'Ok'.

Excel will now import the complete table with the newlines intact.

Adding Http Headers to HttpClient

Create a HttpRequestMessage, set the Method to GET, set your headers and then use SendAsync instead of GetAsync.

var client = new HttpClient();
var request = new HttpRequestMessage() {
    RequestUri = new Uri("http://www.someURI.com"),
    Method = HttpMethod.Get,
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
var task = client.SendAsync(request)
    .ContinueWith((taskwithmsg) =>
    {
        var response = taskwithmsg.Result;

        var jsonTask = response.Content.ReadAsAsync<JsonObject>();
        jsonTask.Wait();
        var jsonObject = jsonTask.Result;
    });
task.Wait();

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

This is a briefer variation of the accepted answer: the function below extracts the bits from-to inclusive by creating a bitmask. After applying an AND logic over the original number the result is shifted so the function returns just the extracted bits. Skipped index/integrity checks for clarity.

uint16_t extractInt(uint16_t orig16BitWord, unsigned from, unsigned to) 
{
  unsigned mask = ( (1<<(to-from+1))-1) << from;
  return (orig16BitWord & mask) >> from;
}

Extract first item of each sublist

Python includes a function called itemgetter to return the item at a specific index in a list:

from operator import itemgetter

Pass the itemgetter() function the index of the item you want to retrieve. To retrieve the first item, you would use itemgetter(0). The important thing to understand is that itemgetter(0) itself returns a function. If you pass a list to that function, you get the specific item:

itemgetter(0)([10, 20, 30]) # Returns 10

This is useful when you combine it with map(), which takes a function as its first argument, and a list (or any other iterable) as the second argument. It returns the result of calling the function on each object in the iterable:

my_list = [['a', 'b', 'c'], [1, 2, 3], ['x', 'y', 'z']]
list(map(itemgetter(0), my_list)) # Returns ['a', 1, 'x']

Note that map() returns a generator, so the result is passed to list() to get an actual list. In summary, your task could be done like this:

lst2.append(list(map(itemgetter(0), lst)))

This is an alternative method to using a list comprehension, and which method to choose highly depends on context, readability, and preference.

More info: https://docs.python.org/3/library/operator.html#operator.itemgetter

C++ Best way to get integer division and remainder

Sample code testing div() and combined division & mod. I compiled these with gcc -O3, I had to add the call to doNothing to stop the compiler from optimising everything out (output would be 0 for the division + mod solution).

Take it with a grain of salt:

#include <stdio.h>
#include <sys/time.h>
#include <stdlib.h>

extern doNothing(int,int); // Empty function in another compilation unit

int main() {
    int i;
    struct timeval timeval;
    struct timeval timeval2;
    div_t result;
    gettimeofday(&timeval,NULL);
    for (i = 0; i < 1000; ++i) {
        result = div(i,3);
        doNothing(result.quot,result.rem);
    }
    gettimeofday(&timeval2,NULL);
    printf("%d",timeval2.tv_usec - timeval.tv_usec);
}

Outputs: 150

#include <stdio.h>
#include <sys/time.h>
#include <stdlib.h>

extern doNothing(int,int); // Empty function in another compilation unit

int main() {
    int i;
    struct timeval timeval;
    struct timeval timeval2;
    int dividend;
    int rem;
    gettimeofday(&timeval,NULL);
    for (i = 0; i < 1000; ++i) {
        dividend = i / 3;
        rem = i % 3;
        doNothing(dividend,rem);
    }
    gettimeofday(&timeval2,NULL);
    printf("%d",timeval2.tv_usec - timeval.tv_usec);
}

Outputs: 25

Eliminating duplicate values based on only one column of the table

This is where the window function row_number() comes in handy:

SELECT s.siteName, s.siteIP, h.date
FROM sites s INNER JOIN
     (select h.*, row_number() over (partition by siteName order by date desc) as seqnum
      from history h
     ) h
    ON s.siteName = h.siteName and seqnum = 1
ORDER BY s.siteName, h.date

How to delete cookies on an ASP.NET website

You should never store password as a cookie. To delete a cookie, you really just need to modify and expire it. You can't really delete it, ie, remove it from the user's disk.

Here is a sample:

HttpCookie aCookie;
    string cookieName;
    int limit = Request.Cookies.Count;
    for (int i=0; i<limit; i++)
    {
        cookieName = Request.Cookies[i].Name;
        aCookie = new HttpCookie(cookieName);
        aCookie.Expires = DateTime.Now.AddDays(-1); // make it expire yesterday
        Response.Cookies.Add(aCookie); // overwrite it
    }

How to display image from URL on Android

Write the code using ASyncTask for http handling.

Bitmap b;
ImageView img;
......
try
    {
        URL url = new URL("http://10.119.120.10:80/img.jpg");
        InputStream is = new BufferedInputStream(url.openStream());
        b = BitmapFactory.decodeStream(is);
    } catch(Exception e){}
......
img.setImageBitmap(b);

Increasing nesting function calls limit

Personally I would suggest this is an error as opposed to a setting that needs adjusting. In my code it was because I had a class that had the same name as a library within one of my controllers and it seemed to trip it up.

Output errors and see where this is being triggered.

How to replace all double quotes to single quotes using jquery?

You can also use replaceAll(search, replaceWith) [MDN].

Then, make sure you have a string by wrapping one type of quotes by a different type:

 'a "b" c'.replaceAll('"', "'")
 // result: "a 'b' c"
    
 'a "b" c'.replaceAll(`"`, `'`)
 // result: "a 'b' c"

 // Using RegEx. You MUST use a global RegEx(Meaning it'll match all occurrences).
 'a "b" c'.replaceAll(/\"/g, "'")
 // result: "a 'b' c"

Important(!) if you choose regex:

when using a regexp you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".

Scikit-learn train_test_split with indices

The docs mention train_test_split is just a convenience function on top of shuffle split.

I just rearranged some of their code to make my own example. Note the actual solution is the middle block of code. The rest is imports, and setup for a runnable example.

from sklearn.model_selection import ShuffleSplit
from sklearn.utils import safe_indexing, indexable
from itertools import chain
import numpy as np
X = np.reshape(np.random.randn(20),(10,2)) # 10 training examples
y = np.random.randint(2, size=10) # 10 labels
seed = 1

cv = ShuffleSplit(random_state=seed, test_size=0.25)
arrays = indexable(X, y)
train, test = next(cv.split(X=X))
iterator = list(chain.from_iterable((
    safe_indexing(a, train),
    safe_indexing(a, test),
    train,
    test
    ) for a in arrays)
)
X_train, X_test, train_is, test_is, y_train, y_test, _, _  = iterator

print(X)
print(train_is)
print(X_train)

Now I have the actual indexes: train_is, test_is

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

To begin with (and unrelated), instantiating the Application class by yourself does not seem to be its intended use. From what one can read from its source, you are rather expected to use the static instance returned by getApplication().

Now let's get to the error Eclipse reports. I've ran into a similar issue recently: Access restriction: The method ... is not API (restriction on required project). I called the method in question as a method of an object which inherited that method from a super class. All I had to do was to add the package the super class was in to the packages imported by my plugin.

However, there is a lot of different causes for errors based on "restriction on required project/library". Similar to the problem described above, the type you are using might have dependencies to packages that are not exported by the library or might not be exported itself. In that case you can try to track down the missing packages and export them my yourself, as suggested here, or try Access Rules. Other possible scenarios include:

  • Eclipse wants to keep you from using available packages that are not part of the public Java API (solution 1, 2)
  • Dependencies are satisfied by multiple sources, versions are conflicting etc. (solution 1, 2, 3)
  • Eclipse is using a JRE where a JDK is necessary (which might be the case here, from what your errors say; solution) or JRE/JDK version in project build path is not the right one

This ended up as more like a medley of restriction-related issues than an actual answer. But since restriction on required projects is such a versatile error to be reported, the perfect recipe is probably still to be found.

How to convert .pem into .key?

I assume you want the DER encoded version of your PEM private key.

openssl rsa -outform der -in private.pem -out private.key

Is it possible to use JavaScript to change the meta-tags of the page?

If we don't have the meta tag at all, then we can use the following:

var _desc = 'Out description';
var meta = document.createElement('meta');
meta.setAttribute('name', 'description');
meta.setAttribute('content', _desc);
document.getElementsByTagName('head')[0].appendChild(meta);

Get element from within an iFrame

If iframe is not in the same domain such that you cannot get access to its internals from the parent but you can modify the source code of the iframe then you can modify the page displayed by the iframe to send messages to the parent window, which allows you to share information between the pages. Some sources:

How do I get a button to open another activity?

A. Make sure your other activity is declared in manifest:

<activity
    android:name="MyOtherActivity"
    android:label="@string/app_name">
</activity>

All activities must be declared in manifest, even if they do not have an intent filter assigned to them.


B. In your MainActivity do something like this:

Button btn = (Button)findViewById(R.id.open_activity_button);    

btn.setOnClickListener(new View.OnClickListener() {         
        @Override
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, MyOtherActivity.class));
        }
});

JQUERY ajax passing value from MVC View to Controller

$('#btnSaveComments').click(function () {
    var comments = $('#txtComments').val();
    var selectedId = $('#hdnSelectedId').val();

    $.ajax({
        url: '<%: Url.Action("SaveComments")%>',
        data: { 'id' : selectedId, 'comments' : comments },
        type: "post",
        cache: false,
        success: function (savingStatu`enter code here`s) {
            $("#hdnOrigComments").val($('#txtComments').val());
            $('#lblCommentsNotification').text(savingStatus);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $('#lblCommentsNotification').text("Error encountered while saving the comments.");
        }
    });
});

Open button in new window?

<input type="button" onclick="window.open(); return false;" value="click me" />

http://www.javascript-coder.com/window-popup/javascript-window-open.phtml

How to generate XML file dynamically using PHP?

Hope this code may help you out. Easy and simple solution

$dom = new DOMDocument();
$dom->encoding = 'utf-8';
$dom->xmlVersion = '1.0';
$dom->formatOutput = true;
$xml_file_name = './movies_list.xml'; //You can give your path to save file.
$root = $dom->createElement('Movies');
    $movie_node = $dom->createElement('movie');
    $attr_movie_id = new DOMAttr('movie_id', '5467');
    $movie_node->setAttributeNode($attr_movie_id);
        
        $child_node_title = $dom->createElement('Title', 'The Campaign');
        $movie_node->appendChild($child_node_title);
        
        $child_node_year = $dom->createElement('Year', 2012);
        $movie_node->appendChild($child_node_year);
        
        $child_node_genre = $dom->createElement('Genre', 'The Campaign');
        $movie_node->appendChild($child_node_genre);
        
        $child_node_ratings = $dom->createElement('Ratings', 6.2);
        $movie_node->appendChild($child_node_ratings);
    $root->appendChild($movie_node);
$dom->appendChild($root);
$dom->save($xml_file_name);

For more information visit this to get information in details: https://www.guru99.com/php-and-xml.html

Rename multiple columns by names

This is the function that you need: Then just pass the x in a rename(X) and it will rename all values that appear and if it isn't in there it won't error

rename <-function(x){
  oldNames = c("a","b","c")
  newNames = c("d","e","f")
  existing <- match(oldNames,names(x))
  names(x)[na.omit(existing)] <- newNames[which(!is.na(existing))]
  return(x)
}

Copy multiple files in Python

If you don't want to copy the whole tree (with subdirs etc), use or glob.glob("path/to/dir/*.*") to get a list of all the filenames, loop over the list and use shutil.copy to copy each file.

for filename in glob.glob(os.path.join(source_dir, '*.*')):
    shutil.copy(filename, dest_dir)

Subset and ggplot2

With option 2 in @agstudy's answer now deprecated, defining data with a function can be handy.

library(plyr)
ggplot(data=dat) + 
  geom_line(aes(Value1, Value2, group=ID, colour=ID),
            data=function(x){x$ID %in% c("P1", "P3"))

This approach comes in handy if you wish to reuse a dataset in the same plot, e.g. you don't want to specify a new column in the data.frame, or you want to explicitly plot one dataset in a layer above the other.:

library(plyr)
ggplot(data=dat, aes(Value1, Value2, group=ID, colour=ID)) + 
  geom_line(data=function(x){x[!x$ID %in% c("P1", "P3"), ]}, alpha=0.5) +
  geom_line(data=function(x){x[x$ID %in% c("P1", "P3"), ]})

Call to getLayoutInflater() in places not in activity

LayoutInflater.from(context).inflate(R.layout.row_payment_gateway_item, null);

Return current date plus 7 days

strtotime will automatically use the current unix timestamp to base your string annotation off of.

Just do:

$date = strtotime("+7 day");
echo date('M d, Y', $date);

Added Info For Future Visitors: If you need to pass a timestamp to the function, the below will work.

This will calculate 7 days from yesterday:

$timestamp = time()-86400;

$date = strtotime("+7 day", $timestamp);
echo date('M d, Y', $date);

Get the value of input text when enter key pressed

Something like this (not tested, but should work)

Pass this as parameter in Html:

<input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>

And alert the value of the parameter passed into the search function:

function search(e){
  alert(e.value);
}

Jupyter notebook not running code. Stuck on In [*]

Sometimes the extensions also create a problem. I was using a dark mode extension(Night Eye) in Microsoft edge. So kernel was busy. When I uninstalled it. It working fine.

How to remove element from an array in JavaScript?

shift() is ideal for your situation. shift() removes the first element from an array and returns that element. This method changes the length of the array.

array = [1, 2, 3, 4, 5];

array.shift(); // 1

array // [2, 3, 4, 5]

What is use of c_str function In c++

c_str returns a const char* that points to a null-terminated string (i.e. a C-style string). It is useful when you want to pass the "contents"¹ of an std::string to a function that expects to work with a C-style string.

For example, consider this code:

std::string str("Hello world!");
int pos1 = str.find_first_of('w');

int pos2 = strchr(str.c_str(), 'w') - str.c_str();

if (pos1 == pos2) {
    printf("Both ways give the same result.\n");
}

See it in action.

Notes:

¹ This is not entirely true because an std::string (unlike a C string) can contain the \0 character. If it does, the code that receives the return value of c_str() will be fooled into thinking that the string is shorter than it really is, since it will interpret \0 as the end of the string.

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 2

I had this problem before, and the reason is very simple: Check your variables, if there were strings, so put it in quotes '$your_string_variable_here' ,, if it were numerical keep it without any quotes. for example, if I had these data: $name ( It will be string ) $phone_number ( It will be numerical ) So, it will be like that:

$query = "INSERT INTO users (name, phone) VALUES ('$name', $phone)"; Just like that and it will be fixed ^_^

fatal: early EOF fatal: index-pack failed

None of the solutions above worked for me.

The solution that finally worked for me was switching SSH client. GIT_SSH environment variable was set to the OpenSSH provided by Windows Server 2019. Version 7.7.2.1

C:\Windows\System32\OpenSSH\ssh.exe

I simply installed putty, 0.72

choco install putty

And changed GIT_SSH to

C:\ProgramData\chocolatey\lib\putty.portable\tools\PLINK.EXE

React onClick and preventDefault() link refresh/redirect?

I've had some troubles with anchor tags and preventDefault in the past and I always forget what I'm doing wrong, so here's what I figured out.

The problem I often have is that I try to access the component's attributes by destructuring them directly as with other React components. This will not work, the page will reload, even with e.preventDefault():

function (e, { href }) {
  e.preventDefault();
  // Do something with href
}
...
<a href="/foobar" onClick={clickHndl}>Go to Foobar</a>

It seems the destructuring causes an error (Cannot read property 'href' of undefined) that is not displayed to the console, probably due to the page complete reload. Since the function is in error, the preventDefault doesn't get called. If the href is #, the error is displayed properly since there's no actual reload.

I understand now that I can only access attributes as a second handler argument on custom React components, not on native HTML tags. So of course, to access an HTML tag attribute in an event, this would be the way:

function (e) {
  e.preventDefault();
  const { href } = e.target;
  // Do something with href
}
...
<a href="/foobar" onClick={clickHndl}>Go to Foobar</a>

I hope this helps other people like me puzzled by not shown errors!

Best way to move files between S3 buckets?

If you have a unix host within AWS, then use s3cmd from s3tools.org. Set up permissions so that your key as read access to your development bucket. Then run:

s3cmd cp -r s3://productionbucket/feed/feedname/date s3://developmentbucket/feed/feedname

How to analyze disk usage of a Docker container

The volume part did not work anymore so if anyone is insterested I just change the above script a little bit:

for d in `docker ps | awk '{print $1}' | tail -n +2`; do
    d_name=`docker inspect -f {{.Name}} $d`
    echo "========================================================="
    echo "$d_name ($d) container size:"
    sudo du -d 2 -h /var/lib/docker/aufs | grep `docker inspect -f "{{.Id}}" $d`
    echo "$d_name ($d) volumes:"
    for mount in `docker inspect -f "{{range .Mounts}} {{.Source}}:{{.Destination}}                                                                                                                                                      
    {{end}}" $d`; do
        size=`echo $mount | cut -d':' -f1 | sudo xargs du -d 0 -h`
        mnt=`echo $mount | cut -d':' -f2`
        echo "$size mounted on $mnt"
    done
done

casting Object array to Integer array error

Ross, you can use Arrays.copyof() or Arrays.copyOfRange() too.

Integer[] integerArray = Arrays.copyOf(a, a.length, Integer[].class);
Integer[] integerArray = Arrays.copyOfRange(a, 0, a.length, Integer[].class);

Here the reason to hitting an ClassCastException is you can't treat an array of Integer as an array of Object. Integer[] is a subtype of Object[] but Object[] is not a Integer[].

And the following also will not give an ClassCastException.

Object[] a = new Integer[1];
Integer b=1;
a[0]=b;
Integer[] c = (Integer[]) a;

How to style a div to have a background color for the entire width of the content, and not just for the width of the display?

The inline-block display style seems to do what you want. Note that the <nobr> tag is deprecated, and should not be used. Non-breaking white space is doable in CSS. Here's how I would alter your example style rules:

div { display: inline-block; white-space: nowrap; }
.success { background-color: #ccffcc; }

Alter your stylesheet, remove the <nobr> tags from your source, and give it a try. Note that display: inline-block does not work in every browser, though it tends to only be problematic in older browsers (newer versions should support it to some degree). My personal opinion is to ignore coding for broken browsers. If your code is standards compliant, it should work in all of the major, modern browsers. Anyone still using IE6 (or earlier) deserves the pain. :-)

Excel VBA Macro: User Defined Type Not Defined

I am late for the party. Try replacing as below, mine worked perfectly- "DOMDocument" to "MSXML2.DOMDocument60" "XMLHTTP" to "MSXML2.XMLHTTP60"

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

I would do something like the following:

INSERT INTO cache VALUES (key, generation)
ON DUPLICATE KEY UPDATE (key = key, generation = generation + 1);

Setting the generation value to 0 in code or in the sql but the using the ON DUP... to increment the value. I think that's the syntax anyway.

How to program a fractal?

You should indeed start with the Mandelbrot set, and understand what it really is.

The idea behind it is relatively simple. You start with a function of complex variable

f(z) = z2 + C

where z is a complex variable and C is a complex constant. Now you iterate it starting from z = 0, i.e. you compute z1 = f(0), z2 = f(z1), z3 = f(z2) and so on. The set of those constants C for which the sequence z1, z2, z3, ... is bounded, i.e. it does not go to infinity, is the Mandelbrot set (the black set in the figure on the Wikipedia page).

In practice, to draw the Mandelbrot set you should:

  • Choose a rectangle in the complex plane (say, from point -2-2i to point 2+2i).
  • Cover the rectangle with a suitable rectangular grid of points (say, 400x400 points), which will be mapped to pixels on your monitor.
  • For each point/pixel, let C be that point, compute, say, 20 terms of the corresponding iterated sequence z1, z2, z3, ... and check whether it "goes to infinity". In practice you can check, while iterating, if the absolute value of one of the 20 terms is greater than 2 (if one of the terms does, the subsequent terms are guaranteed to be unbounded). If some z_k does, the sequence "goes to infinity"; otherwise, you can consider it as bounded.
  • If the sequence corresponding to a certain point C is bounded, draw the corresponding pixel on the picture in black (for it belongs to the Mandelbrot set). Otherwise, draw it in another color. If you want to have fun and produce pretty plots, draw it in different colors depending on the magnitude of abs(20th term).

The astounding fact about fractals is how we can obtain a tremendously complex set (in particular, the frontier of the Mandelbrot set) from easy and apparently innocuous requirements.

Enjoy!

URL Encode a string in jQuery for an AJAX request

encodeURIComponent works fine for me. we can give the url like this in ajax call.The code shown below:

  $.ajax({
    cache: false,
    type: "POST",
    url: "http://atandra.mivamerchantdev.com//mm5/json.mvc?Store_Code=ATA&Function=Module&Module_Code=thub_connector&Module_Function=THUB_Request",
    data: "strChannelName=" + $('#txtupdstorename').val() + "&ServiceUrl=" + encodeURIComponent($('#txtupdserviceurl').val()),
    dataType: "HTML",
    success: function (data) {
    },
    error: function (xhr, ajaxOptions, thrownError) {
    }
  });

SQL exclude a column using SELECT * [except columnA] FROM tableA?

No.

Maintenance-light best practice is to specify only the required columns.

At least 2 reasons:

  • This makes your contract between client and database stable. Same data, every time
  • Performance, covering indexes

Edit (July 2011):

If you drag from Object Explorer the Columns node for a table, it puts a CSV list of columns in the Query Window for you which achieves one of your goals

What is the JSF resource library for and how should it be used?

Actually, all of those examples on the web wherein the common content/file type like "js", "css", "img", etc is been used as library name are misleading.

Real world examples

To start, let's look at how existing JSF implementations like Mojarra and MyFaces and JSF component libraries like PrimeFaces and OmniFaces use it. No one of them use resource libraries this way. They use it (under the covers, by @ResourceDependency or UIViewRoot#addComponentResource()) the following way:

<h:outputScript library="javax.faces" name="jsf.js" />
<h:outputScript library="primefaces" name="jquery/jquery.js" />
<h:outputScript library="omnifaces" name="omnifaces.js" />
<h:outputScript library="omnifaces" name="fixviewstate.js" />
<h:outputScript library="omnifaces.combined" name="[dynamicname].js" />
<h:outputStylesheet library="primefaces" name="primefaces.css" />
<h:outputStylesheet library="primefaces-aristo" name="theme.css" />
<h:outputStylesheet library="primefaces-vader" name="theme.css" />

It should become clear that it basically represents the common library/module/theme name where all of those resources commonly belong to.

Easier identifying

This way it's so much easier to specify and distinguish where those resources belong to and/or are coming from. Imagine that you happen to have a primefaces.css resource in your own webapp wherein you're overriding/finetuning some default CSS of PrimeFaces; if PrimeFaces didn't use a library name for its own primefaces.css, then the PrimeFaces own one wouldn't be loaded, but instead the webapp-supplied one, which would break the look'n'feel.

Also, when you're using a custom ResourceHandler, you can also apply more finer grained control over resources coming from a specific library when library is used the right way. If all component libraries would have used "js" for all their JS files, how would the ResourceHandler ever distinguish if it's coming from a specific component library? Examples are OmniFaces CombinedResourceHandler and GraphicResourceHandler; check the createResource() method wherein the library is checked before delegating to next resource handler in chain. This way they know when to create CombinedResource or GraphicResource for the purpose.

Noted should be that RichFaces did it wrong. It didn't use any library at all and homebrewed another resource handling layer over it and it's therefore impossible to programmatically identify RichFaces resources. That's exactly the reason why OmniFaces CombinedResourceHander had to introduce a reflection-based hack in order to get it to work anyway with RichFaces resources.

Your own webapp

Your own webapp does not necessarily need a resource library. You'd best just omit it.

<h:outputStylesheet name="css/style.css" />
<h:outputScript name="js/script.js" />
<h:graphicImage name="img/logo.png" />

Or, if you really need to have one, you can just give it a more sensible common name, like "default" or some company name.

<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />

Or, when the resources are specific to some master Facelets template, you could also give it the name of the template, so that it's easier to relate each other. In other words, it's more for self-documentary purposes. E.g. in a /WEB-INF/templates/layout.xhtml template file:

<h:outputStylesheet library="layout" name="css/style.css" />
<h:outputScript library="layout" name="js/script.js" />

And a /WEB-INF/templates/admin.xhtml template file:

<h:outputStylesheet library="admin" name="css/style.css" />
<h:outputScript library="admin" name="js/script.js" />

For a real world example, check the OmniFaces showcase source code.

Or, when you'd like to share the same resources over multiple webapps and have created a "common" project for that based on the same example as in this answer which is in turn embedded as JAR in webapp's /WEB-INF/lib, then also reference it as library (name is free to your choice; component libraries like OmniFaces and PrimeFaces also work that way):

<h:outputStylesheet library="common" name="css/style.css" />
<h:outputScript library="common" name="js/script.js" />
<h:graphicImage library="common" name="img/logo.png" />

Library versioning

Another main advantage is that you can apply resource library versioning the right way on resources provided by your own webapp (this doesn't work for resources embedded in a JAR). You can create a direct child subfolder in the library folder with a name in the \d+(_\d+)* pattern to denote the resource library version.

WebContent
 |-- resources
 |    `-- default
 |         `-- 1_0
 |              |-- css
 |              |    `-- style.css
 |              |-- img
 |              |    `-- logo.png
 |              `-- js
 |                   `-- script.js
 :

When using this markup:

<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />

This will generate the following HTML with the library version as v parameter:

<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&amp;v=1_0" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&amp;v=1_0"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&amp;v=1_0" alt="" />

So, if you have edited/updated some resource, then all you need to do is to copy or rename the version folder into a new value. If you have multiple version folders, then the JSF ResourceHandler will automatically serve the resource from the highest version number, according to numerical ordering rules.

So, when copying/renaming resources/default/1_0/* folder into resources/default/1_1/* like follows:

WebContent
 |-- resources
 |    `-- default
 |         |-- 1_0
 |         |    :
 |         |
 |         `-- 1_1
 |              |-- css
 |              |    `-- style.css
 |              |-- img
 |              |    `-- logo.png
 |              `-- js
 |                   `-- script.js
 :

Then the last markup example would generate the following HTML:

<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&amp;v=1_1" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&amp;v=1_1"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&amp;v=1_1" alt="" />

This will force the webbrowser to request the resource straight from the server instead of showing the one with the same name from the cache, when the URL with the changed parameter is been requested for the first time. This way the endusers aren't required to do a hard refresh (Ctrl+F5 and so on) when they need to retrieve the updated CSS/JS resource.

Please note that library versioning is not possible for resources enclosed in a JAR file. You'd need a custom ResourceHandler. See also How to use JSF versioning for resources in jar.

See also:

Text file in VBA: Open/Find Replace/SaveAs/Close File

Why involve Notepad?

Sub ReplaceStringInFile()

Dim sBuf As String
Dim sTemp As String
Dim iFileNum As Integer
Dim sFileName As String

' Edit as needed
sFileName = "C:\Temp\test.txt"

iFileNum = FreeFile
Open sFileName For Input As iFileNum

Do Until EOF(iFileNum)
    Line Input #iFileNum, sBuf
    sTemp = sTemp & sBuf & vbCrLf
Loop
Close iFileNum

sTemp = Replace(sTemp, "THIS", "THAT")

iFileNum = FreeFile
Open sFileName For Output As iFileNum
Print #iFileNum, sTemp
Close iFileNum

End Sub

How to check version of python modules?

You can simply use subprocess.getoutput(python3 --version)

import subprocess as sp
print(sp.getoutput(python3 --version))

# or however it suits your needs!
py3_version = sp.getoutput(python3 --version)

def check_version(name, version):...

check_version('python3', py3_version)

For more information and ways to do this without depending on the __version__ attribute:

Assign output of os.system to a variable and prevent it from being displayed on the screen

You can also use subprocess.check_output() which raises an error when the subprocess returns anything other than exit code 0:

https://docs.python.org/3/library/subprocess.html#check_output()

Axios handling errors

if u wanna use async await try

export const post = async ( link,data ) => {
const option = {
    method: 'post',
    url: `${URL}${link}`,
    validateStatus: function (status) {
        return status >= 200 && status < 300; // default
      },
    data
};

try {
    const response = await axios(option);
} catch (error) {
    const { response } = error;
    const { request, ...errorObject } = response; // take everything but 'request'
    console.log(errorObject);
}

How do I copy an entire directory of files into an existing directory using Python?

Here is a version inspired by this thread that more closely mimics distutils.file_util.copy_file.

updateonly is a bool if True, will only copy files with modified dates newer than existing files in dst unless listed in forceupdate which will copy regardless.

ignore and forceupdate expect lists of filenames or folder/filenames relative to src and accept Unix-style wildcards similar to glob or fnmatch.

The function returns a list of files copied (or would be copied if dryrun if True).

import os
import shutil
import fnmatch
import stat
import itertools

def copyToDir(src, dst, updateonly=True, symlinks=True, ignore=None, forceupdate=None, dryrun=False):

    def copySymLink(srclink, destlink):
        if os.path.lexists(destlink):
            os.remove(destlink)
        os.symlink(os.readlink(srclink), destlink)
        try:
            st = os.lstat(srclink)
            mode = stat.S_IMODE(st.st_mode)
            os.lchmod(destlink, mode)
        except OSError:
            pass  # lchmod not available
    fc = []
    if not os.path.exists(dst) and not dryrun:
        os.makedirs(dst)
        shutil.copystat(src, dst)
    if ignore is not None:
        ignorepatterns = [os.path.join(src, *x.split('/')) for x in ignore]
    else:
        ignorepatterns = []
    if forceupdate is not None:
        forceupdatepatterns = [os.path.join(src, *x.split('/')) for x in forceupdate]
    else:
        forceupdatepatterns = []
    srclen = len(src)
    for root, dirs, files in os.walk(src):
        fullsrcfiles = [os.path.join(root, x) for x in files]
        t = root[srclen+1:]
        dstroot = os.path.join(dst, t)
        fulldstfiles = [os.path.join(dstroot, x) for x in files]
        excludefiles = list(itertools.chain.from_iterable([fnmatch.filter(fullsrcfiles, pattern) for pattern in ignorepatterns]))
        forceupdatefiles = list(itertools.chain.from_iterable([fnmatch.filter(fullsrcfiles, pattern) for pattern in forceupdatepatterns]))
        for directory in dirs:
            fullsrcdir = os.path.join(src, directory)
            fulldstdir = os.path.join(dstroot, directory)
            if os.path.islink(fullsrcdir):
                if symlinks and dryrun is False:
                    copySymLink(fullsrcdir, fulldstdir)
            else:
                if not os.path.exists(directory) and dryrun is False:
                    os.makedirs(os.path.join(dst, dir))
                    shutil.copystat(src, dst)
        for s,d in zip(fullsrcfiles, fulldstfiles):
            if s not in excludefiles:
                if updateonly:
                    go = False
                    if os.path.isfile(d):
                        srcdate = os.stat(s).st_mtime
                        dstdate = os.stat(d).st_mtime
                        if srcdate > dstdate:
                            go = True
                    else:
                        go = True
                    if s in forceupdatefiles:
                        go = True
                    if go is True:
                        fc.append(d)
                        if not dryrun:
                            if os.path.islink(s) and symlinks is True:
                                copySymLink(s, d)
                            else:
                                shutil.copy2(s, d)
                else:
                    fc.append(d)
                    if not dryrun:
                        if os.path.islink(s) and symlinks is True:
                            copySymLink(s, d)
                        else:
                            shutil.copy2(s, d)
    return fc

White spaces are required between publicId and systemId

I just found my self with this Exception, I was trying to consume a JAX-WS, with a custom URL like this:

String WSDL_URL= <get value from properties file>;
Customer service = new Customer(new URL(WSDL_URL));
ExecutePtt port = service.getExecutePt();
return port.createMantainCustomers(part);

and Java threw:

XML reader error: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,63]
Message: White spaces are required between publicId and systemId.

Turns out that the URL string used to construct the service was missing the "?wsdl" at the end. For instance:

Bad:

http://www.host.org/service/Customer

Good:

http://www.host.org/service/Customer?wsdl

Connecting to remote URL which requires authentication using Java

Since Java 9, you can do this

URL url = new URL("http://www.example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setAuthenticator(new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication ("USER", "PASS".toCharArray());
    }
});

How to inspect Javascript Objects

Here is my object inspector that is more readable. Because the code takes to long to write down here you can download it at http://etto-aa-js.googlecode.com/svn/trunk/inspector.js

Use like this :

document.write(inspect(object));

How can I find the number of elements in an array?

void numel(int array1[100][100])
{
    int count=0;
    for(int i=0;i<100;i++)
    {
        for(int j=0;j<100;j++)
        {
            if(array1[i][j]!='\0') 
            {
                count++;
                //printf("\n%d-%d",array1[i][j],count);
            }
            else 
                break;
        }
    }
    printf("Number of elements=%d",count);
}
int main()
{   
    int r,arr[100][100]={0},c;
    printf("Enter the no. of rows: ");
    scanf("%d",&r);
    printf("\nEnter the no. of columns: ");
    scanf("%d",&c);
    printf("\nEnter the elements: ");
    for(int i=0;i<r;i++)
    {
        for(int j=0;j<c;j++)
        {
            scanf("%d",&arr[i][j]);
        }
    }
    numel(arr);
}

This shows the exact number of elements in matrix irrespective of the array size you mentioned while initilasing(IF that's what you meant)

'any' vs 'Object'

Bit old, but doesn't hurt to add some notes.

When you write something like this

let a: any;
let b: Object;
let c: {};
  • a has no interface, it can be anything, the compiler knows nothing about its members so no type checking is performed when accessing/assigning both to it and its members. Basically, you're telling the compiler to "back off, I know what I'm doing, so just trust me";
  • b has the Object interface, so ONLY the members defined in that interface are available for b. It's still JavaScript, so everything extends Object;
  • c extends Object, like anything else in TypeScript, but adds no members. Since type compatibility in TypeScript is based on structural subtyping, not nominal subtyping, c ends up being the same as b because they have the same interface: the Object interface.

And that's why

a.doSomething(); // Ok: the compiler trusts you on that
b.doSomething(); // Error: Object has no doSomething member
c.doSomething(); // Error: c neither has doSomething nor inherits it from Object

and why

a.toString(); // Ok: whatever, dude, have it your way
b.toString(); // Ok: toString is defined in Object
c.toString(); // Ok: c inherits toString from Object

So Object and {} are equivalents in TypeScript.

If you declare functions like these

function fa(param: any): void {}
function fb(param: Object): void {}

with the intention of accepting anything for param (maybe you're going to check types at run-time to decide what to do with it), remember that

  • inside fa, the compiler will let you do whatever you want with param;
  • inside fb, the compiler will only let you reference Object's members.

It is worth noting, though, that if param is supposed to accept multiple known types, a better approach is to declare it using union types, as in

function fc(param: string|number): void {}

Obviously, OO inheritance rules still apply, so if you want to accept instances of derived classes and treat them based on their base type, as in

interface IPerson {
    gender: string;
}

class Person implements IPerson {
    gender: string;
}

class Teacher extends Person {}

function func(person: IPerson): void {
    console.log(person.gender);
}

func(new Person());     // Ok
func(new Teacher());    // Ok
func({gender: 'male'}); // Ok
func({name: 'male'});   // Error: no gender..

the base type is the way to do it, not any. But that's OO, out of scope, I just wanted to clarify that any should only be used when you don't know whats coming, and for anything else you should annotate the correct type.

UPDATE:

Typescript 2.2 added an object type, which specifies that a value is a non-primitive: (i.e. not a number, string, boolean, symbol, undefined, or null).

Consider functions defined as:

function b(x: Object) {}
function c(x: {}) {}
function d(x: object) {}

x will have the same available properties within all of these functions, but it's a type error to call d with a primitive:

b("foo"); //Okay
c("foo"); //Okay
d("foo"); //Error: "foo" is a primitive

Name attribute in @Entity and @Table

@Entity is useful with model classes to denote that this is the entity or table

@Table is used to provide any specific name to your table if you want to provide any different name

Note: if you don't use @Table then hibernate consider that @Entity is your table name by default and @Entity must

@Entity    
@Table(name = "emp")     
public class Employee implements java.io.Serializable    
{

}

Fill background color left to right CSS

The thing you will need to do here is use a linear gradient as background and animate the background position. In code:

Use a linear gradient (50% red, 50% blue) and tell the browser that background is 2 times larger than the element's width (width:200%, height:100%), then tell it to position the background left.

background: linear-gradient(to right, red 50%, blue 50%);
background-size: 200% 100%;
background-position:left bottom;

On hover, change the background position to right bottom and with transition:all 2s ease;, the position will change gradually (it's nicer with linear tough) background-position:right bottom;

http://jsfiddle.net/75Umu/3/

As for the -vendor-prefix'es, see the comments to your question

extra If you wish to have a "transition" in the colour, you can make it 300% width and make the transition start at 34% (a bit more than 1/3) and end at 65% (a bit less than 2/3).

background: linear-gradient(to right, red 34%, blue 65%);
background-size: 300% 100%;

Demo:

_x000D_
_x000D_
div {
    font: 22px Arial;
    display: inline-block;
    padding: 1em 2em;
    text-align: center;
    color: white;
    background: red; /* default color */

    /* "to left" / "to right" - affects initial color */
    background: linear-gradient(to left, salmon 50%, lightblue 50%) right;
    background-size: 200%;
    transition: .5s ease-out;
}
div:hover {
    background-position: left;
}
_x000D_
<div>Hover me</div>
_x000D_
_x000D_
_x000D_

Ignore mapping one property with Automapper

I'm perhaps a bit of a perfectionist; I don't really like the ForMember(..., x => x.Ignore()) syntax. It's a little thing, but it it matters to me. I wrote this extension method to make it a bit nicer:

public static IMappingExpression<TSource, TDestination> Ignore<TSource, TDestination>(
    this IMappingExpression<TSource, TDestination> map,
    Expression<Func<TDestination, object>> selector)
{
    map.ForMember(selector, config => config.Ignore());
    return map;
}

It can be used like so:

Mapper.CreateMap<JsonRecord, DatabaseRecord>()
        .Ignore(record => record.Field)
        .Ignore(record => record.AnotherField)
        .Ignore(record => record.Etc);

You could also rewrite it to work with params, but I don't like the look of a method with loads of lambdas.