Programs & Examples On #Py++

Undefined reference to main - collect2: ld returned 1 exit status

I my case I found out the void for the main function declaration was missing.

I was previously using Visual Studio in Windows and this was never a problem, so I thought I might leave it out now too.

How to forcefully set IE's Compatibility Mode off from the server-side?

Changing my header to the following solve the problem:

<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

Facebook key hash does not match any stored key hashes

You are may be using wrong password the default password for debug keystore is android

How to [recursively] Zip a directory in PHP?

Great solution but for my Windows I need make a modifications. Below the modify code

function Zip($source, $destination){

if (!extension_loaded('zip') || !file_exists($source)) {
    return false;
}

$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
    return false;
}

$source = str_replace('\\', '/', realpath($source));

if (is_dir($source) === true)
{
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

    foreach ($files as $file)
    {
        $file = str_replace('\\', '/', $file);

        // Ignore "." and ".." folders
        if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
            continue;

        if (is_dir($file) === true)
        {
            $zip->addEmptyDir(str_replace($source . '/', '', $file));
        }
        else if (is_file($file) === true)
        {

            $str1 = str_replace($source . '/', '', '/'.$file);
            $zip->addFromString($str1, file_get_contents($file));

        }
    }
}
else if (is_file($source) === true)
{
    $zip->addFromString(basename($source), file_get_contents($source));
}

return $zip->close();
}

Access to the path denied error in C#

I had this issue for longer than I would like to admit.

I simply just needed to run VS as an administrator, rookie mistake on my part...

Hope this helps someone <3

How to grant permission to users for a directory using command line in Windows?

Corrupt Permissions: Regaining access to a folder and its sub-objects

Although most of the answers posted in reply to the question have some merit, IMHO none of them give a complete solution. The following (might be) a perfect solution for Windows 7 if you are locked-out of a folder by corrupted permission settings:

icacls "c:\folder" /remove:d /grant:r Everyone:(OI)(CI)F /T  

For Windows 10 the user/SID must be specified after the /remove:d option:

icacls "c:\folder" /remove:d Everyone /grant:r Everyone:(OI)(CI)F /T  

.
Notes:

  1. The command is applied to the specified directory.

  2. Specifying the user "Everyone" sets the widest possible permission, as it includes every possible user.

  3. The option "/remove:d" deletes any explicit DENY settings that may exist, as those override explicit ALLOW settings: a necessary preliminary to creating a new ALLOW setting. This is only a precaution, as there is often no DENY setting present, but better safe than sorry.

  4. The option "/grant" creates a new ALLOW setting, an explicit permission that replaces (":r") any and all explicit ALLOW settings that may exist.

  5. The "F" parameter (i.e. the permission created) makes this a grant of FULL control.

  6. The "/T" parameter adds recursion, applying these changes to all current sub-objects in the specified directory (i.e. files and subfolders), as well as the folder itself.

  7. The "(OI)" and "(CI)" parameters also add recursion, applying these changes to sub-objects created subsequently.
    .

ADDENDUM (2019/02/10) -

The Windows 10 command line above was kindly suggested to me today, so here it is. I haven't got Windows 10 to test it, but please try it out if you have (and then will you please post a comment below).

The change only concerns removing the DENY setting as a first step. There might well not be any DENY setting present, so that option might make no difference. My understanding is, on Windows 7, that you don't need to specify a user after /remove:d but I might be wrong about that!

.

ADDENDUM (2019/11/21) -

User astark recommends replacing Everyone with the term *S-1-1-0 in order for the command to be language independent. I only have an English install of Windows, so I can't test this proposal, but it seems reasonable.

AngularJS - get element attributes values

You can do this using dataset property of the element, using with or without jquery it work... i'm not aware of old browser Note: that when you use dash ('-') sign, you need to use capital case. Eg. a-b => aB

_x000D_
_x000D_
function onContentLoad() {_x000D_
  var item = document.getElementById("id1");_x000D_
  var x = item.dataset.x;_x000D_
  var data = item.dataset.myData;_x000D_
_x000D_
  var resX = document.getElementById("resX");_x000D_
  var resData = document.getElementById("resData");_x000D_
_x000D_
  resX.innerText = x;_x000D_
  resData.innerText = data;_x000D_
_x000D_
  console.log(x);_x000D_
  console.log(data);_x000D_
}
_x000D_
<body onload="onContentLoad()">_x000D_
  <div id="id1" data-x="a" data-my-data="b"></div>_x000D_
_x000D_
  Read 'x':_x000D_
  <label id="resX"></label>_x000D_
  <br/>Read 'my-data':_x000D_
  <label id="resData"></label>_x000D_
</body>
_x000D_
_x000D_
_x000D_

try/catch blocks with async/await

catching in this fashion, in my experience, is dangerous. Any error thrown in the entire stack will be caught, not just an error from this promise (which is probably not what you want).

The second argument to a promise is already a rejection/failure callback. It's better and safer to use that instead.

Here's a typescript typesafe one-liner I wrote to handle this:

function wait<R, E>(promise: Promise<R>): [R | null, E | null] {
  return (promise.then((data: R) => [data, null], (err: E) => [null, err]) as any) as [R, E];
}

// Usage
const [currUser, currUserError] = await wait<GetCurrentUser_user, GetCurrentUser_errors>(
  apiClient.getCurrentUser()
);

Filtering JSON array using jQuery grep()

var data = {
    "items": [{
        "id": 1,
        "category": "cat1"
    }, {
        "id": 2,
        "category": "cat2"
    }, {
        "id": 3,
        "category": "cat1"
    }]
};

var returnedData = $.grep(data.items, function (element, index) {
    return element.id == 1;
});


alert(returnedData[0].id + "  " + returnedData[0].category);

The returnedData is returning an array of objects, so you can access it by array index.

http://jsfiddle.net/wyfr8/913/

DATEDIFF function in Oracle

You can simply subtract two dates. You have to cast it first, using to_date:

select to_date('2000-01-01', 'yyyy-MM-dd')
       - to_date('2000-01-02', 'yyyy-MM-dd')
       datediff
from   dual
;

The result is in days, to the difference of these two dates is -1 (you could swap the two dates if you like). If you like to have it in hours, just multiply the result with 24.

Adding Text to DataGridView Row Header

it's because of your first column (Rows Header column) width ! increase it's width then you can see it's value ! you can use this command:

dgv1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;

(notice: you must first set dgv1.RowHeadersVisible = true;)

How to create a vector of user defined size but with no predefined values?

With the constructor:

// create a vector with 20 integer elements
std::vector<int> arr(20);

for(int x = 0; x < 20; ++x)
   arr[x] = x;

Unicode (UTF-8) reading and writing to files in Python

Well, your favorite text editor does not realize that \xc3\xa1 are supposed to be character literals, but it interprets them as text. That's why you get the double backslashes in the last line -- it's now a real backslash + xc3, etc. in your file.

If you want to read and write encoded files in Python, best use the codecs module.

Pasting text between the terminal and applications is difficult, because you don't know which program will interpret your text using which encoding. You could try the following:

>>> s = file("f1").read()
>>> print unicode(s, "Latin-1")
Capitán

Then paste this string into your editor and make sure that it stores it using Latin-1. Under the assumption that the clipboard does not garble the string, the round trip should work.

'tuple' object does not support item assignment

Tuples, in python can't have their values changed. If you'd like to change the contained values though I suggest using a list:

[1,2,3] not (1,2,3)

jQuery get mouse position within an element

One way is to use the jQuery offset method to translate the event.pageX and event.pageY coordinates from the event into a mouse position relative to the parent. Here's an example for future reference:

$("#something").click(function(e){
   var parentOffset = $(this).parent().offset(); 
   //or $(this).offset(); if you really just want the current element's offset
   var relX = e.pageX - parentOffset.left;
   var relY = e.pageY - parentOffset.top;
});

.NET / C# - Convert char[] to string

char[] chars = {'a', ' ', 's', 't', 'r', 'i', 'n', 'g'};
string s = new string(chars);

The name 'ConfigurationManager' does not exist in the current context

You may also get this error if you add a reference to a different, unrelated project by mistake. Check if that applies to you.

How to select a specific node with LINQ-to-XML

Assuming the ID is unique:

var result = xmldoc.Element("Customers")
                   .Elements("Customer")
                   .Single(x => (int?)x.Attribute("ID") == 2);

You could also use First, FirstOrDefault, SingleOrDefault or Where, instead of Single for different circumstances.

The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

  1. Why is this happening?

    The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, was officially deprecated in PHP v5.5.0 and removed in PHP v7.

    It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.

    The manual has contained warnings against its use in new code since June 2011.

  2. How can I fix it?

    As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.

    They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.

    Hashphp.org has an excellent tutorial on migrating from ext/mysql to PDO.

  3. I understand that it's possible to suppress deprecation errors by setting error_reporting in php.ini to exclude E_DEPRECATED:

    error_reporting = E_ALL ^ E_DEPRECATED
    

    What will happen if I do that?

    Yes, it is possible to suppress such error messages and continue using the old ext/mysql extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.

    Note also that this technique will suppress all E_DEPRECATED messages, not just those to do with the ext/mysql extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @—however this will suppress all errors raised by that expression, not just E_DEPRECATED ones.


What should you do?

  • You are starting a new project.

    There is absolutely no reason to use ext/mysql—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.

  • You have (your own) legacy codebase that currently depends upon ext/mysql.

    It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.

    • Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.

      Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.

    • The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.

      Consider whether you really need to upgrade to PHP v5.5 at this time.

      You should begin planning to replace ext/mysql with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.

      However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

  • You are using a third party project that depends upon ext/mysql.

    Consider whether you really need to upgrade to PHP v5.5 at this time.

    Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

    It is absolutely essential to perform regression testing.

How to use ArrayList's get() method

To put it nice and simply, get(int index) returns the element at the specified index.

So say we had an ArrayList of Strings:

List<String> names = new ArrayList<String>();
names.add("Arthur Dent");
names.add("Marvin");
names.add("Trillian");
names.add("Ford Prefect");

Which can be visualised as: A visual representation of the array list Where 0, 1, 2, and 3 denote the indexes of the ArrayList.

Say we wanted to retrieve one of the names we would do the following: String name = names.get(1); Which returns the name at the index of 1.

Getting the element at index 1 So if we were to print out the name System.out.println(name); the output would be Marvin - Although he might not be too happy with us disturbing him.

Full Screen Theme for AppCompat

Issues arise among before and after versions of Android 4.0 (API level 14).

from here I created my own solution.

@SuppressLint("NewApi")
@Override
protected void onResume()
{
    super.onResume();

    if (Build.VERSION.SDK_INT < 16)
    {
        // Hide the status bar
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // Hide the action bar
        getSupportActionBar().hide();
    }
    else
    {
        // Hide the status bar
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
        / Hide the action bar
        getActionBar().hide();
    }
}

I write this code in onResume() method because if you exit from your app and then you reopen it, the action bar remains active! (and so this fix the problem)

I hope it was helpful ;)

Get UserDetails object from Security Context in Spring MVC controller

That's another solution (Spring Security 3):

public String getLoggedUser() throws Exception {
    String name = SecurityContextHolder.getContext().getAuthentication().getName();
    return (!name.equals("anonymousUser")) ? name : null;
}

Getting first value from map in C++

A map will not keep insertion order. Use *(myMap.begin()) to get the value of the first pair (the one with the smallest key when ordered).

You could also do myMap.begin()->first to get the key and myMap.begin()->second to get the value.

Position last flex item at the end of container

Flexible Box Layout Module - 8.1. Aligning with auto margins

Auto margins on flex items have an effect very similar to auto margins in block flow:

  • During calculations of flex bases and flexible lengths, auto margins are treated as 0.

  • Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

Therefore you could use margin-top: auto to distribute the space between the other elements and the last element.

This will position the last element at the bottom.

p:last-of-type {
  margin-top: auto;
}

_x000D_
_x000D_
.container {
  display: flex;
  flex-direction: column;
  border: 1px solid #000;
  min-height: 200px;
  width: 100px;
}
p {
  height: 30px;
  background-color: blue;
  margin: 5px;
}
p:last-of-type {
  margin-top: auto;
}
_x000D_
<div class="container">
  <p></p>
  <p></p>
  <p></p>
</div>
_x000D_
_x000D_
_x000D_

vertical example


Likewise, you can also use margin-left: auto or margin-right: auto for the same alignment horizontally.

p:last-of-type {
  margin-left: auto;
}

_x000D_
_x000D_
.container {
  display: flex;
  width: 100%;
  border: 1px solid #000;
}
p {
  height: 50px;
  width: 50px;
  background-color: blue;
  margin: 5px;
}
p:last-of-type {
  margin-left: auto;
}
_x000D_
<div class="container">
  <p></p>
  <p></p>
  <p></p>
  <p></p>
</div>
_x000D_
_x000D_
_x000D_

horizontal example

force Maven to copy dependencies into target/lib

If you make your project a war or ear type maven will copy the dependencies.

calculating number of days between 2 columns of dates in data frame

In Ronald's example, if the date formats are different (as displayed below) then modify the format parameter

survey <- data.frame(date=c("2012-07-26","2012-07-25"),tx_start=c("2012-01-01","2012-01-01"))

survey$date_diff <- as.Date(as.character(survey$date), format="%Y-%m-%d")-
              as.Date(as.character(survey$tx_start), format="%Y-%m-%d")

survey:

   date      tx_start     date_diff
1 2012-07-26     2012-01-01    207 days
2 2012-07-25     2012-01-01    206 days

Docker-Compose persistent data MySQL

Actually this is the path and you should mention a valid path for this to work. If your data directory is in current directory then instead of my-data you should mention ./my-data, otherwise it will give you that error in mysql and mariadb also.

volumes:
 ./my-data:/var/lib/mysql

ImportError: No module named pythoncom

If you're on windows you probably want the pywin32 library, which includes pythoncom and a whole lot of other stuff that is pretty standard.

How to get element by innerText

I've just needed a way to get the element that contains a specific text and this is what I came up with.

Use document.getElementsByInnerText() to get multiple elements (multiple elements might have the same exact text), and use document.getElementByInnerText() to get just one element (first match).

Also, you can localize the search by using an element (e.g. someElement.getElementByInnerText()) instead of document.

You might need to tweak it in order to make it cross-browser or satisfy your needs.

I think the code is self-explanatory, so I'll leave it as it is.

_x000D_
_x000D_
HTMLElement.prototype.getElementsByInnerText = function (text, escape) {_x000D_
    var nodes  = this.querySelectorAll("*");_x000D_
    var matches = [];_x000D_
    for (var i = 0; i < nodes.length; i++) {_x000D_
        if (nodes[i].innerText == text) {_x000D_
            matches.push(nodes[i]);_x000D_
        }_x000D_
    }_x000D_
    if (escape) {_x000D_
        return matches;_x000D_
    }_x000D_
    var result = [];_x000D_
    for (var i = 0; i < matches.length; i++) {_x000D_
        var filter = matches[i].getElementsByInnerText(text, true);_x000D_
        if (filter.length == 0) {_x000D_
            result.push(matches[i]);_x000D_
        }_x000D_
    }_x000D_
    return result;_x000D_
};_x000D_
document.getElementsByInnerText = HTMLElement.prototype.getElementsByInnerText;_x000D_
_x000D_
HTMLElement.prototype.getElementByInnerText = function (text) {_x000D_
    var result = this.getElementsByInnerText(text);_x000D_
    if (result.length == 0) return null;_x000D_
    return result[0];_x000D_
}_x000D_
document.getElementByInnerText = HTMLElement.prototype.getElementByInnerText;_x000D_
_x000D_
console.log(document.getElementsByInnerText("Text1"));_x000D_
console.log(document.getElementsByInnerText("Text2"));_x000D_
console.log(document.getElementsByInnerText("Text4"));_x000D_
console.log(document.getElementsByInnerText("Text6"));_x000D_
_x000D_
console.log(document.getElementByInnerText("Text1"));_x000D_
console.log(document.getElementByInnerText("Text2"));_x000D_
console.log(document.getElementByInnerText("Text4"));_x000D_
console.log(document.getElementByInnerText("Text6"));
_x000D_
<table>_x000D_
    <tr>_x000D_
        <td>Text1</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Text2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>_x000D_
            <a href="#">Text2</a>_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>_x000D_
            <a href="#"><span>Text3</span></a>_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>_x000D_
            <a href="#">Special <span>Text4</span></a>_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>_x000D_
            Text5_x000D_
            <a href="#">Text6</a>_x000D_
            Text7_x000D_
        </td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

ERROR : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

I got a similar error, which was resolved by installing the corresponding MySQL drivers from:

http://www.connectionstrings.com/mysql-connector-odbc-5-2/info-and-download/

and by performing the following steps:

  1. Go to IIS and Application Pools in the left menu.
  2. Select relevant application pool which is assigned to the project.
  3. Click the Set Application Pool Defaults.
  4. In General Tab, set the Enable 32 Bit Application entry to "True".

Reference:

http://www.codeproject.com/Tips/305249/ERROR-IM-Microsoft-ODBC-Driver-Manager-Data-sou

How to get value from form field in django framework?

Using a form in a view pretty much explains it.

The standard pattern for processing a form in a view looks like this:

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...

            print form.cleaned_data['my_form_field_name']

            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = ContactForm() # An unbound form

    return render_to_response('contact.html', {
        'form': form,
    })

Amazon S3 upload file and get URL

No you cannot get the URL in single action but two :)

First of all, you may have to make the file public before uploading because it makes no sense to get the URL that no one can access. You can do so by setting ACL as Michael Astreiko suggested. You can get the resource URL either by calling getResourceUrl or getUrl.

AmazonS3Client s3Client = (AmazonS3Client)AmazonS3ClientBuilder.defaultClient();
s3Client.putObject(new PutObjectRequest("your-bucket", "some-path/some-key.jpg", new File("somePath/someKey.jpg")).withCannedAcl(CannedAccessControlList.PublicRead))
s3Client.getResourceUrl("your-bucket", "some-path/some-key.jpg");

Note1: The different between getResourceUrl and getUrl is that getResourceUrl will return null when exception occurs.

Note2: getUrl method is not defined in the AmazonS3 interface. You have to cast the object to AmazonS3Client if you use the standard builder.

ng-model for `<input type="file"/>` (with directive DEMO)

How to enable <input type="file"> to work with ng-model

Working Demo of Directive that Works with ng-model

The core ng-model directive does not work with <input type="file"> out of the box.

This custom directive enables ng-model and has the added benefit of enabling the ng-change, ng-required, and ng-form directives to work with <input type="file">.

_x000D_
_x000D_
angular.module("app",[]);

angular.module("app").directive("selectNgFiles", function() {
  return {
    require: "ngModel",
    link: function postLink(scope,elem,attrs,ngModel) {
      elem.on("change", function(e) {
        var files = elem[0].files;
        ngModel.$setViewValue(files);
      })
    }
  }
});
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app">
    <h1>AngularJS Input `type=file` Demo</h1>
    
    <input type="file" select-ng-files ng-model="fileArray" multiple>

    <code><table ng-show="fileArray.length">
    <tr><td>Name</td><td>Date</td><td>Size</td><td>Type</td><tr>
    <tr ng-repeat="file in fileArray">
      <td>{{file.name}}</td>
      <td>{{file.lastModified | date  : 'MMMdd,yyyy'}}</td>
      <td>{{file.size}}</td>
      <td>{{file.type}}</td>
    </tr>
    </table></code>
    
  </body>
_x000D_
_x000D_
_x000D_

How to set default values in Rails?

For boolean fields in Rails 3.2.6 at least, this will work in your migration.

def change
  add_column :users, :eula_accepted, :boolean, default: false
end

Putting a 1 or 0 for a default will not work here, since it is a boolean field. It must be a true or false value.

How to unstage large number of files without deleting the content

2019 update

As pointed out by others in related questions (see here, here, here, here, here, here, and here), you can now unstage a file with git restore --staged <file>.

To unstage all the files in your project, run the following from the root of the repository (the command is recursive):

git restore --staged .

If you only want to unstage the files in a directory, navigate to it before running the above or run:

git restore --staged <directory-path>

Notes

  • git restore was introduced in July 2019 and released in version 2.23.
    With the --staged flag, it restores the content of the working tree from HEAD (so it does the opposite of git add and does not delete any change).

  • This is a new command, but the behaviour of the old commands remains unchanged. So the older answers with git reset or git reset HEAD are still perfectly valid.

  • When running git status with staged uncommitted file(s), this is now what Git suggests to use to unstage file(s) (instead of git reset HEAD <file> as it used to prior to v2.23).

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

Get rid of the semicolon after WordGame.

You really should have discovered this problem when the class was a lot smaller. When you're writing code, you should be compiling about every time you add half a dozen lines.

How to copy a file to multiple directories using the gnu cp command

As far as I can see it you can use the following:

ls | xargs -n 1 cp -i file.dat

The -i option of cp command means that you will be asked whether to overwrite a file in the current directory with the file.dat. Though it is not a completely automatic solution it worked out for me.

Tkinter understanding mainloop

I'm using an MVC / MVA design pattern, with multiple types of "views". One type is a "GuiView", which is a Tk window. I pass a view reference to my window object which does things like link buttons back to view functions (which the adapter / controller class also calls).

In order to do that, the view object constructor needed to be completed prior to creating the window object. After creating and displaying the window, I wanted to do some initial tasks with the view automatically. At first I tried doing them post mainloop(), but that didn't work because mainloop() blocked!

As such, I created the window object and used tk.update() to draw it. Then, I kicked off my initial tasks, and finally started the mainloop.

import Tkinter as tk

class Window(tk.Frame):
    def __init__(self, master=None, view=None ):
        tk.Frame.__init__( self, master )
        self.view_ = view       
        """ Setup window linking it to the view... """

class GuiView( MyViewSuperClass ):

    def open( self ):
        self.tkRoot_ = tk.Tk()
        self.window_ = Window( master=None, view=self )
        self.window_.pack()
        self.refresh()
        self.onOpen()
        self.tkRoot_.mainloop()         

    def onOpen( self ):        
        """ Do some initial tasks... """

    def refresh( self ):        
        self.tkRoot_.update()

Changing file extension in Python

>> file = r'C:\Docs\file.2020.1.1.xls'
>> ext = '.'+ os.path.realpath(file).split('.')[-1:][0]
>> filefinal = file.replace(ext,'.zip')
>> os.rename(file ,filefinal) 

Bad logic for repeating extension, sample: 'C:\Docs\.xls_aaa.xls.xls'

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

How to select all columns, except one column in pandas?

df[df.columns.difference(['b'])]

Out: 
          a         c         d
0  0.427809  0.459807  0.333869
1  0.678031  0.668346  0.645951
2  0.996573  0.673730  0.314911
3  0.786942  0.719665  0.330833

How do I apply a CSS class to Html.ActionLink in ASP.NET MVC?

@ewomack has a great answer for C#, unless you don't need extra object values. In my case, I ended up using something similar to:

@Html.ActionLink("Delete", "DeleteList", "List", new object { },
new { @class = "delete"})

Unicode character as bullet for list-item in CSS

Try this code...

li:before {
    content: "? "; /* caractère UTF-8 */
}

(Excel) Conditional Formatting based on Adjacent Cell Value

You need to take out the $ signs before the row numbers in the formula....and the row number used in the formula should correspond to the first row of data, so if you are applying this to the ("applies to") range $B$2:$B$5 it must be this formula

=$B2>$C2

by using that "relative" version rather than your "absolute" one Excel (implicitly) adjusts the formula for each row in the range, as if you were copying the formula down

SQLite error 'attempt to write a readonly database' during insert?

I used:

echo exec('whoami');

to find out who is running the script (say username), and then gave the user permissions to the entire application directory, like:

sudo chown -R :username /var/www/html/myapp

Hope this helps someone out there.

PHP: Best way to check if input is a valid number?

The most secure way

if(preg_replace('/^(\-){0,1}[0-9]+(\.[0-9]+){0,1}/', '', $value) == ""){
  //if all made of numbers "-" or ".", then yes is number;
}

Difference between if () { } and if () : endif;

I think that it's particularly clearer when you're using a mix of ifs, fors and foreaches in view scripts:

<?php if ( $this->hasIterable ): ?>
    <h2>Iterable</h2>
    <ul>
    <?php foreach ( $this->iterable as $key => $val ):?>
        <?php for ( $i = 0; $i <= $val; $i++ ): ?>
        <li><?php echo $key ?></li>
        <?php endfor; ?>
    <?php endforeach; ?>
    </ul>
<?php elseif ( $this->hasScalar ): ?>
    <h2>Scalar</h2>
    <?php for ( $i = 0; $i <= $this->scalar; $i++ ): ?>
    <p>Foo = Bar</p>
    <?php endfor; ?>
<?php else: ?>
    <h2>Other</h2>
    <?php if ( $this->otherVal === true ): ?>
    <p>Spam</p>
    <?php else: ?>  
    <p>Eggs</p>  
    <?php endif; ?>
<?php endif; ?>

as opposed to:

<?php if ( $this->hasIterable ){ ?>
    <h2>Iterable</h2>
    <ul>
    <?php foreach ( $this->iterable as $key => $val ){?>
        <?php for ( $i = 0; $i <= $val; $i++ ){ ?>
        <li><?php echo $key ?></li>
        <?php } ?>
    <?php } ?>
    </ul>
<?php } elseif ( $this->hasScalar ){ ?>
    <h2>Scalar</h2>
    <?php for ( $i = 0; $i <= $this->scalar; $i++ ){ ?>
    <p>Foo = Bar</p>
    <?php } ?>
<?php } else { ?>
    <h2>Other</h2>
    <?php if ( $this->otherVal === true ){ ?>
    <p>Spam</p>
    <?php } else { ?>  
    <p>Eggs</p>  
    <?php } ?>
<?php } ?>

This is especially useful for long control statements where you might not be able to see the top declaration from the bottom brace.

How to delete columns in pyspark dataframe

Maybe a little bit off topic, but here is the solution using Scala. Make an Array of column names from your oldDataFrame and delete the columns that you want to drop ("colExclude"). Then pass the Array[Column] to select and unpack it.

val columnsToKeep: Array[Column] = oldDataFrame.columns.diff(Array("colExclude"))
                                               .map(x => oldDataFrame.col(x))
val newDataFrame: DataFrame = oldDataFrame.select(columnsToKeep: _*)

Cassandra cqlsh - connection refused

This is because of some pre-configurations in the cassandra. And to fix this, there are following commented lines in the cassandra-env.sh file:

#add this if you’re having trouble connecting:
#JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=<public name>

where you have to start fixing the error.

Open the terminal and start fixing using the following easy steps:

Step-1

use

sudo nano /etc/cassandra/cassandra-env.sh

this command and search for JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname= uncomment the line by simply removing # attached in the start of the line.

NOTE: If you have never opened this file to fix this error then you will find JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=<public name>

Step-2 Now replace <public name> with 127.0.0.1

Step-3 Save the file and restart the cassandra using systemctl restart cassandra.service (if you haven't the server is alredy running). OR start the cassandra using systemctl start cassandra.service (if the server is not running).

Step-4 Check the status either by using sudo service cassandra status or systemctl status cassandra.service.

Note: Once check the system monitor whether cassandra is running there or not.

Try cqlsh now. It'll work.

Note: nano is editor you can use other editors you are comfortable with.

IndentationError: unexpected unindent WHY?

It's because you have:

def readTTable(fname):
    try:

without a matching except block after the try: block. Every try must have at least one matching except.

See the Errors and Exceptions section of the Python tutorial.

How to convert a single char into an int

If you are worried about encoding, you can always use a switch statement.

Just be careful with the format you keep those large numbers in. The maximum size for an integer in some systems is as low as 65,535 (32,767 signed). Other systems, you've got 2,147,483,647 (or 4,294,967,295 unsigned)

IF/ELSE Stored Procedure

Nick is right. The next error is the else should be else if (you currently have a boolean expression in your else which makes no sense). Here is what it should be

ELSE IF(@Trans_type = 'subscr_cancel')
    BEGIN
    SET @tmpType = 'basic'
    END

You currently have the following (which is wrong):

ELSE(@Trans_type = 'subscr_cancel')
    BEGIN
    SET @tmpType = 'basic'
    END

Here's a tip for the future- double click on the error and SQL Server management Studio will go to the line where the error resides. If you think SQL Server gives cryptic errors (which I don't think it does), then you haven't worked with Oracle!

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

This code will do what you're looking for. It's based on examples found here and here.

The autofmt_xdate() call is particularly useful for making the x-axis labels readable.

import numpy as np
from matplotlib import pyplot as plt

fig = plt.figure()

width = .35
ind = np.arange(len(OY))
plt.bar(ind, OY, width=width)
plt.xticks(ind + width / 2, OX)

fig.autofmt_xdate()

plt.savefig("figure.pdf")

enter image description here

How can labels/legends be added for all chart types in chart.js (chartjs.org)?

I know this question is old. But this might be useful for someone who is having the problem with legend. In addition to the answer given by ZaneDarken, I modified the chart.js file to show the legend in my pie chart. I changed the legendTemplate(which is declared many times for every chart type) just above these lines :

_x000D_
_x000D_
Chart.Type.extend({_x000D_
      //Passing in a name registers this chart in the Chart namespace_x000D_
      name: "Doughnut",_x000D_
      //Providing a defaults will also register the deafults in the chart namespace_x000D_
      defaults: defaultConfig,_x000D_
      .......
_x000D_
_x000D_
_x000D_

My legendTemplate is changed from

_x000D_
_x000D_
legendTemplate : "_x000D_
<ul class=\ "<%=name.toLowerCase()%>-legend\">_x000D_
  <% for (var i=0; i<datasets.length; i++){%>_x000D_
    <li><span style=\ "background-color:<%=datasets[i].strokeColor%>\"></span>_x000D_
      <%if(datasets[i].label){%>_x000D_
        <%=datasets[i].label%>_x000D_
          <%}%>_x000D_
    </li>_x000D_
    <%}%>_x000D_
</ul>"
_x000D_
_x000D_
_x000D_

To

_x000D_
_x000D_
legendTemplate: "_x000D_
<ul class=\ "<%=name.toLowerCase()%>-legend\">_x000D_
  <% for (var i=0; i<segments.length; i++){%>_x000D_
    <li><span style=\ "-moz-border-radius:7px 7px 7px 7px; border-radius:7px 7px 7px 7px; margin-right:10px;width:15px;height:15px;display:inline-block;background-color:<%=segments[i].fillColor%>\"> </span>_x000D_
      <%if(segments[i].label){%>_x000D_
        <%=s egments[i].label%>_x000D_
          <%}%>_x000D_
    </li>_x000D_
    <%}%>_x000D_
</ul>"
_x000D_
_x000D_
_x000D_

Case Insensitive String comp in C

You can get an idea, how to implement an efficient one, if you don't have any in the library, from here

It use a table for all 256 chars.

  • in that table for all chars, except letters - used its ascii codes.
  • for upper case letter codes - the table list codes of lower cased symbols.

then we just need to traverse a strings and compare our table cells for a given chars:

const char *cm = charmap,
        *us1 = (const char *)s1,
        *us2 = (const char *)s2;
while (cm[*us1] == cm[*us2++])
    if (*us1++ == '\0')
        return (0);
return (cm[*us1] - cm[*--us2]);

When to use If-else if-else over switch statements and vice versa

concerning Readability:

I typically prefer if/else constructs over switch statements, especially in languages that allows fall-through cases. What I've found, often, is as the projects age, and multiple developers gets involved, you'll start having trouble with the construction of a switch statement.

If they (the statements) become anything more than simple, many programmers become lazy and instead of reading the entire statement to understand it, they'll simply pop in a case to cover whatever case they're adding into the statement.

I've seen many cases where code repeats in a switch statement because a person's test was already covered, a simple fall-though case would have sufficed, but laziness forced them to add the redundant code at the end instead of trying to understand the switch. I've also seen some nightmarish switch statements with many cases that were poorly constructed, and simply trying to follow all the logic, with many fall-through cases dispersed throughout, and many cases which weren't, becomes difficult ... which kind of leads to the first/redundancy problem I talked about.

Theoretically, the same problem could exist with if/else constructs, but in practice this just doesn't seem to happen as often. Maybe (just a guess) programmers are forced to read a bit more carefully because you need to understand the, often, more complex conditions being tested within the if/else construct? If you're writing something simple that you know others are likely to never touch, and you can construct it well, then I guess it's a toss-up. In that case, whatever is more readable and feels best to you is probably the right answer because you're likely to be sustaining that code.

concerning Speed:

Switch statements often perform faster than if-else constructs (but not always). Since the possible values of a switch statement are laid out beforehand, compilers are able to optimize performance by constructing jump tables. Each condition doesn't have to be tested as in an if/else construct (well, until you find the right one, anyway).

However this isn't always the case, though. If you have a simple switch, say, with possible values of 1 to 10, this will be the case. The more values you add requires the jump tables to be larger and the switch becomes less efficient (not than an if/else, but less efficient than the comparatively simple switch statement). Also, if the values are highly variant ( i.e. instead of 1 to 10, you have 10 possible values of, say, 1, 1000, 10000, 100000, and so on to 100000000000), the switch is less efficient than in the simpler case.

Hope this helps.

Is it possible to overwrite a function in PHP

short answer is no, you can't overwrite a function once its in the PHP function scope.

your best of using anonymous functions like so

$ihatefooexamples = function()
{
  return "boo-foo!";
}

//...
unset($ihatefooexamples);
$ihatefooexamples = function()
{
   return "really boo-foo";
}

http://php.net/manual/en/functions.anonymous.php

Tomcat manager/html is not available?

Your website is blank because ROOT directory is missing from your ../webapps folder. Refer to tomcat documentation for the specific location on where it should be.

Counting null and non-null values in a single query

SELECT
    ALL_VALUES
    ,COUNT(ALL_VALUES)
FROM(
        SELECT 
        NVL2(A,'NOT NULL','NULL') AS ALL_VALUES 
        ,NVL(A,0)
        FROM US
)
GROUP BY ALL_VALUES

GROUP_CONCAT ORDER BY

In IMPALA, not having order in the GROUP_CONCAT can be problematic, over at Coders'Co. we have some sort of a workaround for that (we need it for Rax/Impala). If you need the GROUP_CONCAT result with an ORDER BY clause in IMPALA, take a look at this blog post: http://raxdb.com/blog/sorting-by-regex/

Checking if jquery is loaded using Javascript

You can check whether it exists and, if it does not exist, load it dynamically.

function loadScript(src) {
    return new Promise(function (resolve, reject) {
        var s;
        s = document.createElement('script');
        s.src = src;
        s.onload = resolve;
        s.onerror = reject;
        document.head.appendChild(s);
    });
}



async function load(){
if (!window.jQuery){
    await loadScript(`https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js`);
}

console.log(jQuery);

}

load();

CSS Image size, how to fill, but not stretch?

Enhancement on the accepted answer by @afonsoduarte.
in case you are using bootstrap


There are three differences:
  1. Providing width:100% on the style.
    This is helpful if you are using bootstrap and want the image to stretch all the available width.

  2. Specifying the height property is optional, You can remove/keep it as you need

    .cover {
       object-fit: cover;
       width: 100%;
       /*height: 300px;  optional, you can remove it, but in my case it was good */
    }
    
  3. By the way, there is NO need to provide the height and width attributes on the image element because they will be overridden by the style.
    so it is enough to write something like this.

    <img class="cover" src="url to img ..."  />
    

How to style icon color, size, and shadow of Font Awesome Icons

Using FA 4.4.0 adding

.text-danger
    color: #d9534f

to the document css and then using

 <i class="fa fa-ban text-danger"></i>

changes the color to red. You can set your own for any color.

Where to place the 'assets' folder in Android Studio?

In Android Studio 4.1.1

Right Click on your module (app for example) -> New -> Folder -> Assets Folder

enter image description here

How do I make a dictionary with multiple keys to one value?

If you're going to be adding to this dictionary frequently you'd want to take a class based approach, something similar to @Latty's answer in this SO question 2d-dictionary-with-many-keys-that-will-return-the-same-value.

However, if you have a static dictionary, and you need only access values by multiple keys then you could just go the very simple route of using two dictionaries. One to store the alias key association and one to store your actual data:

alias = {
    'a': 'id1',
    'b': 'id1',
    'c': 'id2',
    'd': 'id2'
}

dictionary = {
    'id1': 1,
    'id2': 2
}

dictionary[alias['a']]

If you need to add to the dictionary you could write a function like this for using both dictionaries:

def add(key, id, value=None)
    if id in dictionary:
        if key in alias:
            # Do nothing
            pass
        else:
            alias[key] = id
    else:
        dictionary[id] = value
        alias[key] = id

add('e', 'id2')
add('f', 'id3', 3)

While this works, I think ultimately if you want to do something like this writing your own data structure is probably the way to go, though it could use a similar structure.

How to tell CRAN to install package dependencies automatically?

Another possibility is to select the Install Dependencies checkbox In the R package installer, on the bottom right:

enter image description here

Error: Execution failed for task ':app:clean'. Unable to delete file

This issue appeared to me in android studio 2.0 stable channel and the solution was due to a problem happened while updating my android studio i solved this by installing a fresh android studio. after deleting all old files for the old installation. and to keep the very nice feature of Instant Run

Getting Google+ profile picture url with user_id

If you use Flutter, then you can access it via people.googleapis.com endpoint, code uses google_sign_in library

import 'package:google_sign_in/google_sign_in.dart';

Future<String> getPhotoUrl(GoogleSignInAccount account, String userId) async {
  // final authentication = await account.authentication;
  final url = 'https://people.googleapis.com/v1/people/${userId}?personFields=photos';
  final response = await http.get(
    url,
    headers: await account.authHeaders
  );

  final data = json.decode(response.body);
  return data['photos'].first['url'];
}

You will get something like

{
  resourceName: people/998812322529259873423, 
  etag: %EgQBAzcabcQBAgUH, 
  photos: [{metadata: {primary: true, source: {type: PROFILE, id: 107721622529987673423}}, 
  url: https://lh3.googleusercontent.com/a-/abcdefmB2p1VWxLsNT9WSV0yqwuwo6o2Ba21sh_ra7CnrZ=s100}]
}

where url is an accessible image url.

How to make Excel VBA variables available to multiple macros?

Declare them outside the subroutines, like this:

Public wbA as Workbook
Public wbB as Workbook
Sub MySubRoutine()
    Set wbA = Workbooks.Open("C:\file.xlsx")
    Set wbB = Workbooks.Open("C:\file2.xlsx")
    OtherSubRoutine
End Sub
Sub OtherSubRoutine()
    MsgBox wbA.Name, vbInformation
End Sub

Alternately, you can pass variables between subroutines:

Sub MySubRoutine()
Dim wbA as Workbook
Dim wbB as Workbook
    Set wbA = Workbooks.Open("C:\file.xlsx")
    Set wbB = Workbooks.Open("C:\file2.xlsx")
    OtherSubRoutine wbA, wbB
End Sub
Sub OtherSubRoutine(wb1 as Workbook, wb2 as Workbook)
    MsgBox wb1.Name, vbInformation
    MsgBox wb2.Name, vbInformation
End Sub

Or use Functions to return values:

Sub MySubroutine()
    Dim i as Long
    i = MyFunction()
    MsgBox i
End Sub
Function MyFunction()
    'Lots of code that does something
    Dim x As Integer, y as Double
    For x = 1 to 1000
        'Lots of code that does something
    Next
    MyFunction = y
End Function

In the second method, within the scope of OtherSubRoutine you refer to them by their parameter names wb1 and wb2. Passed variables do not need to use the same names, just the same variable types. This allows you some freedom, for example you have a loop over several workbooks, and you can send each workbook to a subroutine to perform some action on that Workbook, without making all (or any) of the variables public in scope.

A Note About User Forms

Personally I would recommend keeping Option Explicit in all of your modules and forms (this prevents you from instantiating variables with typos in their names, like lCoutn when you meant lCount etc., among other reasons).

If you're using Option Explicit (which you should), then you should qualify module-scoped variables for style and to avoid ambiguity, and you must qualify user-form Public scoped variables, as these are not "public" in the same sense. For instance, i is undefined, though it's Public in the scope of UserForm1:

enter image description here

You can refer to it as UserForm1.i to avoid the compile error, or since forms are New-able, you can create a variable object to contain reference to your form, and refer to it that way:

enter image description here

NB: In the above screenshots x is declared Public x as Long in another standard code module, and will not raise the compilation error. It may be preferable to refer to this as Module2.x to avoid ambiguity and possible shadowing in case you re-use variable names...

How do I find the index of a character within a string in C?

You can also use strcspn(string, "e") but this may be much slower since it's able to handle searching for multiple possible characters. Using strchr and subtracting the pointer is the best way.

Converting an int to a binary string representation in Java?

Convert Integer to Binary:

import java.util.Scanner;

public class IntegerToBinary {

    public static void main(String[] args) {

        Scanner input = new Scanner( System.in );

        System.out.println("Enter Integer: ");
        String integerString =input.nextLine();

        System.out.println("Binary Number: "+Integer.toBinaryString(Integer.parseInt(integerString)));
    }

}

Output:

Enter Integer:

10

Binary Number: 1010

Quick unix command to display specific lines in the middle of a file?

I'd first split the file into few smaller ones like this

$ split --lines=50000 /path/to/large/file /path/to/output/file/prefix

and then grep on the resulting files.

C++ Fatal Error LNK1120: 1 unresolved externals

Well it seems that you are missing a reference to some library. I had the similar error solved it by adding a reference to the #pragma comment(lib, "windowscodecs.lib")

When to use throws in a Java method declaration?

If you are catching an exception type, you do not need to throw it, unless you are going to rethrow it. In the example you post, the developer should have done one or another, not both.

Typically, if you are not going to do anything with the exception, you should not catch it.

The most dangerous thing you can do is catch an exception and not do anything with it.

A good discussion of when it is appropriate to throw exceptions is here

When to throw an exception?

REST API Best practice: How to accept list of parameter values as input

First:

I think you can do it 2 ways

http://our.api.com/Product/<id> : if you just want one record

http://our.api.com/Product : if you want all records

http://our.api.com/Product/<id1>,<id2> :as James suggested can be an option since what comes after the Product tag is a parameter

Or the one I like most is:

You can use the the Hypermedia as the engine of application state (HATEOAS) property of a RestFul WS and do a call http://our.api.com/Product that should return the equivalent urls of http://our.api.com/Product/<id> and call them after this.

Second

When you have to do queries on the url calls. I would suggest using HATEOAS again.

1) Do a get call to http://our.api.com/term/pumas/productType/clothing/color/black

2) Do a get call to http://our.api.com/term/pumas/productType/clothing,bags/color/black,red

3) (Using HATEOAS) Do a get call to `http://our.api.com/term/pumas/productType/ -> receive the urls all clothing possible urls -> call the ones you want (clothing and bags) -> receive the possible color urls -> call the ones you want

Check if a Bash array contains a value

I came up with this one, which turns out to work only in zsh, but I think the general approach is nice.

arr=( "hello world" "find me" "what?" )
if [[ "${arr[@]/#%find me/}" != "${arr[@]}" ]]; then
    echo "found!"
else
    echo "not found!"
fi

You take out your pattern from each element only if it starts ${arr[@]/#pattern/} or ends ${arr[@]/%pattern/} with it. These two substitutions work in bash, but both at the same time ${arr[@]/#%pattern/} only works in zsh.

If the modified array is equal to the original, then it doesn't contain the element.

Edit:

This one works in bash:

 function contains () {
        local arr=(${@:2})
        local el=$1
        local marr=(${arr[@]/#$el/})
        [[ "${#arr[@]}" != "${#marr[@]}" ]]
    }

After the substitution it compares the length of both arrays. Obly if the array contains the element the substitution will completely delete it, and the count will differ.

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

Send SMS/Text Messages from Command Line with VBScript!

If VBA meets the rules for VB Script then it can be called from command line by simply placing it into a text file - in this case there's no need to specifically open Outlook.

I had a need to send automated text messages to myself from the command line, so I used the code below, which is just a compressed version of @Geoff's answer above.

Most mobile phone carriers worldwide provide an email address "version" of your mobile phone number. For example in Canada with Rogers or Chatr Wireless, an email sent to <YourPhoneNumber> @pcs.rogers.com will be immediately delivered to your Rogers/Chatr phone as a text message.

* You may need to "authorize" the first message on your phone, and some carriers may charge an additional fee for theses message although as far as I know, all Canadian carriers provide this little-known service for free. Check your carrier's website for details.

There are further instructions and various compiled lists of worldwide carrier's Email-to-Text addresses available online such as this and this and this.


Code & Instructions

  1. Copy the code below and paste into a new file in your favorite text editor.
  2. Save the file with any name with a .VBS extension, such as TextMyself.vbs.

That's all!
Just double-click the file to send a test message, or else run it from a batch file using START.

Sub SendMessage()
    Const EmailToSMSAddy = "[email protected]"
    Dim objOutlookRecip
    With CreateObject("Outlook.Application").CreateItem(0)
        Set objOutlookRecip = .Recipients.Add(EmailToSMSAddy)
        objOutlookRecip.Type = 1
        .Subject = "The computer needs your attention!"
        .Body = "Go see why Windows Command Line is texting you!"
        .Save
        .Send
    End With
End Sub

Example Batch File Usage:

START x:\mypath\TextMyself.vbs

Of course there are endless possible ways this could be adapted and customized to suit various practical or creative needs.

Change Input to Upper Case

I couldn't find the text-uppercase in Bootstrap referred to in one of the answers. No matter, I created it;

.text-uppercase {
  text-transform: uppercase;
}

This displays text in uppercase, but the underlying data is not transformed in this way. So in jquery I have;

$(".text-uppercase").keyup(function () {
    this.value = this.value.toLocaleUpperCase();
});

This will change the underlying data wherever you use the text-uppercase class.

535-5.7.8 Username and Password not accepted

Goto config/initializers/setup_mail.rb Check whether the configuration there matches the configuration written in the development.rb file.It should look like the following in both files:

config.action_mailer.smtp_settings = {
     :address =>"[email protected]",
     :port => 587,
     :domain => "gmail.com",
     :user_name => "[email protected]",
     :password => "********",
     :authentication => 'plain',
     :enable_starttls_auto => true,
     :openssl_verify_mode => 'none' 
     } 

This will most certainly solve your problem.

Use Fieldset Legend with bootstrap

That's because Bootstrap by default sets the width of the legend element to 100%. You can fix this by changing your legend.scheduler-border to also use:

legend.scheduler-border {
    width:inherit; /* Or auto */
    padding:0 10px; /* To give a bit of padding on the left and right */
    border-bottom:none;
}

JSFiddle example.

You'll also need to ensure your custom stylesheet is being added after Bootstrap to prevent Bootstrap overriding your styling - although your styles here should have higher specificity.

You may also want to add margin-bottom:0; to it as well to reduce the gap between the legend and the divider.

Adding system header search path to Xcode

To use quotes just for completeness.

"/Users/my/work/a project with space"/**

If not recursive, remove the /**

How to Convert string "07:35" (HH:MM) to TimeSpan

You can convert the time using the following code.

TimeSpan _time = TimeSpan.Parse("07:35");

But if you want to get the current time of the day you can use the following code:

TimeSpan _CurrentTime = DateTime.Now.TimeOfDay;

The result will be:

03:54:35.7763461

With a object cantain the Hours, Minutes, Seconds, Ticks and etc.

Reading images in python

Easy way

from IPython.display import Image

Image(filename ="Covid.jpg" size )

How do I display Ruby on Rails form validation error messages one at a time?

I resolved it like this:

<% @user.errors.each do |attr, msg| %>
  <li>
    <%= @user.errors.full_messages_for(attr).first if @user.errors[attr].first == msg %>
  </li>
<% end %>

This way you are using the locales for the error messages.

Handling errors in Promise.all

Alternately, if you have a case where you don't particularly care about the values of the resolved promises when there is one failure but you still want them to have run, you could do something like this which will resolve with the promises as normal when they all succeed and reject with the failed promises when any of them fail:

function promiseNoReallyAll (promises) {
  return new Promise(
    async (resolve, reject) => {
      const failedPromises = []

      const successfulPromises = await Promise.all(
        promises.map(
          promise => promise.catch(error => {
            failedPromises.push(error)
          })
        )
      )

      if (failedPromises.length) {
        reject(failedPromises)
      } else {
        resolve(successfulPromises)
      }
    }
  )
}

MySQL "NOT IN" query

To use IN, you must have a set, use this syntax instead:

SELECT * FROM Table1 WHERE Table1.principal NOT IN (SELECT principal FROM table2)

Play audio from a stream using C#

NAudio wraps the WaveOutXXXX API. I haven't looked at the source, but if NAudio exposes the waveOutWrite() function in a way that doesn't automatically stop playback on each call, then you should be able to do what you really want, which is to start playing the audio stream before you've received all the data.

Using the waveOutWrite() function allows you to "read ahead" and dump smaller chunks of audio into the output queue - Windows will automatically play the chunks seamlessly. Your code would have to take the compressed audio stream and convert it to small chunks of WAV audio on the fly; this part would be really difficult - all the libraries and components I've ever seen do MP3-to-WAV conversion an entire file at a time. Probably your only realistic chance is to do this using WMA instead of MP3, because you can write simple C# wrappers around the multimedia SDK.

How to print (using cout) a number in binary form?

If you want to display the bit representation of any object, not just an integer, remember to reinterpret as a char array first, then you can print the contents of that array, as hex, or even as binary (via bitset):

#include <iostream>
#include <bitset>
#include <climits>

template<typename T>
void show_binrep(const T& a)
{
    const char* beg = reinterpret_cast<const char*>(&a);
    const char* end = beg + sizeof(a);
    while(beg != end)
        std::cout << std::bitset<CHAR_BIT>(*beg++) << ' ';
    std::cout << '\n';
}
int main()
{
    char a, b;
    short c;
    a = -58;
    c = -315;
    b = a >> 3;
    show_binrep(a);
    show_binrep(b);
    show_binrep(c);
    float f = 3.14;
    show_binrep(f);
}

Note that most common systems are little-endian, so the output of show_binrep(c) is not the 1111111 011000101 you expect, because that's not how it's stored in memory. If you're looking for value representation in binary, then a simple cout << bitset<16>(c) works.

Insert results of a stored procedure into a temporary table

Here is my T-SQL with parameters

--require one time execution if not configured before
sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO

--require one time execution if not configured before
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO


--the query
DECLARE @param1 int = 1, @param2 int = 2
DECLARE @SQLStr varchar(max) = 'SELECT * INTO #MyTempTable
                                FROM OPENROWSET(''SQLNCLI'',  
''Server=ServerName;Database=DbName;Trusted_Connection=yes'',
''exec StoredProcedureName '+ CAST(@param1 AS varchar(15)) +','+ CAST(@param2 AS varchar(15)) +''') AS a ;
 select * from #MyTempTable;
 drop table #MyTempTable        
';
EXECUTE(@SQLStr);

Flex-box: Align last row to grid

I made a SCSS mixin for it.

@mixin last-row-flexbox($num-columns, $width-items){

  $filled-space: $width-items * $num-columns;
  $margin: calc((100% - #{$filled-space}) / (#{$num-columns} - 1));

  $num-cols-1 : $num-columns - 1;

  &:nth-child(#{$num-columns}n+1):nth-last-child(-n+#{$num-cols-1}) ~ & {
    margin-left: $margin;
  }
  @for $i from 1 through $num-columns - 2 { 
    $index: $num-columns - $i;
    &:nth-child(#{$num-columns}n+#{$index}):last-child{
      margin-right: auto;
    }
  }
}

This is the codepen link: http://codepen.io/diana_aceves/pen/KVGNZg

You just have to set the items width in percentage and number of columns.

I hope this can help you.

How do I import modules or install extensions in PostgreSQL 9.1+?

While Evan Carrol's answer is correct, please note that you need to install the postgresql contrib package in order for the CREATE EXTENSION command to work.

In Ubuntu 12.04 it would go like this:

sudo apt-get install postgresql-contrib

Restart the postgresql server:

sudo /etc/init.d/postgresql restart

All available extension are in:

/usr/share/postgresql/9.1/extension/

Now you can run the CREATE EXTENSION command.

ng-options with simple array init

<select ng-model="option" ng-options="o for o in options">

$scope.option will be equal to 'var1' after change, even you see value="0" in generated html

plunker

Dump all documents of Elasticsearch

You can also dump elasticsearch data in JSON format by http request: https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html
CURL -XPOST 'https://ES/INDEX/_search?scroll=10m'
CURL -XPOST 'https://ES/_search/scroll' -d '{"scroll": "10m", "scroll_id": "ID"}'

Finding the mode of a list

Perhaps try the following. It is O(n) and returns a list of floats (or ints). It is thoroughly, automatically tested. It uses collections.defaultdict, but I'd like to think you're not opposed to using that. It can also be found at https://stromberg.dnsalias.org/~strombrg/stddev.html

def compute_mode(list_: typing.List[float]) -> typing.List[float]:
    """                       
    Compute the mode of list_.

    Note that the return value is a list, because sometimes there is a tie for "most common value".
                                                                        
    See https://stackoverflow.com/questions/10797819/finding-the-mode-of-a-list
    """                                                                                                        
    if not list_:
        raise ValueError('Empty list')
    if len(list_) == 1:           
        raise ValueError('Single-element list')
    value_to_count_dict: typing.DefaultDict[float, int] = collections.defaultdict(int)
    for element in list_:
        value_to_count_dict[element] += 1
    count_to_values_dict = collections.defaultdict(list)
    for value, count in value_to_count_dict.items():   
        count_to_values_dict[count].append(value)                           
    counts = list(count_to_values_dict)
    if len(counts) == 1:                                                                            
        raise ValueError('All elements in list are the same')          
    maximum_occurrence_count = max(counts)
    if maximum_occurrence_count == 1:
        raise ValueError('No element occurs more than once')
    minimum_occurrence_count = min(counts)
    if maximum_occurrence_count <= minimum_occurrence_count:
        raise ValueError('Maximum count not greater than minimum count')
    return count_to_values_dict[maximum_occurrence_count]

format a number with commas and decimals in C# (asp.net MVC3)

CultureInfo us = new CultureInfo("en-US");
TotalAmount.ToString("N", us)

how to check for special characters php

preg_match('/'.preg_quote('^\'£$%^&*()}{@#~?><,@|-=-_+-¬', '/').'/', $string);

What is http multipart request?

I have found an excellent and relatively short explanation here.

A multipart request is a REST request containing several packed REST requests inside its entity.

Could not load file or assembly or one of its dependencies. Access is denied. The issue is random, but after it happens once, it continues

In my case, I was using simple impersonation and the impersonation user had trouble accessing one of the project assemblies. My solution:

  1. Look for the message of the inner exception to identify the problematic assembly.
  2. Modify the security properties of the assembly file.

    a) Add the user account you're using for impersonation to the Group and user names.

    b) Give that user account full access to the assembly file.

No process is on the other end of the pipe (SQL Server 2012)

Please check this also enter image description here Also check in configuration TCP/IP,Names PipeLine and shared memory enabled

How to make several plots on a single page using matplotlib?

This works also:

for i in range(19):
    plt.subplot(5,4,i+1) 

It plots 19 total graphs on one page. The format is 5 down and 4 across..

Validation of radio button group using jQuery validation plugin

As per Brandon's answer. But if you're using ASP.NET MVC which uses unobtrusive validation, you can add the data-val attribute to the first one. I also like to have labels for each radio button for usability.

<span class="field-validation-valid" data-valmsg-for="color" data-valmsg-replace="true"></span>
<p><input type="radio" name="color" id="red" value="R" data-val="true" data-val-required="Please choose one of these options:"/> <label for="red">Red</label></p>
<p><input type="radio" name="color" id="green" value="G"/> <label for="green">Green</label></p>
<p><input type="radio" name="color" id="blue" value="B"/> <label for="blue">Blue</label></p>

Giving a border to an HTML table row, <tr>

After fighting with this for a long time I have concluded that the spectacularly simple answer is to just fill the table with empty cells to pad out every row of the table to the same number of cells (taking colspan into account, obviously). With computer-generated HTML this is very simple to arrange, and avoids fighting with complex workarounds. Illustration follows:

<h3>Table borders belong to cells, and aren't present if there is no cell</h3>
<table style="border:1px solid red; width:100%; border-collapse:collapse;">
    <tr style="border-top:1px solid darkblue;">
        <th>Col 1<th>Col 2<th>Col 3
    <tr style="border-top:1px solid darkblue;">
        <td>Col 1 only
    <tr style="border-top:1px solid darkblue;">
        <td colspan=2>Col 1 2 only
    <tr style="border-top:1px solid darkblue;">
        <td>1<td>2<td>3

</table>


<h3>Simple solution, artificially insert empty cells</h3>

<table style="border:1px solid red; width:100%; border-collapse:collapse;">
    <tr style="border-top:1px solid darkblue;">
        <th>Col 1<th>Col 2<th>Col 3
    <tr style="border-top:1px solid darkblue;">
        <td>Col 1 only<td><td>
    <tr style="border-top:1px solid darkblue;">
        <td colspan=2>Col 1 2 only<td>
    <tr style="border-top:1px solid darkblue;">
        <td>1<td>2<td>3

</table>

maven command line how to point to a specific settings.xml for a single command?

You can simply use:

mvn --settings YourOwnSettings.xml clean install

or

mvn -s YourOwnSettings.xml clean install

ImportError: No module named dateutil.parser

If you are using Pipenv, you may need to add this to your Pipfile:

[packages]
python-dateutil = "*"

Regular expression that matches valid IPv6 addresses

From "IPv6 regex":

(\A([0-9a-f]{1,4}:){1,1}(:[0-9a-f]{1,4}){1,6}\Z)|
(\A([0-9a-f]{1,4}:){1,2}(:[0-9a-f]{1,4}){1,5}\Z)|
(\A([0-9a-f]{1,4}:){1,3}(:[0-9a-f]{1,4}){1,4}\Z)|
(\A([0-9a-f]{1,4}:){1,4}(:[0-9a-f]{1,4}){1,3}\Z)|
(\A([0-9a-f]{1,4}:){1,5}(:[0-9a-f]{1,4}){1,2}\Z)|
(\A([0-9a-f]{1,4}:){1,6}(:[0-9a-f]{1,4}){1,1}\Z)|
(\A(([0-9a-f]{1,4}:){1,7}|:):\Z)|
(\A:(:[0-9a-f]{1,4}){1,7}\Z)|
(\A((([0-9a-f]{1,4}:){6})(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3})\Z)|
(\A(([0-9a-f]{1,4}:){5}[0-9a-f]{1,4}:(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3})\Z)|
(\A([0-9a-f]{1,4}:){5}:[0-9a-f]{1,4}:(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\Z)|
(\A([0-9a-f]{1,4}:){1,1}(:[0-9a-f]{1,4}){1,4}:(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\Z)|
(\A([0-9a-f]{1,4}:){1,2}(:[0-9a-f]{1,4}){1,3}:(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\Z)|
(\A([0-9a-f]{1,4}:){1,3}(:[0-9a-f]{1,4}){1,2}:(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\Z)|
(\A([0-9a-f]{1,4}:){1,4}(:[0-9a-f]{1,4}){1,1}:(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\Z)|
(\A(([0-9a-f]{1,4}:){1,5}|:):(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\Z)|
(\A:(:[0-9a-f]{1,4}){1,5}:(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\Z)

Arithmetic overflow error converting numeric to data type numeric

Use TRY_CAST function in exact same way of CAST function. TRY_CAST takes a string and tries to cast it to a data type specified after the AS keyword. If the conversion fails, TRY_CAST returns a NULL instead of failing.

MD5 hashing in Android

MD5 is a bit old, SHA-1 is a better algorithm, there is a example here.

(Also as they note in that post, Java handles this on it's own, no Android specific code.)

C# generic list <T> how to get the type of T?

Given an object which I suspect to be some kind of IList<>, how can I determine of what it's an IList<>?

Here's a reliable solution. My apologies for length - C#'s introspection API makes this suprisingly difficult.

/// <summary>
/// Test if a type implements IList of T, and if so, determine T.
/// </summary>
public static bool TryListOfWhat(Type type, out Type innerType)
{
    Contract.Requires(type != null);

    var interfaceTest = new Func<Type, Type>(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>) ? i.GetGenericArguments().Single() : null);

    innerType = interfaceTest(type);
    if (innerType != null)
    {
        return true;
    }

    foreach (var i in type.GetInterfaces())
    {
        innerType = interfaceTest(i);
        if (innerType != null)
        {
            return true;
        }
    }

    return false;
}

Example usage:

    object value = new ObservableCollection<int>();
Type innerType;
TryListOfWhat(value.GetType(), out innerType).Dump();
innerType.Dump();

Returns

True
typeof(Int32)

Write string to text file and ensure it always overwrites the existing content.

System.IO.File.WriteAllText (@"D:\path.txt", contents);
  • If the file exists, this overwrites it.
  • If the file does not exist, this creates it.
  • Please make sure you have appropriate privileges to write at the location, otherwise you will get an exception.

How to recover a dropped stash in Git?

You can list all unreachable commits by writing this command in terminal -

git fsck --unreachable

Check unreachable commit hash -

git show hash

Finally apply if you find the stashed item -

git stash apply hash

How to print the current time in a Batch-File?

Not sure if your question was answered.

This will write the time & date every 20 seconds in the file ping_ip.txt. The second to last line just says run the same batch file again, and agan, and again,..........etc.

Does not seem to create multiple instances, so that's a good thing.

@echo %time% %date% >>ping_ip.txt
ping -n 20 -w 3 127.0.0.1 >>ping_ip.txt
This_Batch_FileName.bat
cls

SQL Server: the maximum number of rows in table

I don't know MSSQL specifically, but 36 million rows is not large to an enterprise database - working with mainframe databases, 100,000 rows sounds like a configuration table to me :-).

While I'm not a big fan of some of Microsoft's software, this isn't Access we're talking about here: I assume they can handle pretty substantial database sizes with their enterprise DBMS.

I suspect days may have been too fine a resolution to divide it up, if indeed it needs dividing at all.

What is this Javascript "require"?

So what is this "require?"

require() is not part of the standard JavaScript API. But in Node.js, it's a built-in function with a special purpose: to load modules.

Modules are a way to split an application into separate files instead of having all of your application in one file. This concept is also present in other languages with minor differences in syntax and behavior, like C's include, Python's import, and so on.

One big difference between Node.js modules and browser JavaScript is how one script's code is accessed from another script's code.

  • In browser JavaScript, scripts are added via the <script> element. When they execute, they all have direct access to the global scope, a "shared space" among all scripts. Any script can freely define/modify/remove/call anything on the global scope.

  • In Node.js, each module has its own scope. A module cannot directly access things defined in another module unless it chooses to expose them. To expose things from a module, they must be assigned to exports or module.exports. For a module to access another module's exports or module.exports, it must use require().

In your code, var pg = require('pg'); loads the pg module, a PostgreSQL client for Node.js. This allows your code to access functionality of the PostgreSQL client's APIs via the pg variable.

Why does it work in node but not in a webpage?

require(), module.exports and exports are APIs of a module system that is specific to Node.js. Browsers do not implement this module system.

Also, before I got it to work in node, I had to do npm install pg. What's that about?

NPM is a package repository service that hosts published JavaScript modules. npm install is a command that lets you download packages from their repository.

Where did it put it, and how does Javascript find it?

The npm cli puts all the downloaded modules in a node_modules directory where you ran npm install. Node.js has very detailed documentation on how modules find other modules which includes finding a node_modules directory.

Android SharedPreferences in Fragment

getActivity() and onAttach() didnot help me in same situation
maybe I did something wrong
but! I found another decision
I have created a field Context thisContext inside my Fragment
And got a current context from method onCreateView
and now I can work with shared pref from fragment

public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {   
...   
thisContext = container.getContext();   
...   
}

VBA test if cell is in a range

Here is another option to see if a cell exists inside a range. In case you have issues with the Intersect solution as I did.

If InStr(range("NamedRange").Address, range("IndividualCell").Address) > 0 Then
    'The individual cell exists in the named range
Else
    'The individual cell does not exist in the named range
End If

InStr is a VBA function that checks if a string exists within another string.

https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/instr-function

How to match, but not capture, part of a regex?

Try this:

/\d{3}-(?:(apple|banana)-)?\d{3}/

element with the max height from a set of elements

Use .map() and Math.max.

var maxHeight = Math.max.apply(null, $("div.panel").map(function ()
{
    return $(this).height();
}).get());

If that's confusing to read, this might be clearer:

var heights = $("div.panel").map(function ()
    {
        return $(this).height();
    }).get();

maxHeight = Math.max.apply(null, heights);

JavaFX How to set scene background image

In addition to @Elltz answer, we can use both fill and image for background:

someNode.setBackground(
            new Background(
                    Collections.singletonList(new BackgroundFill(
                            Color.WHITE, 
                            new CornerRadii(500), 
                            new Insets(10))),
                    Collections.singletonList(new BackgroundImage(
                            new Image("image/logo.png", 100, 100, false, true),
                            BackgroundRepeat.NO_REPEAT,
                            BackgroundRepeat.NO_REPEAT,
                            BackgroundPosition.CENTER,
                            BackgroundSize.DEFAULT))));

Use

setBackground(
                new Background(
                        Collections.singletonList(new BackgroundFill(
                                Color.WHITE,
                                new CornerRadii(0),
                                new Insets(0))),
                        Collections.singletonList(new BackgroundImage(
                                new Image("file:clouds.jpg", 100, 100, false, true),
                                BackgroundRepeat.NO_REPEAT,
                                BackgroundRepeat.NO_REPEAT,
                                BackgroundPosition.DEFAULT,
                                new BackgroundSize(1.0, 1.0, true, true, false, false)
                        ))));

(different last argument) to make the image full-window size.

How can I view an old version of a file with Git?

If you like GUIs, you can use gitk:

  1. start gitk with:

    gitk /path/to/file
    
  2. Choose the revision in the top part of the screen, e.g. by description or date. By default, the lower part of the screen shows the diff for that revision, (corresponding to the "patch" radio button).

  3. To see the file for the selected revision:

    • Click on the "tree" radio button. This will show the root of the file tree at that revision.
    • Drill down to your file.

Brackets.io: Is there a way to auto indent / format <html>

The Identator plugin works to me in Brackets Release 1.13 versión 1.13.0-17696 (release 49d29a8bc) on S.O. Windows 10

How do I give text or an image a transparent background using CSS?

For a simple semi-transparent background color, the above solutions (CSS3 or bg images) are the best options. However, if you want to do something fancier (e.g. animation, multiple backgrounds, etc.), or if you don't want to rely on CSS3, you can try the “pane technique”:

.pane, .pane > .back, .pane > .cont { display: block; }

.pane {
    position: relative;
}

.pane > .back {
    position: absolute;
    width: 100%; height: 100%;
    top: auto; bottom: auto; left: auto; right: auto;
}

.pane > .cont {
    position: relative;
    z-index: 10;
}
<p class="pane">
    <span class="back" style="background-color: green; opacity: 0.6;"></span>
    <span class="cont" style="color: white;">Hello world</span>
</p>

The technique works by using two “layers” inside of the outer pane element:

  • one (the “back”) that fits the size of the pane element without affecting the flow of content,
  • and one (the “cont”) that contains the content and helps determine the size of the pane.

The position: relative on pane is important; it tells back layer to fit to the pane's size. (If you need the <p> tag to be absolute, change the pane from a <p> to a <span> and wrap all that in a absolutely-position <p> tag.)

The main advantage this technique has over similar ones listed above is that the pane doesn't have to be a specified size; as coded above, it will fit full-width (normal block-element layout) and only as high as the content. The outer pane element can be sized any way you please, as long as it's rectangular (i.e. inline-block will work; plain-old inline will not).

Also, it gives you a lot of freedom for the background; you're free to put really anything in the back element and have it not affect the flow of content (if you want multiple full-size sub-layers, just make sure they also have position: absolute, width/height: 100%, and top/bottom/left/right: auto).

One variation to allow background inset adjustment (via top/bottom/left/right) and/or background pinning (via removing one of the left/right or top/bottom pairs) is to use the following CSS instead:

.pane > .back {
    position: absolute;
    width: auto; height: auto;
    top: 0px; bottom: 0px; left: 0px; right: 0px;
}

As written, this works in Firefox, Safari, Chrome, IE8+, and Opera, although IE7 and IE6 require extra CSS and expressions, IIRC, and last time I checked, the second CSS variation does not work in Opera.

Things to watch out for:

  • Floating elements inside of the cont layer will not be contained. You'll need to make sure they are cleared or otherwise contained, or they'll slip out of the bottom.
  • Margins go on the pane element and padding goes on the cont element. Don't do use the opposite (margins on the cont or padding on the pane) or you'll discover oddities such as the page always being slightly wider than the browser window.
  • As mentioned, the whole thing needs to be block or inline-block. Feel free to use <div>s instead of <span>s to simplify your CSS.

A fuller demo, showing off the flexiblity of this technique by using it in tandem with display: inline-block, and with both auto & specific widths/min-heights:

_x000D_
_x000D_
.pane, .pane > .back, .pane > .cont { display: block; }_x000D_
.pane {_x000D_
 position: relative;_x000D_
 width: 175px; min-height: 100px;_x000D_
 margin: 8px;_x000D_
}_x000D_
_x000D_
.pane > .back {_x000D_
 position: absolute; z-index: 1;_x000D_
 width: auto; height: auto;_x000D_
 top: 8px; bottom: 8px; left: 8px; right: 8px;_x000D_
}_x000D_
_x000D_
.pane > .cont {_x000D_
 position: relative; z-index: 10;_x000D_
}_x000D_
_x000D_
.debug_red { background: rgba(255, 0, 0, 0.5); border: 1px solid rgba(255, 0, 0, 0.75); }_x000D_
.debug_green { background: rgba(0, 255, 0, 0.5); border: 1px solid rgba(0, 255, 0, 0.75); }_x000D_
.debug_blue { background: rgba(0, 0, 255, 0.5); border: 1px solid rgba(0, 0, 255, 0.75); }
_x000D_
<p class="pane debug_blue" style="float: left;">_x000D_
 <span class="back debug_green"></span>_x000D_
 <span class="cont debug_red">_x000D_
  Pane content.<br/>_x000D_
  Pane content._x000D_
 </span>_x000D_
</p>_x000D_
<p class="pane debug_blue" style="float: left;">_x000D_
 <span class="back debug_green"></span>_x000D_
 <span class="cont debug_red">_x000D_
  Pane content.<br/>_x000D_
  Pane content.<br/>_x000D_
  Pane content.<br/>_x000D_
  Pane content.<br/>_x000D_
  Pane content.<br/>_x000D_
  Pane content.<br/>_x000D_
  Pane content.<br/>_x000D_
  Pane content.<br/>_x000D_
  Pane content._x000D_
 </span>_x000D_
</p>_x000D_
<p class="pane debug_blue" style="float: left; display: inline-block; width: auto;">_x000D_
 <span class="back debug_green"></span>_x000D_
 <span class="cont debug_red">_x000D_
  Pane content.<br/>_x000D_
  Pane content._x000D_
 </span>_x000D_
</p>_x000D_
<p class="pane debug_blue" style="float: left; display: inline-block; width: auto; min-height: auto;">_x000D_
 <span class="back debug_green"></span>_x000D_
 <span class="cont debug_red">_x000D_
  Pane content.<br/>_x000D_
  Pane content._x000D_
 </span>_x000D_
</p>
_x000D_
_x000D_
_x000D_

And here's a live demo of the technique being used extensively:

christmas-card-2009.slippyd.com screenshot

Read from file in eclipse

you just need to get the absolute-path of the file, since the file you are looking for doesnt exist in the eclipse's runtime workspace you can use - getProperty() or getLocationURI() methods to get the absolute-path of the file

How do I get the max and min values from a set of numbers entered?

here you need to skip int 0 like following:

val = s.nextInt();
  if ((val < min) && (val!=0)) {
      min = val;
  }

How to position the form in the center screen?

Try using this:

this.setBounds(x,y,w,h);

How can I pipe stderr, and not stdout?

You can use the rc shell.

First install the package (it's less than 1 MB).

This an example of how you would discard standard output and pipe standard error to grep in rc:

find /proc/ >[1] /dev/null |[2] grep task

You can do it without leaving Bash:

rc -c 'find /proc/ >[1] /dev/null |[2] grep task'

As you may have noticed, you can specify which file descriptor you want piped by using brackets after the pipe.

Standard file descriptors are numerated as such:

  • 0 : Standard input
  • 1 : Standard output
  • 2 : Standard error

How to put an image in div with CSS?

Take this as a sample code. Replace imageheight and image width with your image dimensions.

<div style="background:yourimage.jpg no-repeat;height:imageheight px;width:imagewidth px">
</div>

How can I set the maximum length of 6 and minimum length of 6 in a textbox?

You can't set a minimum length on a text field. Otherwise, users wouldn't be able to type in the first five characters.

Your best bet is to validate the input when the form is submitted to ensure that the length is six.

maxlength is not a validation attribute. It is designed to prevent the user from physically typing in more than six characters. The corresponding minlengh is not in scope of the HTML specification, because its implementation would render the textbox unusable.

Scala best way of turning a Collection into a Map-by-key?

How about using zip and toMap?

myList.zip(myList.map(_.length)).toMap

What does "javax.naming.NoInitialContextException" mean?

Just read the docs:

This exception is thrown when no initial context implementation can be created. The policy of how an initial context implementation is selected is described in the documentation of the InitialContext class.

This exception can be thrown during any interaction with the InitialContext, not only when the InitialContext is constructed. For example, the implementation of the initial context might lazily retrieve the context only when actual methods are invoked on it. The application should not have any dependency on when the existence of an initial context is determined.

But this is explained much better in the docs for InitialContext

redirect COPY of stdout to log file from within bash script itself

Using the accepted answer my script kept returning exceptionally early (right after 'exec > >(tee ...)') leaving the rest of my script running in the background. As I couldn't get that solution to work my way I found another solution/work around to the problem:

# Logging setup
logfile=mylogfile
mkfifo ${logfile}.pipe
tee < ${logfile}.pipe $logfile &
exec &> ${logfile}.pipe
rm ${logfile}.pipe

# Rest of my script

This makes output from script go from the process, through the pipe into the sub background process of 'tee' that logs everything to disc and to original stdout of the script.

Note that 'exec &>' redirects both stdout and stderr, we could redirect them separately if we like, or change to 'exec >' if we just want stdout.

Even thou the pipe is removed from the file system in the beginning of the script it will continue to function until the processes finishes. We just can't reference it using the file name after the rm-line.

How to get Linux console window width in Python

Here is an version that should be Linux and Solaris compatible. Based on the posts and commments from madchine. Requires the subprocess module.

def termsize():
    import shlex, subprocess, re
    output = subprocess.check_output(shlex.split('/bin/stty -a'))
    m = re.search('rows\D+(?P\d+); columns\D+(?P\d+);', output)
    if m:
        return m.group('rows'), m.group('columns')
    raise OSError('Bad response: %s' % (output))
>>> termsize()
('40', '100')

Why ModelState.IsValid always return false in mvc

"ModelState.IsValid" tells you that the model is consumed by the view (i.e. PaymentAdviceEntity) is satisfy all types of validation or not specified in the model properties by DataAnotation.

In this code the view does not bind any model properties. So if you put any DataAnotations or validation in model (i.e. PaymentAdviceEntity). then the validations are not satisfy. say if any properties in model is Name which makes required in model.Then the value of the property remains blank after post.So the model is not valid (i.e. ModelState.IsValid returns false). You need to remove the model level validations.

Change the background color in a twitter bootstrap modal?

remove bootstrap modal background try this one

.modal-backdrop {
   background: none;
}

How do I pass a value from a child back to the parent form?

Many ways to skin the cat here and @Mitch's suggestion is a good way. If you want the client form to have more 'control', you may want to pass the instance of the parent to the child when created and then you can call any public parent method on the child.

What does a (+) sign mean in an Oracle SQL WHERE clause?

This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.

In standard SQL one would write:

SELECT t0.foo, t1.bar
  FROM FIRST_TABLE t0
 RIGHT OUTER JOIN SECOND_TABLE t1;

Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]

Organizing a multiple-file Go project

Let's explorer how the go get repository_remote_url command manages the project structure under $GOPATH. If we do a go get github.com/gohugoio/hugo It will clone the repository under

$GOPATH/src/repository_remote/user_name/project_name


$GOPATH/src/github.com/gohugoio/hugo

This is a nice way to create your initial project path. Now let's explorer what are the project types out there and how their inner structures are organized. All golang projects in the community can be categorized under

  • Libraries (no executable binaries)
  • Single Project (contains only 1 executable binary)
  • Tooling Projects (contains multiple executable binaries)

Generally golang project files can be packaged under any design principles such as DDD, POD

Most of the available go projects follows this Package Oriented Design

Package Oriented Design encourage the developer to keeps the implementation only inside it's own packages, other than the /internal package those packages can't can communicate with each other


Libraries

  • Projects such as database drivers, qt can put under this category.
  • Some libraries such as color, now follows a flat structure without any other packages.
  • Most of these library projects manages a package called internal.
  • /internal package is mainly used to hide the implementation from other projects.
  • Don't have any executable binaries, so no files that contains the main func.

 ~/$GOPATH/
    bin/
    pkg/
    src/
      repository_remote/
        user_name/
            project_name/
              internal/
              other_pkg/

Single Project

  • Projects such as hugo, etcd has a single main func in root level and.
  • Target is to generate one single binary

Tooling Projects

  • Projects such as kubernetes, go-ethereum has multiple main func organized under a package called cmd
  • cmd/ package manages the number of binaries (tools) that we want to build

 ~/$GOPATH/
    bin/
    pkg/
    src/
      repository_remote/
        user_name/
            project_name/
              cmd/
                binary_one/
                   main.go
                binary_two/
                   main.go
                binary_three/
                   main.go
              other_pkg/

Cannot read property 'length' of null (javascript)

From the code that you have provided, not knowing the language that you are programming in. The variable capital is null. When you are trying to read the property length, the system cant as it is trying to deference a null variable. You need to define capital.

keypress, ctrl+c (or some combo like that)

Simple way to do it in jQuery :

/* The elements we'll bind the shortcut keys to. */
var elements = "body, input, select, checkbox, textarea";

/* Bind the key short-cut 'Ctrl+S' to the save function. */
$(elements).bind ("keydown", "ctrl+space", function (e) {
    // Prevent the default operation.
    e.preventDefault ();
    // Stop processing if we're already doing something.
    console.log ("That's right , you pressed correct shortcut!");
});

String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?

If you really want to match only the dot, then StringComparison.Ordinal would be fastest, as there is no case-difference.

"Ordinal" doesn't use culture and/or casing rules that are not applicable anyway on a symbol like a ..

.NET data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?

There are subtle and not-so-subtle differences between generic and non-generic collections. They merely use different underlying data structures. For example, Hashtable guarantees one-writer-many-readers without sync. Dictionary does not.

Angular.js programmatically setting a form field to dirty

If you have access to the NgModelController (you can only get access to it from a directive) then you can call

ngModel.$setViewValue("your new view value");
// or to keep the view value the same and just change it to dirty
ngModel.$setViewValue(ngModel.$viewValue);

Clear a terminal screen for real

Try reset. It clears up the terminal screen but the previous commands can be accessed through arrow or whichever key binding you have.

Matplotlib scatter plot with different text at each data point

In case anyone is trying to apply the above solutions to a .scatter() instead of a .subplot(),

I tried running the following code

y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
z = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123]

fig, ax = plt.scatter(z, y)

for i, txt in enumerate(n):
    ax.annotate(txt, (z[i], y[i]))

But ran into errors stating "cannot unpack non-iterable PathCollection object", with the error specifically pointing at codeline fig, ax = plt.scatter(z, y)

I eventually solved the error using the following code

plt.scatter(z, y)

for i, txt in enumerate(n):
    plt.annotate(txt, (z[i], y[i]))

I didn't expect there to be a difference between .scatter() and .subplot() I should have known better.

How to detect when a UIScrollView has finished scrolling

Using Ashley Smart logic and is being converted into Swift 4.0 and above.

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
         NSObject.cancelPreviousPerformRequests(withTarget: self)
        perform(#selector(UIScrollViewDelegate.scrollViewDidEndScrollingAnimation(_:)), with: scrollView, afterDelay: 0.3)
    }

    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        NSObject.cancelPreviousPerformRequests(withTarget: self)
    }

The logic above solve issues such as when user is scrolling off the tableview. Without the logic, when you scroll off the tableview, didEnd will be called but it will not execute anything. Currently using it in year 2020.

Controller 'ngModel', required by directive '...', can't be found

One possible solution to this issue is ng-model attribute is required to use that directive.

Hence adding in the 'ng-model' attribute can resolve the issue.

<input submit-required="true" ng-model="user.Name"></input>

How to fix Error: laravel.log could not be opened?

Fixed my problem with this command in centos 7.6 Server

chcon -R -t httpd_sys_content_t $SITE_PATH

chcon -R -t httpd_sys_rw_content_t $SITE_PATH

Oracle SQL Developer: Unable to find a JVM

The Oracle SQL developer is not supported by the 64bit JDK. To resolve this issue:

  1. Install a 32bit JDK (x86)
  2. Update your SQL developer config file (It should now point to the new 32bit JDK).
  3. Edit the sqldeveloper.conf, which can be found under {ORACLE_HOME}\sqldeveloper\sqldeveloper\bin\sqldeveloper.conf
  4. Make sure SetJavaHome is pointing to your 32bit JDK.

For example:

SetJavaHome C:\Program Files (x86) \Java\jdk1.6.0_13

How to generate random float number in C

If you want to generate a random float in a range, try a next solution.

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


float
random_float(const float min, const float max)
{
    if (max == min) return min;
    else if (min < max) return (max - min) * ((float)rand() / RAND_MAX) + min;

    // return 0 if min > max
    return 0;
}


int
main (const int argc, const char *argv[])
{
    srand(time(NULL));

    char line[] = "-------------------------------------------";

    float data[10][2] = {
        {-10, 10},
        {-5., 5},
        {-1, 1},
        {-0.25, -0.15},
        {1.5, 1.52},
        {-1700, 8000},
        {-0.1, 0.1},
        {-1, 0},
        {-1, -2},
        {1.2, 1.1}
    };

    puts(line);
    puts("     From    |    Result    |      To");
    puts(line);


    int i;
    for (i = 0; i < 10; ++i) {
        printf("%12f | %12f | %12f\n", data[i][0], random_float(data[i][0], data[i][1]), data[i][1]);
    }

    puts(line);

    return 0;
}

A result (values is fickle)

-------------------------------------------
     From    |    Result    |      To
-------------------------------------------
  -10.000000 |     2.330828 |    10.000000
   -5.000000 |    -4.945523 |     5.000000
   -1.000000 |     0.004242 |     1.000000
   -0.250000 |    -0.203197 |    -0.150000
    1.500000 |     1.513431 |     1.520000
-1700.000000 |  3292.941895 |  8000.000000
   -0.100000 |    -0.021541 |     0.100000
   -1.000000 |    -0.148299 |     0.000000
   -1.000000 |     0.000000 |    -2.000000
    1.200000 |     0.000000 |     1.100000
-------------------------------------------

Importing a csv into mysql via command line

For importing csv with a header row using mysqlimport, just add

--ignore-lines=N

(ignores the first N lines of the data file)

This option is described in the page you've linked.

How to delete a localStorage item when the browser window/tab is closed?

You can make use of the beforeunload event in JavaScript.

Using vanilla JavaScript you could do something like:

window.onbeforeunload = function() {
  localStorage.removeItem(key);
  return '';
};

That will delete the key before the browser window/tab is closed and prompts you to confirm the close window/tab action. I hope that solves your problem.

NOTE: The onbeforeunload method should return a string.

mean() warning: argument is not numeric or logical: returning NA

The same error appears if you do not use the correct (numeric) format of your data in your data.frame column using mean() function. Therefore, check your data using str(data.frame&column) function to see what data type you have, and convert it to numeric format if necessary. For example, if your data is Character convert it with as.numeric(data.frame$column), or as a factor with as.numeric(as.character(data.frame$column)). The mean function does not work with types other than numeric.

Error in Python IOError: [Errno 2] No such file or directory: 'data.csv'

open looks in the current working directory, which in your case is ~, since you are calling your script from the ~ directory.

You can fix the problem by either

  • cding to the directory containing data.csv before executing the script, or

  • by using the full path to data.csv in your script, or

  • by calling os.chdir(...) to change the current working directory from within your script. Note that all subsequent commands that use the current working directory (e.g. open and os.listdir) may be affected by this.

Spring data JPA query with parameter properties

You can try something like this:

public interface PersonRepository extends CrudRepository<Person, Long> {
       @Query("select p from Person AS p"
       + " ,Name AS n"  
       + " where p.forename = n.forename "
       + " and p.surname = n.surname"
       + " and n = :name")
       Set<Person>findByName(@Param("name") Name name);
    }

Filter Extensions in HTML form upload

I wouldnt use this attribute as most browsers ignore it as CMS points out.

By all means use client side validation but only in conjunction with server side. Any client side validation can be got round.

Slightly off topic but some people check the content type to validate the uploaded file. You need to be careful about this as an attacker can easily change it and upload a php file for example. See the example at: http://www.scanit.be/uploads/php-file-upload.pdf

Python time measure function

Elaborating on @Jonathan Ray I think this does the trick a bit better

import time
import inspect

def timed(f:callable):
    start = time.time()
    ret = f()
    elapsed = 1000*(time.time() - start)
    source_code=inspect.getsource(f).strip('\n') 
    logger.info(source_code+":  "+str(elapsed)+" seconds")
    return ret

It allows to take a regular line of code, say a = np.sin(np.pi) and transform it rather simply into

a = timed(lambda: np.sin(np.pi))

so that the timing is printed onto the logger and you can keep the same assignment of the result to a variable you might need for further work.

I suppose in Python 3.8 one could use the := but I do not have 3.8 yet

Oracle Insert via Select from multiple tables where one table may not have a row

Outter joins don't work "as expected" in that case because you have explicitly told Oracle you only want data if that criteria on that table matches. In that scenario, the outter join is rendered useless.

A work-around

INSERT INTO account_type_standard 
  (account_type_Standard_id, tax_status_id, recipient_id) 
VALUES( 
  (SELECT account_type_standard_seq.nextval FROM DUAL),
  (SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?), 
  (SELECT recipient_id FROM recipient WHERE recipient_code = ?)
)

[Edit] If you expect multiple rows from a sub-select, you can add ROWNUM=1 to each where clause OR use an aggregate such as MAX or MIN. This of course may not be the best solution for all cases.

[Edit] Per comment,

  (SELECT account_type_standard_seq.nextval FROM DUAL),

can be just

  account_type_standard_seq.nextval,

How do you add input from user into list in Python

shopList = [] 
maxLengthList = 6
while len(shopList) < maxLengthList:
    item = input("Enter your Item to the List: ")
    shopList.append(item)
    print shopList
print "That's your Shopping List"
print shopList

jQuery: how to scroll to certain anchor/div on page load?

Just append #[id of the div you want to scroll to] to your page url. For example, if I wanted to scroll to the copyright section of this stackoverflow question, the URL would change from

http://stackoverflow.com/questions/9757625/jquery-how-to-scroll-to-certain-anchor-div-on-page-load

to

http://stackoverflow.com/questions/9757625/jquery-how-to-scroll-to-certain-anchor-div-on-page-load#copyright

notice the #copyright at the end of the URL.

C++ passing an array pointer as a function argument

This is another method . Passing array as a pointer to the function
void generateArray(int *array,  int size) {
    srand(time(0));
    for (int j=0;j<size;j++)
        array[j]=(0+rand()%9);
}

int main(){
    const int size=5;
    int a[size];
    generateArray(a, size);
    return 0;
}

List of enum values in java

tl;dr

Can you make and edit a collection of objects from an enum? Yes.

If you do not care about the order, use EnumSet, an implementation of Set.

enum Animal{ DOG , CAT , BIRD , BAT ; }

Set<Animal> flyingAnimals = EnumSet.of( BIRD , BAT );

Set<Animal> featheredFlyingAnimals = flyingAnimals.clone().remove( BAT ) ;

If you care about order, use a List implementation such as ArrayList. For example, we can create a list of a person’s preference in choosing a pet, in the order of their most preferred.

List< Animal > favoritePets = new ArrayList<>() ;
favoritePets.add( CAT ) ;  // This person prefers cats over dogs…
favoritePets.add( DOG ) ;  // …but would accept either.
                           // This person would not accept a bird nor a bat.

For a non-modifiable ordered list, use List.of.

List< Animal > favoritePets = List.of( CAT , DOG ) ;  // This person prefers cats over dogs, but would accept either. This person would not accept a bird nor a bat. 

Details

The Answer (EnumSet) by Amit Deshpande and the Answer (.values) by Marko Topolnik are both correct. Here is a bit more info.

Enum.values

The .values() method is an implicitly declared method on Enum, added by the compiler. It produces a crude array rather than a Collection. Certainly usable.

Special note about documentation: Being unusual as an implicitly declared method, the .values() method is not listed among the methods on the Enum class. The method is defined in the Java Language Specification, and is mentioned in the doc for Enum.valueOf.

EnumSet – Fast & Small

The upsides to EnumSet include:

  • Extreme speed.
  • Compact use of memory.

To quote the class doc:

Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags." Even bulk operations (such as containsAll and retainAll) should run very quickly if their argument is also an enum set.

Given this enum:

enum Animal
{
    DOG , CAT , BIRD , BAT ;
}

Make an EnumSet in one line.

Set<Animal> allAnimals = EnumSet.allOf( Animal.class );

Dump to console.

System.out.println( "allAnimals : " + allAnimals );

allAnimals : [DOG, CAT, BIRD, BAT]

Make a set from a subset of the enum objects.

Set<Animal> flyingAnimals = EnumSet.of( BIRD , BAT );

Look at the class doc to see many ways to manipulate the collection including adding or removing elements.

Set<Animal> featheredFlyingAnimals = 
    EnumSet.copyOf( flyingAnimals ).remove( BAT );

Natural Order

The doc promises the Iterator for EnumSet is in natural order, the order in which the values of the enum were originally declared.

To quote the class doc:

The iterator returned by the iterator method traverses the elements in their natural order (the order in which the enum constants are declared).

Frankly, given this promise, I'm confused why this is not a SortedSet. But, oh well, good enough. We can create a List from the Set if desired. Pass any Collection to constructor of ArrayList and that collection’s Iterator is automatically called on your behalf.

List<Animal> list = new ArrayList<>( allAnimals );

Dump to console.

System.out.println("list : " + list );

When run.

list : [DOG, CAT, BIRD, BAT]

In Java 10 and later, you can conveniently create a non-modifiable List by passing the EnumSet. The order of the new list will be in the iterator order of the EnumSet. The iterator order of an EnumSet is the order in which the element objects of the enum were defined on that enum.

List< Animal > nonModList = List.copyOf( allAnimals ) ;  // Or pass Animals.values() 

Right to Left support for Twitter Bootstrap 3

Bootstrap Persian version of the site http://rbootstrap.ir/ Ver.2.3.2

How to create JSON string in JavaScript?

The way i do it is:

   var obj = new Object();
   obj.name = "Raj";
   obj.age  = 32;
   obj.married = false;
   var jsonString= JSON.stringify(obj);

I guess this way can reduce chances for errors.

Pandas read in table without headers

In order to read a csv in that doesn't have a header and for only certain columns you need to pass params header=None and usecols=[3,6] for the 4th and 7th columns:

df = pd.read_csv(file_path, header=None, usecols=[3,6])

See the docs

Psql could not connect to server: No such file or directory, 5432 error?

If non of the above answers are not working for you, then please try this one,

Many people have mentioned many solutions to this problem! But all of them forgot that, the same problem will arise when your disk don't have enough space or the space you are assigned for postgres is full

Check your system storage, if its full free up some space! then restart your postgres by sudo service postgresql restart or do a stop and start sudo service posgresql stop then sudo service postgresql start

This will solve the issue, it solved for me

form_for but to post to a different action

form_for @user, :url => url_for(:controller => 'mycontroller', :action => 'myaction')

or

form_for @user, :url => whatever_path

set the width of select2 input (through Angular-ui directive)

This is an old question but new info is still worth posting...

Starting with Select2 version 3.4.0 there is an attribute dropdownAutoWidth which solves the problem and handles all the odd cases. Note it is not on by default. It resizes dynamically as the user makes selections, it adds width for allowClear if that attribute is used, and it handles placeholder text properly too.

$("#some_select_id").select2({
    dropdownAutoWidth : true
});

How do I disable form resizing for users?

Change the FormBorderStyle to one of the fixed values: FixedSingle, Fixed3D, FixedDialog or FixedToolWindow.

The FormBorderStyle property is under the Appearance category.

Or check this:

// Define the border style of the form to a dialog box.
form1.FormBorderStyle = FormBorderStyle.FixedDialog;

// Set the MaximizeBox to false to remove the maximize box.
form1.MaximizeBox = false;

// Set the MinimizeBox to false to remove the minimize box.
form1.MinimizeBox = false;

// Set the start position of the form to the center of the screen.
form1.StartPosition = FormStartPosition.CenterScreen;

// Display the form as a modal dialog box.
form1.ShowDialog();

How to parse XML using jQuery?

First thing that pop-up in google results http://think2loud.com/224-reading-xml-with-jquery/ There's no simple way to access xml structure (like you described Pages->pagename->controls->test) in jQuery without any plugins.

How much data / information can we save / store in a QR code?

See this table.

A 101x101 QR code, with high level error correction, can hold 3248 bits, or 406 bytes. Probably not enough for any meaningful SVG/XML data.

A 177x177 grid, depending on desired level of error correction, can store between 1273 and 2953 bytes. Maybe enough to store something small.

enter image description here

Merge or combine by rownames

cbind.fill <- function(x, y){
  xrn <- rownames(x)
  yrn <- rownames(y)
  rn <- union(xrn, yrn)
  xcn <- colnames(x)
  ycn <- colnames(y)
  if(is.null(xrn) | is.null(yrn) | is.null(xcn) | is.null(ycn)) 
    stop("NULL rownames or colnames")
  z <- matrix(NA, nrow=length(rn), ncol=length(xcn)+length(ycn))
  rownames(z) <- rn
  colnames(z) <- c(xcn, ycn)
  idx <- match(rn, xrn)
  z[!is.na(idx), 1:length(xcn)] <- x[na.omit(idx),]
  idy <- match(rn, yrn)
  z[!is.na(idy), length(xcn)+(1:length(ycn))] <- y[na.omit(idy),]
  return(z)
}

Export a graph to .eps file with R

The easiest way I've found to create postscripts is the following, using the setEPS() command:

setEPS()
postscript("whatever.eps")
plot(rnorm(100), main="Hey Some Data")
dev.off()

Disable Buttons in jQuery Mobile

What seems to be needed is to actually define the button as a button widget.

I had the same problem (in beta 1)

I did

$("#submitButton").button();

in my window ready handler, after that it worked to do as it is said in the docs, i.e.:

$("#submitButton").button('disable'); 

I guess this has to do with that jqm is converting the markup, but isnt actually instatiating a real button widget for buttons and link buttons.

Difference between matches() and find() in Java Regex

matches(); does not buffer, but find() buffers. find() searches to the end of the string first, indexes the result, and return the boolean value and corresponding index.

That is why when you have a code like

1:Pattern.compile("[a-z]");

2:Pattern.matcher("0a1b1c3d4");

3:int count = 0;

4:while(matcher.find()){

5:count++: }

At 4: The regex engine using the pattern structure will read through the whole of your code (index to index as specified by the regex[single character] to find at least one match. If such match is found, it will be indexed then the loop will execute based on the indexed result else if it didn't do ahead calculation like which matches(); does not. The while statement would never execute since the first character of the matched string is not an alphabet.

UILabel with text of two different colors

NSAttributedString is the way to go. The following question has a great answer that shows you how to do it How do you use NSAttributedString

.datepicker('setdate') issues, in jQuery

Check that the date you are trying to set it to lies within the allowed date range if the minDate or maxDate options are set.

Unable to start Genymotion Virtual Device - Virtualbox Host Only Ethernet Adapter Failed to start

It seems your VirtualBox installation doesn't work correctly. You should try to reinstall/upgrade VirtualBox so that during the installation process it fixes this "Interface not found" issue.

Go to Matching Brace in Visual Studio?

On a Hungarian keyboard it is Ctrl + ú.

SQL query to find third highest salary in company

for oracle it goes like this:

select salary from employee where rownnum<=3 order by salary desc
minus
select salary from employee where rownnum<=2 order by salary desc;

Display progress bar while doing some work in C#?

And another example that BackgroundWorker is the right way to do it...

using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

namespace SerialSample
{
    public partial class Form1 : Form
    {
        private BackgroundWorker _BackgroundWorker;
        private Random _Random;

        public Form1()
        {
            InitializeComponent();
            _ProgressBar.Style = ProgressBarStyle.Marquee;
            _ProgressBar.Visible = false;
            _Random = new Random();

            InitializeBackgroundWorker();
        }

        private void InitializeBackgroundWorker()
        {
            _BackgroundWorker = new BackgroundWorker();
            _BackgroundWorker.WorkerReportsProgress = true;

            _BackgroundWorker.DoWork += (sender, e) => ((MethodInvoker)e.Argument).Invoke();
            _BackgroundWorker.ProgressChanged += (sender, e) =>
                {
                    _ProgressBar.Style = ProgressBarStyle.Continuous;
                    _ProgressBar.Value = e.ProgressPercentage;
                };
            _BackgroundWorker.RunWorkerCompleted += (sender, e) =>
            {
                if (_ProgressBar.Style == ProgressBarStyle.Marquee)
                {
                    _ProgressBar.Visible = false;
                }
            };
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            _BackgroundWorker.RunWorkerAsync(new MethodInvoker(() =>
                {
                    _ProgressBar.BeginInvoke(new MethodInvoker(() => _ProgressBar.Visible = true));
                    for (int i = 0; i < 1000; i++)
                    {
                        Thread.Sleep(10);
                        _BackgroundWorker.ReportProgress(i / 10);
                    }
                }));
        }
    }
}

How to get cookie's expire time

You can set your cookie value containing expiry and get your expiry from cookie value.

// set
$expiry = time()+3600;
setcookie("mycookie", "mycookievalue|$expiry", $expiry);

// get
if (isset($_COOKIE["mycookie"])) {
  list($value, $expiry) = explode("|", $_COOKIE["mycookie"]);
}

// Remember, some two-way encryption would be more secure in this case. See: https://github.com/qeremy/Cryptee

Is there any difference between a GUID and a UUID?

GUID has longstanding usage in areas where it isn't necessarily a 128-bit value in the same way as a UUID. For example, the RSS specification defines GUIDs to be any string of your choosing, as long as it's unique, with an "isPermalink" attribute to specify that the value you're using is just a permalink back to the item being syndicated.

How to make correct date format when writing data to Excel

Try this solution, in my softwarew work very well:

if (obj != null)
{
    if (obj is DateTime)
    {
        if (DateTime.MinValue == ((DateTime)obj))
        {

            xlWorkSheet.Cells[x,y] = String.Empty;

        }
        else
        {

            dynamic opp = ((DateTime)obj);
            xlWorkSheet.Cells[x,y] = (DateTime)opp;

        }
    }
}

How to set tint for an image view programmatically in android?

This worked for me

mImageView.setColorFilter(ContextCompat.getColor(getContext(), R.color.green_500));

What is console.log?

console.log has nothing to do with jQuery.

It logs a message to a debugging console, such as Firebug.

Calling a Sub and returning a value

You should be using a Property:

Private _myValue As String
Public Property MyValue As String
    Get
        Return _myValue
    End Get
    Set(value As String)
        _myValue = value
     End Set
End Property

Then use it like so:

MyValue = "Hello"
Console.write(MyValue)

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

Uninstall homebrew:

 ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"

Then reinstall

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Warning: This script will remove: /Library/Caches/Homebrew/ - thks benjaminsila

What should I do when 'svn cleanup' fails?

After going through most of the solutions that are cited here, I still was getting the error.

The issue was case insensitive OS X. Checking out a directory that has two files with the same name, but different capitalization causes an issue. For example, ApproximationTest.java and Approximationtest.java should not be in the same directory. As soon as we get rid of one of the file, the issue goes away.

How do I scroll the UIScrollView when the keyboard appears?

This is what I've been using. It's simple and it works well.

#pragma mark - Scrolling

-(void)scrollElement:(UIView *)view toPoint:(float)y
{
    CGRect theFrame = view.frame;
    float orig_y = theFrame.origin.y;
    float diff = y - orig_y;

    if (diff < 0) 
        [self scrollToY:diff];

    else 
        [self scrollToY:0];
}

-(void)scrollToY:(float)y
{
    [UIView animateWithDuration:0.3f animations:^{
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        self.view.transform = CGAffineTransformMakeTranslation(0, y);
    }];
}

Use the UITextField delegate call textFieldDidBeginEditing: to shift your view upwards, and also add a notification observer to return the view to normal when the keyboard hides:

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

    if (self.view.frame.origin.y == 0)
        [self scrollToY:-90.0];  // y can be changed to your liking

}

-(void)keyboardWillHide:(NSNotification*)note
{
    [self scrollToY:0];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

^ outside of the character class ("[a-zA-Z]") notes that it is the "begins with" operator.
^ inside of the character negates the specified class.

So, "^[a-zA-Z]" translates to "begins with character from a-z or A-Z", and "[^a-zA-Z]" translates to "is not either a-z or A-Z"

Here's a quick reference: http://www.regular-expressions.info/reference.html

How to update Python?

  • Official Python .msi installers are designed to replace:

    • any previous micro release (in x.y.z, z is "micro") because they are guaranteed to be backward-compatible and binary-compatible
    • a "snapshot" (built from source) installation with any micro version
  • A snapshot installer is designed to replace any snapshot with a lower micro version.

(See responsible code for 2.x, for 3.x)

Any other versions are not necessarily compatible and are thus installed alongside the existing one. If you wish to uninstall the old version, you'll need to do that manually. And also uninstall any 3rd-party modules you had for it:

  • If you installed any modules from bdist_wininst packages (Windows .exes), uninstall them before uninstalling the version, or the uninstaller might not work correctly if it has custom logic
  • modules installed with setuptools/pip that reside in Lib\site-packages can just be deleted afterwards
  • packages that you installed per-user, if any, reside in %APPDATA%/Python/PythonXY/site-packages and can likewise be deleted

Delegates in swift?

Simple Example:

protocol Work: class {
    func doSomething()
}

class Manager {
    weak var delegate: Work?
    func passAlong() {
        delegate?.doSomething()
    }
}

class Employee: Work {
    func doSomething() {
        print("Working on it")
    }
}

let manager = Manager()
let developer = Employee()
manager.delegate = developer
manager.passAlong() // PRINTS: Working on it

Difference between int32, int, int32_t, int8 and int8_t

The _t data types are typedef types in the stdint.h header, while int is an in built fundamental data type. This make the _t available only if stdint.h exists. int on the other hand is guaranteed to exist.

set pythonpath before import statements

As also noted in the docs here.
Go to Python X.X/Lib and add these lines to the site.py there,

import sys
sys.path.append("yourpathstring")

This changes your sys.path so that on every load, it will have that value in it..

As stated here about site.py,

This module is automatically imported during initialization. Importing this module will append site-specific paths to the module search path and add a few builtins.

For other possible methods of adding some path to sys.path see these docs

Most efficient way to remove special characters from string

It seems good to me. The only improvement I would make is to initialize the StringBuilder with the length of the string.

StringBuilder sb = new StringBuilder(str.Length);

T-SQL stored procedure that accepts multiple Id values

A superfast XML Method, if you want to use a stored procedure and pass the comma separated list of Department IDs :

Declare @XMLList xml
SET @XMLList=cast('<i>'+replace(@DepartmentIDs,',','</i><i>')+'</i>' as xml)
SELECT x.i.value('.','varchar(5)') from @XMLList.nodes('i') x(i))

All credit goes to Guru Brad Schulz's Blog