Programs & Examples On #Openvpn

Free software implementing virtual private networks (VPN). **Important:** This tag is exclusively for programming-related questions, NOT for general questions on configuring or using VPNs; questions about general network and server administration should be directed to Server Fault, and questions about general software use should be directed to Super User.

OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use

It seems to me you are using the wrong version...

TAP-Win32 should not be installed on the 64bit version. Download the right one and try again!

cmake - find_library - custom library location

Use CMAKE_PREFIX_PATH by adding multiple paths (separated by semicolons and no white spaces). You can set it as an environmental variable to avoid having absolute paths in your cmake configuration files

Notice that cmake will look for config file in any of the following folders where is any of the path in CMAKE_PREFIX_PATH and name is the name of the library you are looking for

<prefix>/                                               (W)
<prefix>/(cmake|CMake)/                                 (W)
<prefix>/<name>*/                                       (W)
<prefix>/<name>*/(cmake|CMake)/                         (W)
<prefix>/(lib/<arch>|lib|share)/cmake/<name>*/          (U)
<prefix>/(lib/<arch>|lib|share)/<name>*/                (U)
<prefix>/(lib/<arch>|lib|share)/<name>*/(cmake|CMake)/  (U)

In your case you need to add to CMAKE_PREFIX_PATH the following two paths:

D:/develop/cmake/libs/libA;D:/develop/cmake/libB

Eliminate space before \begin{itemize}

\renewcommand{\@listI}{%
\leftmargin=25pt
\rightmargin=0pt
\labelsep=5pt
\labelwidth=20pt
\itemindent=0pt
\listparindent=0pt
\topsep=0pt plus 2pt minus 4pt
\partopsep=0pt plus 1pt minus 1pt
\parsep=0pt plus 1pt
\itemsep=\parsep}

How do I set default terminal to terminator?

change Settings Manager >> Preferred Applications >> Utilities

CSS-moving text from left to right

If I understand you question correctly, you could create a wrapper around your marquee and then assign a width (or max-width) to the wrapping element. For example:

<div id="marquee-wrapper">
    <div class="marquee">This is a marquee!</div>   
</div>

And then #marquee-wrapper { width: x }.

How to pass values across the pages in ASP.net without using Session

If it's just for passing values between pages and you only require it for the one request. Use Context.

Context

The Context object holds data for a single user, for a single request, and it is only persisted for the duration of the request. The Context container can hold large amounts of data, but typically it is used to hold small pieces of data because it is often implemented for every request through a handler in the global.asax. The Context container (accessible from the Page object or using System.Web.HttpContext.Current) is provided to hold values that need to be passed between different HttpModules and HttpHandlers. It can also be used to hold information that is relevant for an entire request. For example, the IBuySpy portal stuffs some configuration information into this container during the Application_BeginRequest event handler in the global.asax. Note that this only applies during the current request; if you need something that will still be around for the next request, consider using ViewState. Setting and getting data from the Context collection uses syntax identical to what you have already seen with other collection objects, like the Application, Session, and Cache. Two simple examples are shown here:

// Add item to
Context Context.Items["myKey"] = myValue;

// Read an item from the
 Context Response.Write(Context["myKey"]);

http://msdn.microsoft.com/en-us/magazine/cc300437.aspx#S6

Using the above. If you then do a Server.Transfer the data you've saved in the context will now be available to the next page. You don't have to concern yourself with removing/tidying up this data as it is only scoped to the current request.

How to clear jQuery validation error messages?

If you want to simply hide the errors:

$("#clearButton").click(function() {
  $("label.error").hide();
  $(".error").removeClass("error");
});

If you specified the errorClass, call that class to hide instead error (the default) I used above.

How do I move an existing Git submodule within a Git repository?

[Update: 2014-11-26] As Yar summarizes nicely below, before you do anything, make sure you know the URL of the submodule. If unknown, open .git/.gitmodules and examine the keysubmodule.<name>.url.

What worked for me was to remove the old submodule using git submodule deinit <submodule> followed by git rm <submodule-folder>. Then add the submodule again with the new folder name and commit. Checking git status before committing shows the old submodule renamed to the new name and .gitmodule modified.

$ git submodule deinit foo
$ git rm foo
$ git submodule add https://bar.com/foo.git new-foo
$ git status
renamed:    foo -> new-foo
modified:   .gitmodules
$ git commit -am "rename foo submodule to new-foo"

Content Type text/xml; charset=utf-8 was not supported by service

Do not forget check the bindings-related code too. So if you wrote:

BasicHttpBinding binding = new BasicHttpBinding();

Be sure that all your app.config files contains

<endpoint address="..."
          binding="basicHttpBinding" ...

not the

<endpoint address="..."
          binding="wsHttpBinding" ...

or so.

How do I set the default schema for a user in MySQL

If your user has a local folder e.g. Linux, in your users home folder you could create a .my.cnf file and provide the credentials to access the server there. for example:-

[client]
host=localhost
user=yourusername
password=yourpassword or exclude to force entry
database=mygotodb

Mysql would then open this file for each user account read the credentials and open the selected database.

Not sure on Windows, I upgraded from Windows because I needed the whole house not just the windows (aka Linux) a while back.

.crx file install in chrome

Opening the debug console in Chrome, or even looking at the html source file (after it is loaded in the browser), make sure that all the paths there are valid (i.e. when you follow a link you get to it's content, and not an error). When something is not valid, fix the path (e.g. get rid of the server specific part and make sure you only refer to files that are part of your extension through paths like /js/jquery-123-min.js).

ASP.NET MVC 3 Razor: Include JavaScript file in the head tag

You can use Named Sections.

_Layout.cshtml

<head>
    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)
</head>

_SomeView.cshtml

@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}

Remove spacing between table cells and rows

Nothing has worked. The solution for the issue is.

<style>
table td {
    padding: 0;
}
</style>

Cancel a UIView animation?

Swift version of Stephen Darlington's solution

UIView.beginAnimations(nil, context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(0.1)
// other animation properties

// set view properties
UIView.commitAnimations()

How can I undo git reset --hard HEAD~1?

In most cases, yes.

Depending on the state your repository was in when you ran the command, the effects of git reset --hard can range from trivial to undo, to basically impossible.

Below I have listed a range of different possible scenarios, and how you might recover from them.

All my changes were committed, but now the commits are gone!

This situation usually occurs when you run git reset with an argument, as in git reset --hard HEAD~. Don't worry, this is easy to recover from!

If you just ran git reset and haven't done anything else since, you can get back to where you were with this one-liner:

git reset --hard @{1}

This resets your current branch whatever state it was in before the last time it was modified (in your case, the most recent modification to the branch would be the hard reset you are trying to undo).

If, however, you have made other modifications to your branch since the reset, the one-liner above won't work. Instead, you should run git reflog <branchname> to see a list of all recent changes made to your branch (including resets). That list will look something like this:

7c169bd master@{0}: reset: moving to HEAD~
3ae5027 master@{1}: commit: Changed file2
7c169bd master@{2}: commit: Some change
5eb37ca master@{3}: commit (initial): Initial commit

Find the operation in this list that you want to "undo". In the example above, it would be the first line, the one that says "reset: moving to HEAD~". Then copy the representation of the commit before (below) that operation. In our case, that would be master@{1} (or 3ae5027, they both represent the same commit), and run git reset --hard <commit> to reset your current branch back to that commit.

I staged my changes with git add, but never committed. Now my changes are gone!

This is a bit trickier to recover from. git does have copies of the files you added, but since these copies were never tied to any particular commit you can't restore the changes all at once. Instead, you have to locate the individual files in git's database and restore them manually. You can do this using git fsck.

For details on this, see Undo git reset --hard with uncommitted files in the staging area.

I had changes to files in my working directory that I never staged with git add, and never committed. Now my changes are gone!

Uh oh. I hate to tell you this, but you're probably out of luck. git doesn't store changes that you don't add or commit to it, and according to the documentation for git reset:

--hard

Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded.

It's possible that you might be able to recover your changes with some sort of disk recovery utility or a professional data recovery service, but at this point that's probably more trouble than it's worth.

Intellij Idea: Importing Gradle project - getting JAVA_HOME not defined yet

Make sure you have a jdk setup. To do this, create a new project and then go to file -> project structure. From there you can add a new jdk. Once that is setup, go back to your gradle project and you should have a jdk to select in the 'Gradle JVM' field.

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

as explained here

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

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

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

Comparing the contents of two files in Sublime Text

UPDATE
(Given the upvotes, I feel there is a need for a complete step-by-step explanation...)

  1. In the Menu bar click on File->Open Folder...
  2. Select a folder (the actual folder does not really matter, this step is just to make the FOLDERS sidebar available)
  3. If there is no Side Bar shown yet, make it appear via View -> Side Bar -> Show Side Bar
  4. Use this FOLDERS-titled Side Bar to navigate to the first file you want to compare.
  5. Select it (click on it), hold down ctrl and select the second file.
  6. Having two files selected, right click on one of the two and select Diff Files...

There should be a new Tab now showing the comparison.


Original short answer:
Note that:

The "Diff files" only appears with the "folders" sidebar (to open a folder: File->Open Folder) , not with "open files" sidebar.

Convert string to JSON Object

only with js

   JSON.parse(jsonObj);

reference

MySQL "WITH" clause

You might be interested in somethinkg like this:

select * from (
    select * from table
) as Subquery

Convert NSData to String?

Prior Swift 3.0 :

String(data: yourData, encoding: NSUTF8StringEncoding)

For Swift 4.0:

String(data: yourData, encoding: .utf8)

Git submodule update

This GitPro page does summarize the consequence of a git submodule update nicely

When you run git submodule update, it checks out the specific version of the project, but not within a branch. This is called having a detached head — it means the HEAD file points directly to a commit, not to a symbolic reference.
The issue is that you generally don’t want to work in a detached head environment, because it’s easy to lose changes.
If you do an initial submodule update, commit in that submodule directory without creating a branch to work in, and then run git submodule update again from the superproject without committing in the meantime, Git will overwrite your changes without telling you. Technically you won’t lose the work, but you won’t have a branch pointing to it, so it will be somewhat difficult to retrieve.


Note March 2013:

As mentioned in "git submodule tracking latest", a submodule now (git1.8.2) can track a branch.

# add submodule to track master branch
git submodule add -b master [URL to Git repo];

# update your submodule
git submodule update --remote 
# or (with rebase)
git submodule update --rebase --remote

See "git submodule update --remote vs git pull".

MindTooth's answer illustrate a manual update (without local configuration):

git submodule -q foreach git pull -q origin master

In both cases, that will change the submodules references (the gitlink, a special entry in the parent repo index), and you will need to add, commit and push said references from the main repo.
Next time you will clone that parent repo, it will populate the submodules to reflect those new SHA1 references.

The rest of this answer details the classic submodule feature (reference to a fixed commit, which is the all point behind the notion of a submodule).


To avoid this issue, create a branch when you work in a submodule directory with git checkout -b work or something equivalent. When you do the submodule update a second time, it will still revert your work, but at least you have a pointer to get back to.

Switching branches with submodules in them can also be tricky. If you create a new branch, add a submodule there, and then switch back to a branch without that submodule, you still have the submodule directory as an untracked directory:


So, to answer your questions:

can I create branches/modifications and use push/pull just like I would in regular repos, or are there things to be cautious about?

You can create a branch and push modifications.

WARNING (from Git Submodule Tutorial): Always publish (push) the submodule change before publishing (push) the change to the superproject that references it. If you forget to publish the submodule change, others won't be able to clone the repository.

how would I advance the submodule referenced commit from say (tagged) 1.0 to 1.1 (even though the head of the original repo is already at 2.0)

The page "Understanding Submodules" can help

Git submodules are implemented using two moving parts:

  • the .gitmodules file and
  • a special kind of tree object.

These together triangulate a specific revision of a specific repository which is checked out into a specific location in your project.


From the git submodule page

you cannot modify the contents of the submodule from within the main project

100% correct: you cannot modify a submodule, only refer to one of its commits.

This is why, when you do modify a submodule from within the main project, you:

  • need to commit and push within the submodule (to the upstream module), and
  • then go up in your main project, and re-commit (in order for that main project to refer to the new submodule commit you just created and pushed)

A submodule enables you to have a component-based approach development, where the main project only refers to specific commits of other components (here "other Git repositories declared as sub-modules").

A submodule is a marker (commit) to another Git repository which is not bound by the main project development cycle: it (the "other" Git repo) can evolves independently.
It is up to the main project to pick from that other repo whatever commit it needs.

However, should you want to, out of convenience, modify one of those submodules directly from your main project, Git allows you to do that, provided you first publish those submodule modifications to its original Git repo, and then commit your main project refering to a new version of said submodule.

But the main idea remains: referencing specific components which:

  • have their own lifecycle
  • have their own set of tags
  • have their own development

The list of specific commits you are refering to in your main project defines your configuration (this is what Configuration Management is all about, englobing mere Version Control System)

If a component could really be developed at the same time as your main project (because any modification on the main project would involve modifying the sub-directory, and vice-versa), then it would be a "submodule" no more, but a subtree merge (also presented in the question Transferring legacy code base from cvs to distributed repository), linking the history of the two Git repo together.

Does that help understanding the true nature of Git Submodules?

Getting RAW Soap Data from a Web Reference Client running in ASP.net

Not sure why all the fuss with web.config or a serializer class. The below code worked for me:

XmlSerializer xmlSerializer = new XmlSerializer(myEnvelope.GetType());

using (StringWriter textWriter = new StringWriter())
{
    xmlSerializer.Serialize(textWriter, myEnvelope);
    return textWriter.ToString();
}

Filling a List with all enum values in Java

There is a constructor for ArrayList which is

ArrayList(Collection<? extends E> c) 

Now, EnumSet extends AbstractCollection so you can just do

ArrayList<Something> all = new ArrayList<Something>(enumSet)

How to change the background color of the options menu?

Just ran into this issue too, on an App that had to be compatible with Gingerbread and still retain as much of the styling from Holo-enabled devices as possible.

I found a relatively clean solution, that worked OK for me.

In the theme I use a 9-patch drawable background to get a custom background color:

<style name="Theme.Styled" parent="Theme.Sherlock">
   ...
   <item name="android:panelFullBackground">@drawable/menu_hardkey_panel</item>
</style>

I gave up trying to style the text color, and just used a Spannable to set the text color for my item in code:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
   MenuInflater inflater = getSupportMenuInflater();
   inflater.inflate(R.menu.actions_main, menu);

   if (android.os.Build.VERSION.SDK_INT < 
        android.os.Build.VERSION_CODES.HONEYCOMB) {

        SpannableStringBuilder text = new SpannableStringBuilder();
        text.append(getString(R.string.action_text));
        text.setSpan(new ForegroundColorSpan(Color.WHITE), 
                0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        MenuItem item1 = menu.findItem(R.id.action_item1);
        item1.setTitle(text);
   }

   return true;
}

Insert Unicode character into JavaScript

The answer is correct, but you don't need to declare a variable. A string can contain your character:

"This string contains omega, that looks like this: \u03A9"

Unfortunately still those codes in ASCII are needed for displaying UTF-8, but I am still waiting (since too many years...) the day when UTF-8 will be same as ASCII was, and ASCII will be just a remembrance of the past.

Responsive font size in CSS

We can use calc() from css

p{
font-size: calc(48px + (56 - 48) * ((100vw - 300px) / (1600 - 300))) !important;
}

The mathematical formula is calc(minsize + (maxsize - minsize) * (100vm - minviewportwidth) / (maxwidthviewoport - minviewportwidth)))

Codepen

How to delete large data of table in SQL without log?

You can also use GO + how many times you want to execute the same query.

DELETE TOP (10000)  [TARGETDATABASE].[SCHEMA].[TARGETTABLE] 
WHERE readTime < dateadd(MONTH,-1,GETDATE());
-- how many times you want the query to repeat
GO 100

How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

I do not like use pure "a" tag, too much typing. So I come with solution. In view it look

<%: Html.ActionLink(node.Name, "Show", "Browse", 
                    Dic.Route("id", node.Id), Dic.New("data-nodeId", node.Id)) %>

Implementation of Dic class

public static class Dic
{
    public static Dictionary<string, object> New(params object[] attrs)
    {
        var res = new Dictionary<string, object>();
        for (var i = 0; i < attrs.Length; i = i + 2)
            res.Add(attrs[i].ToString(), attrs[i + 1]);
        return res;
    }

    public static RouteValueDictionary Route(params object[] attrs)
    {
        return new RouteValueDictionary(Dic.New(attrs));
    }
}

AngularJS/javascript converting a date String to date object

This is what I did on the controller

var collectionDate = '2002-04-26T09:00:00';
var date = new Date(collectionDate);
//then pushed all my data into an array $scope.rows which I then used in the directive

I ended up formatting the date to my desired pattern on the directive as follows.

var data = new google.visualization.DataTable();
                    data.addColumn('date', 'Dates');
                    data.addColumn('number', 'Upper Normal');
                    data.addColumn('number', 'Result');
                    data.addColumn('number', 'Lower Normal');
                    data.addRows(scope.rows);
                    var formatDate = new google.visualization.DateFormat({pattern: "dd/MM/yyyy"});
                    formatDate.format(data, 0);
//set options for the line chart
var options = {'hAxis': format: 'dd/MM/yyyy'}

//Instantiate and draw the chart passing in options
var chart = new google.visualization.LineChart($elm[0]);
                    chart.draw(data, options);

This gave me dates ain the format of dd/MM/yyyy (26/04/2002) on the x axis of the chart.

How to build a 'release' APK in Android Studio?

AndroidStudio is alpha version for now. So you have to edit gradle build script files by yourself. Add next lines to your build.gradle

android {

    signingConfigs {

        release {

            storeFile file('android.keystore')
            storePassword "pwd"
            keyAlias "alias"
            keyPassword "pwd"
        }
    }

    buildTypes {

       release {

           signingConfig signingConfigs.release
       }
    }
}

To actually run your application at emulator or device run gradle installDebug or gradle installRelease.

You can create helloworld project from AndroidStudio wizard to see what structure of gradle files is needed. Or export gradle files from working eclipse project. Also this series of articles are helpfull http://blog.stylingandroid.com/archives/1872#more-1872

Timeout jQuery effects

You can do something like this:

$('.notice')
    .fadeIn()
    .animate({opacity: '+=0'}, 2000)   // Does nothing for 2000ms
    .fadeOut('fast');

Sadly, you can't just do .animate({}, 2000) -- I think this is a bug, and will report it.

Update value of a nested dictionary of varying depth

Update to @Alex Martelli's answer to fix a bug in his code to make the solution more robust:

def update_dict(d, u):
    for k, v in u.items():
        if isinstance(v, collections.Mapping):
            default = v.copy()
            default.clear()
            r = update_dict(d.get(k, default), v)
            d[k] = r
        else:
            d[k] = v
    return d

The key is that we often want to create the same type at recursion, so here we use v.copy().clear() but not {}. And this is especially useful if the dict here is of type collections.defaultdict which can have different kinds of default_factorys.

Also notice that the u.iteritems() has been changed to u.items() in Python3.

Read specific columns with pandas or other python module

An easy way to do this is using the pandas library like this.

import pandas as pd
fields = ['star_name', 'ra']

df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
# See the keys
print df.keys()
# See content in 'star_name'
print df.star_name

The problem here was the skipinitialspace which remove the spaces in the header. So ' star_name' becomes 'star_name'

What do I do when my program crashes with exception 0xc0000005 at address 0?

Problems with the stack frames could indicate stack corruption (a truely horrible beast), optimisation, or mixing frameworks such as C/C++/C#/Delphi and other craziness as that - there is no absolute standard with respect to stack frames. (Some languages do not even have them!).

So, I suggest getting slightly annoyed with the stack frame issues, ignoring it, and then just use Remy's answer.

What's a good hex editor/viewer for the Mac?

One recommendation I've gotten is Hex Fiend.

how to get request path with express req object

req.route.path is working for me

var pool = require('../db');

module.exports.get_plants = function(req, res) {
    // to run a query we can acquire a client from the pool,
    // run a query on the client, and then return the client to the pool
    pool.connect(function(err, client, done) {
        if (err) {
            return console.error('error fetching client from pool', err);
        }
        client.query('SELECT * FROM plants', function(err, result) {
            //call `done()` to release the client back to the pool
            done();
            if (err) {
                return console.error('error running query', err);
            }
            console.log('A call to route: %s', req.route.path + '\nRequest type: ' + req.method.toLowerCase());
            res.json(result);
        });
    });
};

after executing I see the following in the console and I get perfect result in my browser.

Express server listening on port 3000 in development mode
A call to route: /plants
Request type: get

How to save a plot as image on the disk?

If you open a device using png(), bmp(), pdf() etc. as suggested by Andrie (the best answer), the windows with plots will not pop up open, just *.png, *bmp or *.pdf files will be created. This is convenient in massive calculations, since R can handle only limited number of graphic windows.

However, if you want to see the plots and also have them saved, call savePlot(filename, type) after the plots are drawn and the window containing them is active.

SVG gradient using CSS

Here is how to set a linearGradient on a target element:

<style type="text/css">
    path{fill:url('#MyGradient')}
</style>
<defs>
    <linearGradient id="MyGradient">
        <stop offset="0%" stop-color="#e4e4e3" ></stop>
        <stop offset="80%" stop-color="#fff" ></stop>
    </linearGradient>
</defs>

How do I store and retrieve a blob from sqlite?

This worked fine for me (C#):

byte[] iconBytes = null;
using (var dbConnection = new SQLiteConnection(DataSource))
{
    dbConnection.Open();
    using (var transaction = dbConnection.BeginTransaction())
    {
        using (var command = new SQLiteCommand(dbConnection))
        {
            command.CommandText = "SELECT icon FROM my_table";

            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    if (reader["icon"] != null && !Convert.IsDBNull(reader["icon"]))
                    {
                        iconBytes = (byte[]) reader["icon"];
                    }
                }
            }
        }
        transaction.Commit();
    }
}

No need for chunking. Just cast to a byte array.

How to find out the server IP address (using JavaScript) that the browser is connected to?

Try this as a shortcut, not as a definitive solution (see comments):

<script type="text/javascript">
    var ip = location.host;
    alert(ip);
</script>

This solution cannot work in some scenarios but it can help for quick testing. Regards

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

Defined Edges With CSS3 Filter Blur

The simplest way is just adding a transparent border to the div that contains the image and setting its display property to inline-block just like this:

CSS:

div{
margin: 2rem;
height: 100vh;
overflow: hidden;
display: inline-block;
border: 1px solid #00000000;
}

img {
-webkit-filter: blur(2rem);
filter: blur(2rem);
}

HTML

<div><img src='https://images.unsplash.com/photo-1557853197-aefb550b6fdc?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=375&q=80' /></div>

Here's a codepen depicting the same: https://codepen.io/arnavozil/pen/ExPYKNZ

How to count the number of files in a directory using Python

import os

def count_files(in_directory):
    joiner= (in_directory + os.path.sep).__add__
    return sum(
        os.path.isfile(filename)
        for filename
        in map(joiner, os.listdir(in_directory))
    )

>>> count_files("/usr/lib")
1797
>>> len(os.listdir("/usr/lib"))
2049

CSS customized scroll bar in div

This is what Google has used in some of its applications for a long time now. See in the code that, if you apply next classes, they somehow hide the scrollbar in Chrome, but it still works.

The classes are jfk-scrollbar, jfk-scrollbar-borderless, and jfk-scrollbar-dark

_x000D_
_x000D_
.testg{ border:1px solid black;  max-height:150px;  overflow-y: scroll; overflow-x: hidden; width: 250px;}_x000D_
.content{ height: 700px}_x000D_
_x000D_
/* The google css code for scrollbars */_x000D_
::-webkit-scrollbar {_x000D_
    height: 16px;_x000D_
    overflow: visible;_x000D_
    width: 16px_x000D_
}_x000D_
::-webkit-scrollbar-button {_x000D_
    height: 0;_x000D_
    width: 0_x000D_
}_x000D_
::-webkit-scrollbar-track {_x000D_
    background-clip: padding-box;_x000D_
    border: solid transparent;_x000D_
    border-width: 0 0 0 7px_x000D_
}_x000D_
::-webkit-scrollbar-track:horizontal {_x000D_
    border-width: 7px 0 0_x000D_
}_x000D_
::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(0, 0, 0, .05);_x000D_
    box-shadow: inset 1px 0 0 rgba(0, 0, 0, .1)_x000D_
}_x000D_
::-webkit-scrollbar-track:horizontal:hover {_x000D_
    box-shadow: inset 0 1px 0 rgba(0, 0, 0, .1)_x000D_
}_x000D_
::-webkit-scrollbar-track:active {_x000D_
    background-color: rgba(0, 0, 0, .05);_x000D_
    box-shadow: inset 1px 0 0 rgba(0, 0, 0, .14), inset -1px 0 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
::-webkit-scrollbar-track:horizontal:active {_x000D_
    box-shadow: inset 0 1px 0 rgba(0, 0, 0, .14), inset 0 -1px 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(255, 255, 255, .1);_x000D_
    box-shadow: inset 1px 0 0 rgba(255, 255, 255, .2)_x000D_
}_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-track:horizontal:hover {_x000D_
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, .2)_x000D_
}_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-track:active {_x000D_
    background-color: rgba(255, 255, 255, .1);_x000D_
    box-shadow: inset 1px 0 0 rgba(255, 255, 255, .25), inset -1px 0 0 rgba(255, 255, 255, .15)_x000D_
}_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-track:horizontal:active {_x000D_
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, .25), inset 0 -1px 0 rgba(255, 255, 255, .15)_x000D_
}_x000D_
::-webkit-scrollbar-thumb {_x000D_
    background-color: rgba(0, 0, 0, .2);_x000D_
    background-clip: padding-box;_x000D_
    border: solid transparent;_x000D_
    border-width: 0 0 0 7px;_x000D_
    min-height: 28px;_x000D_
    padding: 100px 0 0;_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .1), inset 0 -1px 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
::-webkit-scrollbar-thumb:horizontal {_x000D_
    border-width: 7px 0 0;_x000D_
    padding: 0 0 0 100px;_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .1), inset -1px 0 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
::-webkit-scrollbar-thumb:hover {_x000D_
    background-color: rgba(0, 0, 0, .4);_x000D_
    box-shadow: inset 1px 1px 1px rgba(0, 0, 0, .25)_x000D_
}_x000D_
::-webkit-scrollbar-thumb:active {_x000D_
    background-color: rgba(0, 0, 0, 0.5);_x000D_
    box-shadow: inset 1px 1px 3px rgba(0, 0, 0, 0.35)_x000D_
}_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-thumb {_x000D_
    background-color: rgba(255, 255, 255, .3);_x000D_
    box-shadow: inset 1px 1px 0 rgba(255, 255, 255, .15), inset 0 -1px 0 rgba(255, 255, 255, .1)_x000D_
}_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-thumb:horizontal {_x000D_
    box-shadow: inset 1px 1px 0 rgba(255, 255, 255, .15), inset -1px 0 0 rgba(255, 255, 255, .1)_x000D_
}_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-thumb:hover {_x000D_
    background-color: rgba(255, 255, 255, .6);_x000D_
    box-shadow: inset 1px 1px 1px rgba(255, 255, 255, .37)_x000D_
}_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-thumb:active {_x000D_
    background-color: rgba(255, 255, 255, .75);_x000D_
    box-shadow: inset 1px 1px 3px rgba(255, 255, 255, .5)_x000D_
}_x000D_
.jfk-scrollbar-borderless::-webkit-scrollbar-track {_x000D_
    border-width: 0 1px 0 6px_x000D_
}_x000D_
.jfk-scrollbar-borderless::-webkit-scrollbar-track:horizontal {_x000D_
    border-width: 6px 0 1px_x000D_
}_x000D_
.jfk-scrollbar-borderless::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(0, 0, 0, .035);_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .14), inset -1px -1px 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
.jfk-scrollbar-borderless.jfk-scrollbar-dark::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(255, 255, 255, .07);_x000D_
    box-shadow: inset 1px 1px 0 rgba(255, 255, 255, .25), inset -1px -1px 0 rgba(255, 255, 255, .15)_x000D_
}_x000D_
.jfk-scrollbar-borderless::-webkit-scrollbar-thumb {_x000D_
    border-width: 0 1px 0 6px_x000D_
}_x000D_
.jfk-scrollbar-borderless::-webkit-scrollbar-thumb:horizontal {_x000D_
    border-width: 6px 0 1px_x000D_
}_x000D_
::-webkit-scrollbar-corner {_x000D_
    background: transparent_x000D_
}_x000D_
body::-webkit-scrollbar-track-piece {_x000D_
    background-clip: padding-box;_x000D_
    background-color: #f5f5f5;_x000D_
    border: solid #fff;_x000D_
    border-width: 0 0 0 3px;_x000D_
    box-shadow: inset 1px 0 0 rgba(0, 0, 0, .14), inset -1px 0 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
body::-webkit-scrollbar-track-piece:horizontal {_x000D_
    border-width: 3px 0 0;_x000D_
    box-shadow: inset 0 1px 0 rgba(0, 0, 0, .14), inset 0 -1px 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
body::-webkit-scrollbar-thumb {_x000D_
    border-width: 1px 1px 1px 5px_x000D_
}_x000D_
body::-webkit-scrollbar-thumb:horizontal {_x000D_
    border-width: 5px 1px 1px_x000D_
}_x000D_
body::-webkit-scrollbar-corner {_x000D_
    background-clip: padding-box;_x000D_
    background-color: #f5f5f5;_x000D_
    border: solid #fff;_x000D_
    border-width: 3px 0 0 3px;_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .14)_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar {_x000D_
    height: 16px;_x000D_
    overflow: visible;_x000D_
    width: 16px_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-button {_x000D_
    height: 0;_x000D_
    width: 0_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-track {_x000D_
    background-clip: padding-box;_x000D_
    border: solid transparent;_x000D_
    border-width: 0 0 0 7px_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-track:horizontal {_x000D_
    border-width: 7px 0 0_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(0, 0, 0, .05);_x000D_
    box-shadow: inset 1px 0 0 rgba(0, 0, 0, .1)_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-track:horizontal:hover {_x000D_
    box-shadow: inset 0 1px 0 rgba(0, 0, 0, .1)_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-track:active {_x000D_
    background-color: rgba(0, 0, 0, .05);_x000D_
    box-shadow: inset 1px 0 0 rgba(0, 0, 0, .14), inset -1px 0 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-track:horizontal:active {_x000D_
    box-shadow: inset 0 1px 0 rgba(0, 0, 0, .14), inset 0 -1px 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(255, 255, 255, .1);_x000D_
    box-shadow: inset 1px 0 0 rgba(255, 255, 255, .2)_x000D_
}_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-track:horizontal:hover {_x000D_
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, .2)_x000D_
}_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-track:active {_x000D_
    background-color: rgba(255, 255, 255, .1);_x000D_
    box-shadow: inset 1px 0 0 rgba(255, 255, 255, .25), inset -1px 0 0 rgba(255, 255, 255, .15)_x000D_
}_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-track:horizontal:active {_x000D_
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, .25), inset 0 -1px 0 rgba(255, 255, 255, .15)_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-thumb {_x000D_
    background-color: rgba(0, 0, 0, .2);_x000D_
    background-clip: padding-box;_x000D_
    border: solid transparent;_x000D_
    border-width: 0 0 0 7px;_x000D_
    min-height: 28px;_x000D_
    padding: 100px 0 0;_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .1), inset 0 -1px 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-thumb:horizontal {_x000D_
    border-width: 7px 0 0;_x000D_
    padding: 0 0 0 100px;_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .1), inset -1px 0 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-thumb:hover {_x000D_
    background-color: rgba(0, 0, 0, .4);_x000D_
    box-shadow: inset 1px 1px 1px rgba(0, 0, 0, .25)_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-thumb:active {_x000D_
    background-color: rgba(0, 0, 0, 0.5);_x000D_
    box-shadow: inset 1px 1px 3px rgba(0, 0, 0, 0.35)_x000D_
}_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-thumb {_x000D_
    background-color: rgba(255, 255, 255, .3);_x000D_
    box-shadow: inset 1px 1px 0 rgba(255, 255, 255, .15), inset 0 -1px 0 rgba(255, 255, 255, .1)_x000D_
}_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-thumb:horizontal {_x000D_
    box-shadow: inset 1px 1px 0 rgba(255, 255, 255, .15), inset -1px 0 0 rgba(255, 255, 255, .1)_x000D_
}_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-thumb:hover {_x000D_
    background-color: rgba(255, 255, 255, .6);_x000D_
    box-shadow: inset 1px 1px 1px rgba(255, 255, 255, .37)_x000D_
}_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-thumb:active {_x000D_
    background-color: rgba(255, 255, 255, .75);_x000D_
    box-shadow: inset 1px 1px 3px rgba(255, 255, 255, .5)_x000D_
}_x000D_
.jfk-scrollbar-borderless.jfk-scrollbar::-webkit-scrollbar-track {_x000D_
    border-width: 0 1px 0 6px_x000D_
}_x000D_
.jfk-scrollbar-borderless.jfk-scrollbar::-webkit-scrollbar-track:horizontal {_x000D_
    border-width: 6px 0 1px_x000D_
}_x000D_
.jfk-scrollbar-borderless.jfk-scrollbar::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(0, 0, 0, .035);_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .14), inset -1px -1px 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
.jfk-scrollbar-borderless.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(255, 255, 255, .07);_x000D_
    box-shadow: inset 1px 1px 0 rgba(255, 255, 255, .25), inset -1px -1px 0 rgba(255, 255, 255, .15)_x000D_
}_x000D_
.jfk-scrollbar-borderless.jfk-scrollbar::-webkit-scrollbar-thumb {_x000D_
    border-width: 0 1px 0 6px_x000D_
}_x000D_
.jfk-scrollbar-borderless.jfk-scrollbar::-webkit-scrollbar-thumb:horizontal {_x000D_
    border-width: 6px 0 1px_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-corner {_x000D_
    background: transparent_x000D_
}_x000D_
body.jfk-scrollbar::-webkit-scrollbar-track-piece {_x000D_
    background-clip: padding-box;_x000D_
    background-color: #f5f5f5;_x000D_
    border: solid #fff;_x000D_
    border-width: 0 0 0 3px;_x000D_
    box-shadow: inset 1px 0 0 rgba(0, 0, 0, .14), inset -1px 0 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
body.jfk-scrollbar::-webkit-scrollbar-track-piece:horizontal {_x000D_
    border-width: 3px 0 0;_x000D_
    box-shadow: inset 0 1px 0 rgba(0, 0, 0, .14), inset 0 -1px 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
body.jfk-scrollbar::-webkit-scrollbar-thumb {_x000D_
    border-width: 1px 1px 1px 5px_x000D_
}_x000D_
body.jfk-scrollbar::-webkit-scrollbar-thumb:horizontal {_x000D_
    border-width: 5px 1px 1px_x000D_
}_x000D_
body.jfk-scrollbar::-webkit-scrollbar-corner {_x000D_
    background-clip: padding-box;_x000D_
    background-color: #f5f5f5;_x000D_
    border: solid #fff;_x000D_
    border-width: 3px 0 0 3px;_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .14)_x000D_
}
_x000D_
<div class="testg">_x000D_
    <div class="content">_x000D_
        Look Ma'  my scrollbars doesn't have arrows <br /><br />_x000D_
        content, content, content <br /> content, content, content <br /> content, content, content s<br />  content, content, content <br/> content, content, content <br/> content, content, content d<br/>  content, content, content <br/> _x000D_
    </div>_x000D_
</div>_x000D_
<br/>_x000D_
<div class="testg jfk-scrollbar jfk-scrollbar-borderless jfk-scrollbar-dark">_x000D_
    <div class="content">_x000D_
        Look Ma'  my scrollbars dissapear in chrome<br /><br />_x000D_
        content, content, content <br /> content, content, content <br /> content, content, content s<br />  content, content, content <br/> content, content, content <br/> content, content, content d<br/>  content, content, content <br/> _x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/76kcuem0/32/

I just found it useful to remove the arrows from the scrollbars. As of 2015 it's been used in Google Maps when searching for places in the list of results in its material design UI.

Vertical (rotated) text in HTML table

Here is one that works for plain-text with some server side processing:

public string RotateHtmltext(string innerHtml)
{
   const string TRANSFORMTEXT = "transform: rotate(90deg);";
   const string EXTRASTYLECSS = "<style type='text/css'>.r90 {"
                                 + "-webkit-" + TRANSFORMTEXT
                                 + "-moz-" + TRANSFORMTEXT
                                 + "-o-" + TRANSFORMTEXT
                                 + "-ms-" + TRANSFORMTEXT
                                 + "" + TRANSFORMTEXT
                                 + "width:1em;line-height:1ex}</style>";
   const string WRAPPERDIV = "<div style='display: table-cell; vertical-align: middle;'>";

   var newinnerHtml = string.Join("</div>"+WRAPPERDIV, Regex.Split(innerHtml, @"<br */?>").Reverse());

   newinnerHtml = Regex.Replace(newinnerHtml, @"((?:<[^>]*>)|(?:[^<]+))",
                                 match => match.Groups[1].Value.StartsWith("<")
                                             ? match.Groups[1].Value
                                             : string.Join("", match.Groups[1].Value.ToCharArray().Select(x=>"<div class='r90'>"+x+"</div>")),
                                 RegexOptions.Singleline);
   return EXTRASTYLECSS + WRAPPERDIV + newinnerHtml + "</div>";
}

which gives something like:

<style type="text/css">.r90 {
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
width: 1em;
line-height: 1ex; 
}</style>
<div style="display: table-cell; vertical-align: middle;">
<div class="r90">p</div>
<div class="r90">o</div>
<div class="r90">s</div>
</div><div style="display: table-cell; vertical-align: middle;">
<div class="r90">(</div>
<div class="r90">A</div>
<div class="r90">b</div>
<div class="r90">s</div>
<div class="r90">)</div>
</div>

http://jsfiddle.net/TzzHy/

No connection could be made because the target machine actively refused it?

I came across this error and took some time to resolve it. In my case I had https and net.tcp configured as IIS bindings on same port. Obviously you can't have two things on the same port. I used netstat -ap tcp command to check whether there is something listening on that port. There was none listening. Removing unnecessary binding (https in my case) solved my issue.

How to use XPath in Python?

You can use:

PyXML:

from xml.dom.ext.reader import Sax2
from xml import xpath
doc = Sax2.FromXmlFile('foo.xml').documentElement
for url in xpath.Evaluate('//@Url', doc):
  print url.value

libxml2:

import libxml2
doc = libxml2.parseFile('foo.xml')
for url in doc.xpathEval('//@Url'):
  print url.content

Get first line of a shell command's output

Yes, that is one way to get the first line of output from a command.

If the command outputs anything to standard error that you would like to capture in the same manner, you need to redirect the standard error of the command to the standard output stream:

utility 2>&1 | head -n 1

There are many other ways to capture the first line too, including sed 1q (quit after first line), sed -n 1p (only print first line, but read everything), awk 'FNR == 1' (only print first line, but again, read everything) etc.

Converting from IEnumerable to List

If you're using an implementation of System.Collections.IEnumerable you can do like following to convert it to a List. The following uses Enumerable.Cast method to convert IEnumberable to a Generic List.

//ArrayList Implements IEnumerable interface
ArrayList _provinces = new System.Collections.ArrayList();
_provinces.Add("Western");
_provinces.Add("Eastern");

List<string> provinces = _provinces.Cast<string>().ToList();

If you're using Generic version IEnumerable<T>, The conversion is straight forward. Since both are generics, you can do like below,

IEnumerable<int> values = Enumerable.Range(1, 10);
List<int> valueList = values.ToList();

But if the IEnumerable is null, when you try to convert it to a List, you'll get ArgumentNullException saying Value cannot be null.

IEnumerable<int> values2 = null;
List<int> valueList2 = values2.ToList();

enter image description here

Therefore as mentioned in the other answer, remember to do a null check before converting it to a List.

Split comma separated column data into additional columns

split_part() does what you want in one step:

SELECT split_part(col, ',', 1) AS col1
     , split_part(col, ',', 2) AS col2
     , split_part(col, ',', 3) AS col3
     , split_part(col, ',', 4) AS col4
FROM   tbl;

Add as many lines as you have items in col (the possible maximum). Columns exceeding data items will be empty strings ('').

I/O error(socket error): [Errno 111] Connection refused

Use a packet sniffer like Wireshark to look at what happens. You need to see a SYN-flagged packet outgoing, a SYN+ACK-flagged incoming and then a ACK-flagged outgoing. After that, the port is considered open on the local side.

If you only see the first packet and the error message comes after several seconds of waiting, the other side is not answering at all (like in: unplugged cable, overloaded server, misguided packet was discarded) and your local network stack aborts the connection attempt. If you see RST packets, the host actually denies the connection. If you see "ICMP Port unreachable" or host unreachable packets, a firewall or the target host inform you of the port actually being closed.

Of course you cannot expect the service to be available at all times (consider all the points of failure in between you and the data), so you should try again later.

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

I had a similar error, but for me it seemed to be caused by re-using an IAM user to work with S3 in two different Elastic Beanstalk environments. I treated the symptom by creating an identically permissioned IAM user for each environment and that made the error go away.

Removing specific rows from a dataframe

Here's a solution to your problem using dplyr's filter function.

Although you can pass your data frame as the first argument to any dplyr function, I've used its %>% operator, which pipes your data frame to one or more dplyr functions (just filter in this case).

Once you are somewhat familiar with dplyr, the cheat sheet is very handy.

> print(df <- data.frame(sub=rep(1:3, each=4), day=1:4))
   sub day
1    1   1
2    1   2
3    1   3
4    1   4
5    2   1
6    2   2
7    2   3
8    2   4
9    3   1
10   3   2
11   3   3
12   3   4
> print(df <- df %>% filter(!((sub==1 & day==2) | (sub==3 & day==4))))
   sub day
1    1   1
2    1   3
3    1   4
4    2   1
5    2   2
6    2   3
7    2   4
8    3   1
9    3   2
10   3   3

Setting java locale settings

You can change on the console:

$ export LANG=en_US.utf8

Spark - load CSV file as DataFrame?

Penny's Spark 2 example is the way to do it in spark2. There's one more trick: have that header generated for you by doing an initial scan of the data, by setting the option inferSchema to true

Here, then, assumming that spark is a spark session you have set up, is the operation to load in the CSV index file of all the Landsat images which amazon host on S3.

  /*
   * Licensed to the Apache Software Foundation (ASF) under one or more
   * contributor license agreements.  See the NOTICE file distributed with
   * this work for additional information regarding copyright ownership.
   * The ASF licenses this file to You under the Apache License, Version 2.0
   * (the "License"); you may not use this file except in compliance with
   * the License.  You may obtain a copy of the License at
   *
   *    http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */

val csvdata = spark.read.options(Map(
    "header" -> "true",
    "ignoreLeadingWhiteSpace" -> "true",
    "ignoreTrailingWhiteSpace" -> "true",
    "timestampFormat" -> "yyyy-MM-dd HH:mm:ss.SSSZZZ",
    "inferSchema" -> "true",
    "mode" -> "FAILFAST"))
  .csv("s3a://landsat-pds/scene_list.gz")

The bad news is: this triggers a scan through the file; for something large like this 20+MB zipped CSV file, that can take 30s over a long haul connection. Bear that in mind: you are better off manually coding up the schema once you've got it coming in.

(code snippet Apache Software License 2.0 licensed to avoid all ambiguity; something I've done as a demo/integration test of S3 integration)

Difference between int32, int, int32_t, int8 and int8_t

Always keep in mind that 'size' is variable if not explicitly specified so if you declare

 int i = 10;

On some systems it may result in 16-bit integer by compiler and on some others it may result in 32-bit integer (or 64-bit integer on newer systems).

In embedded environments this may end up in weird results (especially while handling memory mapped I/O or may be consider a simple array situation), so it is highly recommended to specify fixed size variables. In legacy systems you may come across

 typedef short INT16;
 typedef int INT32;
 typedef long INT64; 

Starting from C99, the designers added stdint.h header file that essentially leverages similar typedefs.

On a windows based system, you may see entries in stdin.h header file as

 typedef signed char       int8_t;
 typedef signed short      int16_t;
 typedef signed int        int32_t;
 typedef unsigned char     uint8_t;

There is quite more to that like minimum width integer or exact width integer types, I think it is not a bad thing to explore stdint.h for a better understanding.

How to make a list of n numbers in Python and randomly select any number?

After that I would like to select another number from the remaining numbers of the list (N-1) and then use that also.

Then you arguably do not really want to create a list of numbers from 1 to N just for the purpose of picking one (why not just ask for a random number in that range directly, instead of explicitly creating it to choose from?), but instead to shuffle such a list. Fortunately, the random module has you covered for this, too: just use random.shuffle.

Of course, if you have a huge list of numbers and you only want to draw a few, then it certainly makes sense to draw each using random.choice and remove it.

But... why do you want to select numbers from a range, that corresponds to the count of some items? Are you going to use the number to select one of the items? Don't do that; that's going out of your way to make things too complicated. If you want to select one of the items, then do so directly - again with random.choice.

Confused about UPDLOCK, HOLDLOCK

Why would UPDLOCK block selects? The Lock Compatibility Matrix clearly shows N for the S/U and U/S contention, as in No Conflict.

As for the HOLDLOCK hint the documentation states:

HOLDLOCK: Is equivalent to SERIALIZABLE. For more information, see SERIALIZABLE later in this topic.

...

SERIALIZABLE: ... The scan is performed with the same semantics as a transaction running at the SERIALIZABLE isolation level...

and the Transaction Isolation Level topic explains what SERIALIZABLE means:

No other transactions can modify data that has been read by the current transaction until the current transaction completes.

Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.

Therefore the behavior you see is perfectly explained by the product documentation:

  • UPDLOCK does not block concurrent SELECT nor INSERT, but blocks any UPDATE or DELETE of the rows selected by T1
  • HOLDLOCK means SERALIZABLE and therefore allows SELECTS, but blocks UPDATE and DELETES of the rows selected by T1, as well as any INSERT in the range selected by T1 (which is the entire table, therefore any insert).
  • (UPDLOCK, HOLDLOCK): your experiment does not show what would block in addition to the case above, namely another transaction with UPDLOCK in T2:
    SELECT * FROM dbo.Test WITH (UPDLOCK) WHERE ...
  • TABLOCKX no need for explanations

The real question is what are you trying to achieve? Playing with lock hints w/o an absolute complete 110% understanding of the locking semantics is begging for trouble...

After OP edit:

I would like to select rows from a table and prevent the data in that table from being modified while I am processing it.

The you should use one of the higher transaction isolation levels. REPEATABLE READ will prevent the data you read from being modified. SERIALIZABLE will prevent the data you read from being modified and new data from being inserted. Using transaction isolation levels is the right approach, as opposed to using query hints. Kendra Little has a nice poster exlaining the isolation levels.

Why is a div with "display: table-cell;" not affected by margin?

Cause

From the MDN documentation:

[The margin property] applies to all elements except elements with table display types other than table-caption, table and inline-table

In other words, the margin property is not applicable to display:table-cell elements.

Solution

Consider using the border-spacing property instead.

Note it should be applied to a parent element with a display:table layout and border-collapse:separate.

For example:

HTML

<div class="table">
    <div class="row">
        <div class="cell">123</div>
        <div class="cell">456</div>
        <div class="cell">879</div>
    </div>
</div>

CSS

.table {display:table;border-collapse:separate;border-spacing:5px;}
.row {display:table-row;}
.cell {display:table-cell;padding:5px;border:1px solid black;}

See jsFiddle demo


Different margin horizontally and vertically

As mentioned by Diego Quirós, the border-spacing property also accepts two values to set a different margin for the horizontal and vertical axes.

For example

.table {/*...*/border-spacing:3px 5px;} /* 3px horizontally, 5px vertically */

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6

please add this code to android section inside your app/build.gradle

compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8
    }

Dataframe to Excel sheet

Or you can do like this:

your_df.to_excel( r'C:\Users\full_path\excel_name.xlsx',
                  sheet_name= 'your_sheet_name'
                )

Reducing the gap between a bullet and text in a list item

If in every li you have only one row of text you can put text indent on li. Like this :

ul {
  list-style: disc;
}
ul li {
   text-indent: 5px;
}

or

ul {
 list-style: disc;
}
ul li {
   text-indent: -5px;
}

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

The problem mainly occurs after updating OS X to El Capitan (OS X 10.11) or macOS Sierra (macOS 10.12).

This is because of file permission issues with El Capitan’s or later macOS's new SIP process. Try changing the permissions for the /usr/local directory:

$ sudo chown -R $(whoami):admin /usr/local  

If it still doesn't work, use these steps inside a terminal session and everything will be fine:

cd /usr/local/Library/Homebrew  
git reset --hard  
git clean -df
brew update

This may be because homebrew is not updated.

Specifying onClick event type with Typescript and React.Konva

You should be using event.currentTarget. React is mirroring the difference between currentTarget (element the event is attached to) and target (the element the event is currently happening on). Since this is a mouse event, type-wise the two could be different, even if it doesn't make sense for a click.

https://github.com/facebook/react/issues/5733 https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget

AngularJS - pass function to directive

use dash and lower case for attribute name ( like other answers said ) :

 <test color1="color1" update-fn="updateFn()"></test>

And use "=" instead of "&" in directive scope:

 scope: { updateFn: '='}

Then you can use updateFn like any other function:

 <button ng-click='updateFn()'>Click</button>

There you go!

How to get distinct values from an array of objects in JavaScript?

If like me you prefer a more "functional" without compromising speed, this example uses fast dictionary lookup wrapped inside reduce closure.

var array = 
[
    {"name":"Joe", "age":17}, 
    {"name":"Bob", "age":17}, 
    {"name":"Carl", "age": 35}
]
var uniqueAges = array.reduce((p,c,i,a) => {
    if(!p[0][c.age]) {
        p[1].push(p[0][c.age] = c.age);
    }
    if(i<a.length-1) {
        return p
    } else {
        return p[1]
    }
}, [{},[]])

According to this test my solution is twice as fast as the proposed answer

Remove non-utf8 characters from string

So the rules are that the first UTF-8 octlet has the high bit set as a marker, and then 1 to 4 bits to indicate how many additional octlets; then each of the additional octlets must have the high two bits set to 10.

The pseudo-python would be:

newstring = ''
cont = 0
for each ch in string:
  if cont:
    if (ch >> 6) != 2: # high 2 bits are 10
      # do whatever, e.g. skip it, or skip whole point, or?
    else:
      # acceptable continuation of multi-octlet char
      newstring += ch
    cont -= 1
  else:
    if (ch >> 7): # high bit set?
      c = (ch << 1) # strip the high bit marker
      while (c & 1): # while the high bit indicates another octlet
        c <<= 1
        cont += 1
        if cont > 4:
           # more than 4 octels not allowed; cope with error
      if !cont:
        # illegal, do something sensible
      newstring += ch # or whatever
if cont:
  # last utf-8 was not terminated, cope

This same logic should be translatable to php. However, its not clear what kind of stripping is to be done once you get a malformed character.

How to use JavaScript variables in jQuery selectors?

$("input").click(function(){
        var name = $(this).attr("name");
        $('input[name="' + name + '"]').hide();    
    });   

Also works with ID:

var id = $(this).attr("id");
$('input[id="' + id + '"]').hide();

when, (sometimes)

$('input#' + id).hide();

does not work, as it should.

You can even do both:

$('input[name="' + name + '"][id="' + id + '"]').hide();

How do I fix the indentation of selected lines in Visual Studio

Selecting the text to fix, and CtrlK, CtrlF shortcut certainly works. However, I generally find that if a particular method (for instance) has it's indentation messed up, simply removing the closing brace of the method, and re-adding, in fact fixes the indentation anyway, thereby doing without the need to select the code before hand, ergo is quicker. ymmv.

JavaScript: function returning an object

The latest way to do this with ES2016 JavaScript

let makeGamePlayer = (name, totalScore, gamesPlayed) => ({
    name,
    totalScore,
    gamesPlayed
})

How to split a String by space

What you have should work. If, however, the spaces provided are defaulting to... something else? You can use the whitespace regex:

str = "Hello I'm your String";
String[] splited = str.split("\\s+");

This will cause any number of consecutive spaces to split your string into tokens.

As a side note, I'm not sure "splited" is a word :) I believe the state of being the victim of a split is also "split". It's one of those tricky grammar things :-) Not trying to be picky, just figured I'd pass it on!

How to stop event propagation with inline onclick attribute?

This worked for me

<script>
function cancelBubble(e) {
 var evt = e ? e:window.event;
 if (evt.stopPropagation)    evt.stopPropagation();
 if (evt.cancelBubble!=null) evt.cancelBubble = true;
}
</script>

<div onclick="alert('Click!')">
  <div onclick="cancelBubble(event)">Something inside the other div</div>
</div>

Oracle 11g SQL to get unique values in one column of a multi-column query

select person, language     
from table A     
group by person, language  

will return unique rows

Submit form with Enter key without submit button?

Change #form to your form's ID

$('#form input').keydown(function(e) {
    if (e.keyCode == 13) {
        $('#form').submit();
    }
});

Or alternatively

$('input').keydown(function(e) {
    if (e.keyCode == 13) {
        $(this).closest('form').submit();
    }
});

What does 'IISReset' do?

Here what's technet has to say about iisreset

You might need to restart Internet Information Services (IIS) before certain configuration changes take effect or when applications become unavailable. Restarting IIS is the same as first stopping IIS, and then starting it again, except it is accomplished with a single command.

Convert string to date in bash

We can use date -d option

1) Change format to "%Y-%m-%d" format i.e 20121212 to 2012-12-12

date -d '20121212' +'%Y-%m-%d'

2)Get next or last day from a given date=20121212. Like get a date 7 days in past with specific format

date -d '20121212 -7 days' +'%Y-%m-%d'

3) If we are getting date in some variable say dat

dat2=$(date -d "$dat -1 days" +'%Y%m%d')

How to install mcrypt extension in xampp

Right from the PHP Docs: PHP 5.3 Windows binaries uses the static version of the MCrypt library, no DLL are needed.

http://php.net/manual/en/mcrypt.requirements.php

But if you really want to download it, just go to the mcrypt sourceforge page

http://sourceforge.net/projects/mcrypt/files/?source=navbar

Writing MemoryStream to Response Object

The problem for me was that my stream was not set to the origin before download.

Response.Clear();
Response.ContentType = "Application/msword";
Response.AddHeader("Content-Disposition", "attachment; filename=myfile.docx");

//ADDED THIS LINE
myMemoryStream.Seek(0,SeekOrigin.Begin);

myMemoryStream.WriteTo(Response.OutputStream); 
Response.Flush();
Response.Close();

Call PowerShell script PS1 from another PS1 script inside Powershell ISE

One line solution:

& ((Split-Path $MyInvocation.InvocationName) + "\MyScript1.ps1")

how to get all markers on google-maps-v3

If you mean "how can I get a reference to all markers on a given map" - then I think the answer is "Sorry, you have to do it yourself". I don't think there is any handy "maps.getMarkers()" type function: you have to keep your own references as the points are created:

var allMarkers = [];
....
// Create some markers
for(var i = 0; i < 10; i++) {
    var marker = new google.maps.Marker({...});
    allMarkers.push(marker);
}
...

Then you can loop over the allMarkers array to and do whatever you need to do.

Convert string to a variable name

There is another simple solution found there: http://www.r-bloggers.com/converting-a-string-to-a-variable-name-on-the-fly-and-vice-versa-in-r/

To convert a string to a variable:

x <- 42
eval(parse(text = "x"))
[1] 42

And the opposite:

x <- 42
deparse(substitute(x))
[1] "x"

How to detect DataGridView CheckBox event change?

To do this when using the devexpress xtragrid, it is necessary to handle the EditValueChanged event of a corresponding repository item as described here. It is also important to call the gridView1.PostEditor() method to ensure the changed value has been posted. Here is an implementation:

        private void RepositoryItemCheckEdit1_EditValueChanged(object sender, System.EventArgs e)
        {
            gridView3.PostEditor();

            var isNoneOfTheAboveChecked = false;

            for (int i = 0; i < gridView3.DataRowCount; i++)
            {
                if ((bool) (gridView3.GetRowCellValue(i, "NoneOfTheAbove")) && (bool) (gridView3.GetRowCellValue(i, "Answer")))
                {
                    isNoneOfTheAboveChecked = true;
                    break;
                }
            }

            if (isNoneOfTheAboveChecked)
            {
                for (int i = 0; i < gridView3.DataRowCount; i++)
                {
                    if (!((bool)(gridView3.GetRowCellValue(i, "NoneOfTheAbove"))))
                    {
                        gridView3.SetRowCellValue(i, "Answer", false);
                    }
                }
            }
        }

Note that because the xtragrid doesnt provide an enumerator it is necessary to use a for loop to iterate over rows.

BarCode Image Generator in Java

ZXing is a free open source Java library to read and generate barcode images. You need to get the source code and build the jars yourself. Here's a simple tutorial that I wrote for building with ZXing jars and writing your first program with ZXing.

[http://www.vineetmanohar.com/2010/09/java-barcode-api/]

Rails: Why "sudo" command is not recognized?

sudo is used for Linux. It looks like you are running this in Windows.

How to log as much information as possible for a Java Exception?

Something that I do is to have a static method that handles all exceptions and I add the log to a JOptionPane to show it to the user, but you could write the result to a file in FileWriter wraped in a BufeeredWriter. For the main static method, to catch the Uncaught Exceptions I do:

SwingUtilities.invokeLater( new Runnable() {
    @Override
    public void run() {
        //Initializations...
    }
});


Thread.setDefaultUncaughtExceptionHandler( 
    new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException( Thread t, Throwable ex ) {
            handleExceptions( ex, true );
        }
    }
);

And as for the method:

public static void handleExceptions( Throwable ex, boolean shutDown ) {
    JOptionPane.showMessageDialog( null,
        "A CRITICAL ERROR APPENED!\n",
        "SYSTEM FAIL",
        JOptionPane.ERROR_MESSAGE );

    StringBuilder sb = new StringBuilder(ex.toString());
    for (StackTraceElement ste : ex.getStackTrace()) {
        sb.append("\n\tat ").append(ste);
    }


    while( (ex = ex.getCause()) != null ) {
        sb.append("\n");
        for (StackTraceElement ste : ex.getStackTrace()) {
            sb.append("\n\tat ").append(ste);
        }
    }

    String trace = sb.toString();

    JOptionPane.showMessageDialog( null,
        "PLEASE SEND ME THIS ERROR SO THAT I CAN FIX IT. \n\n" + trace,
        "SYSTEM FAIL",
        JOptionPane.ERROR_MESSAGE);

    if( shutDown ) {
        Runtime.getRuntime().exit( 0 );
    }
}

In you case, instead of "screaming" to the user, you could write a log like I told you before:

String trace = sb.toString();

File file = new File("mylog.txt");
FileWriter myFileWriter = null;
BufferedWriter myBufferedWriter = null;

try {
    //with FileWriter(File file, boolean append) you can writer to 
    //the end of the file
    myFileWriter = new FileWriter( file, true );
    myBufferedWriter = new BufferedWriter( myFileWriter );

    myBufferedWriter.write( trace );
}
catch ( IOException ex1 ) {
    //Do as you want. Do you want to use recursive to handle 
    //this exception? I don't advise that. Trust me...
}
finally {
    try {
        myBufferedWriter.close();
    }
    catch ( IOException ex1 ) {
        //Idem...
    }

    try {
        myFileWriter.close();
    }
    catch ( IOException ex1 ) {
        //Idem...
    }
}

I hope I have helped.

Have a nice day. :)

No Main class found in NetBeans

if all that is your code you forgot to close the main method

everything else sounds good to me

public class LuisRp3 {

public static void main(String[] args) throws FileNotFoundException  {

    java.io.File newFile = new java.io.File("LuisRamosp4.txt");

    if (newFile.exists()) {
        newFile.delete();
    }

    System.setOut(new PrintStream(newFile));

    Guitar guitar = new Guitar(); 
}}

try that

GridView VS GridLayout in Android Apps

A GridView is a ViewGroup that displays items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.

This is what you'd want to use (keep using). Because a GridView gets its data from a ListAdapter, the only data loaded in memory will be the one displayed on screen. GridViews, much like ListViews reuse and recycle their views for better performance.

Whereas a GridLayout is a layout that places its children in a rectangular grid.

It was introduced in API level 14, and was recently backported in the Support Library. Its main purpose is to solve alignment and performance problems in other layouts. Check out this tutorial if you want to learn more about GridLayout.

Using python's eval() vs. ast.literal_eval()?

datamap = eval(input('Provide some data here: ')) means that you actually evaluate the code before you deem it to be unsafe or not. It evaluates the code as soon as the function is called. See also the dangers of eval.

ast.literal_eval raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.

Use ast.literal_eval whenever you need eval. You shouldn't usually evaluate literal Python statements.

Install a Python package into a different directory using pip?

If you are using brew with python, unfortunately, pip/pip3 ships with very limited options. You do not have --install-option, --target, --user options as mentioned above.

Note on pip install --user
The normal pip install --user is disabled for brewed Python. This is because of a bug in distutils, because Homebrew writes a distutils.cfg which sets the package prefix. A possible workaround (which puts executable scripts in ~/Library/Python/./bin) is: python -m pip install --user --install-option="--prefix=" <package-name>

You might find this line very cumbersome. I suggest use pyenv for management. If you are using

brew upgrade python python3

Ironically you are actually downgrade pip functionality.

(I post this answer, simply because pip in my mac osx does not have --target option, and I have spent hours fixing it)

Entity Framework Provider type could not be loaded?

I just had the same error message.

I have a separate project for my data access. Running the Web Project (which referenced the data project) locally worked just fine. But when I deployed the web project to azure the assembly: EntityFramework.SqlServer was not copied. I just added the reference to the web project and redeployed, now it works.

hope this helps others

Maven: how to override the dependency added by a library

What you put inside the </dependencies> tag of the root pom will be included by all child modules of the root pom. If all your modules use that dependency, this is the way to go.

However, if only 3 out of 10 of your child modules use some dependency, you do not want this dependency to be included in all your child modules. In that case, you can just put the dependency inside the </dependencyManagement>. This will make sure that any child module that needs the dependency must declare it in their own pom file, but they will use the same version of that dependency as specified in your </dependencyManagement> tag.

You can also use the </dependencyManagement> to modify the version used in transitive dependencies, because the version declared in the upper most pom file is the one that will be used. This can be useful if your project A includes an external project B v1.0 that includes another external project C v1.0. Sometimes it happens that a security breach is found in project C v1.0 which is corrected in v1.1, but the developers of B are slow to update their project to use v1.1 of C. In that case, you can simply declare a dependency on C v1.1 in your project's root pom inside `, and everything will be good (assuming that B v1.0 will still be able to compile with C v1.1).

How do I indent multiple lines at once in Notepad++?

Just install the NppAutoIndent plug-in, select Plugins > NppAutoIndent > Ignore Language and then Plugins > NppAutoIndent > Smart Indent.

How do I prevent Eclipse from hanging on startup?

I had a very similar problem with eclipse (Juno) on Fedora 18. In the middle of debugging an Android session, eclipse ended the debug session. I attempted to restart eclipse but it kept haning at the splash screen. I tried the various suggestions above with no success. Finally, I checked the adb service (android debug bridge):

# adb devices
List of devices attached 
XXXXXX offline

I know the android device was still connected but it reported it offline. I disconnected the device and shut down the adb service:

# adb kill-server

Then I waited a few seconds and re-started the adb service:

# adb start-server

And plugged my android back in. After that, eclipse started up just fine.

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

I faced exactly the same issue in a Spring web app. In fact, I had removed spring-security by commenting the config annotation:

// @ImportResource({"/WEB-INF/spring-security.xml"})

but I had forgotten to remove the corresponding filters in web.xml:

<!-- Filters --> 
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

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

Commenting filters solved the issue.

Changing date format in R

After reading your data in via a textConnection, the following seems to work:

dat <- read.table(textConnection(txt), header = TRUE)
dat$date <- strptime(dat$date, format= "%d/%m/%Y")
format(dat$date, format="%Y-%m-%d")

> format(dat$date, format="%Y-%m-%d")
 [1] "2011-08-31" "2011-07-31" "2011-06-30" "2011-05-31" "2011-04-30" "2011-03-31"
 [7] "2011-02-28" "2011-01-31" "2010-12-31" "2010-11-30" "2010-10-31" "2010-09-30"
[13] "2010-08-31" "2010-07-31" "2010-06-30" "2010-05-31" "2010-04-30" "2010-03-31"
[19] "2010-02-28" "2010-01-31" "2009-12-31" "2009-11-30" "2009-10-31"

> str(dat)
'data.frame':   23 obs. of  2 variables:
 $ date    : POSIXlt, format: "2011-08-31" "2011-07-31" "2011-06-30" ...
 $ midpoint: num  0.838 0.846 0.815 0.797 0.788 ...

What does -Xmn jvm option stands for

From GC Performance Tuning training documents of Oracle:

-Xmn[size]: Size of young generation heap space.

Applications with emphasis on performance tend to use -Xmn to size the young generation, because it combines the use of -XX:MaxNewSize and -XX:NewSize and almost always explicitly sets -XX:PermSize and -XX:MaxPermSize to the same value.

In short, it sets the NewSize and MaxNewSize values of New generation to the same value.

How to install latest version of git on CentOS 7.x/6.x

It can be very confusing, and dangerous, to replace the upstream base repositories with add-on repositories without considerable testing and thought. RPMforge, in particularly, is effectively moribund and is not getting updates.

I personally publish tools for building git 2.4, wrapped as an alternatively named "git24" package, at https://github.com/nkadel/git24-srpm/. Feel free to access and fork those if you want packages distinguished from the standard system packages, much as "samba" and "samba4" packages are differentiated.

SQL Server SELECT INTO @variable?

I found your question looking for a solution to the same problem; and what other answers fail to point is a way to use a variable to change the name of the table for every execution of your procedure in a permanent form, not temporary.

So far what I do is concatenate the entire SQL code with the variables to use. Like this:

declare @table_name as varchar(30)
select @table_name = CONVERT(varchar(30), getdate(), 112)
set @table_name = 'DAILY_SNAPSHOT_' + @table_name

EXEC('
        SELECT var1, var2, var3
        INTO '+@table_name+'
        FROM my_view
        WHERE string = ''Strings must use double apostrophe''
    ');

I hope it helps, but it could be cumbersome if the code is too large, so if you've found a better way, please share!

How to analyze a JMeter summary report?

A Jmeter Test Plan must have listener to showcase the result of performance test execution.

  • Listeners capture the response coming back from Server while Jmeter runs and showcase in the form of – tree, tables, graphs and log files.

  • It also allows you to save the result in a file for future reference. There are many types of listeners Jmeter provides. Some of them are: Summary Report, Aggregate Report, Aggregate Graph, View Results Tree, View Results in Table etc.

Here is the detailed understanding of each parameter in Summary report.

By referring to the figure:

image

Label: It is the name/URL for the specific HTTP(s) Request. If you have selected “Include group name in label?” option then the name of the Thread Group is applied as the prefix to each label.

Samples: This indicates the number of virtual users per request.

Average: It is the average time taken by all the samples to execute specific label. In our case, the average time for Label 1 is 942 milliseconds & total average time is 584 milliseconds.

Min: The shortest time taken by a sample for specific label. If we look at Min value for Label 1 then, out of 20 samples shortest response time one of the sample had was 584 milliseconds.

Max: The longest time taken by a sample for specific label. If we look at Max value for Label 1 then, out of 20 samples longest response time one of the sample had was 2867 milliseconds.

Std. Dev.: This shows the set of exceptional cases which were deviating from the average value of sample response time. The lesser this value more consistent the data. Standard deviation should be less than or equal to half of the average time for a label.

Error%: Percentage of Failed requests per Label.

Throughput: Throughput is the number of request that are processed per time unit(seconds, minutes, hours) by the server. This time is calculated from the start of first sample to the end of the last sample. Larger throughput is better.

KB/Sec: This indicates the amount of data downloaded from server during the performance test execution. In short, it is the Throughput measured in Kilobytes per second.

For more information: http://www.testingjournals.com/understand-summary-report-jmeter/

SQL Plus change current directory

I don't think that you can change the directory in SQL*Plus.

Instead of changing directory, you can use @@filename, which reads in another script whose location is relative to the directory the current script is running in. For example, if you have two scripts

C:\Foo\Bar\script1.sql
C:\Foo\Bar\Baz\script2.sql

then script1.sql can run script2.sql if it contains the line

@@Baz\script2.sql

See this for more info about @@.

Socket transport "ssl" in PHP not enabled

In XAMPP Version 1.7.4 server does not have extension=php_openssl.dll line in php ini file. We have to add extension=php_openssl.dll in php.ini file

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

If you're using a newer XAMPP (for example for PHP 5.6, 7) which is built with "Bitnami" installer and it includes Apache 2.4.x then this applies:

https://httpd.apache.org/docs/2.4/upgrading.html#run-time

2.2 configuration:

Order allow,deny
Allow from all

2.4 configuration:

Require all granted

This also applies to VirtualHost sections, if you have any custom virtualhost definitions.

how to resolve DTS_E_OLEDBERROR. in ssis

I've just had this issue and my problem was that I had null rows in a csv file, that contained the text "null" rather than being an empty.

How can I find out if I have Xcode commandline tools installed?

If for some reason xcode is not installed under

/usr/bin/xcodebuild

execute the following command

which xcodebuild

and if it is installed, you'll be prompted with it's location.

Postgresql Select rows where column = array

SELECT  *
FROM    table
WHERE   some_id = ANY(ARRAY[1, 2])

or ANSI-compatible:

SELECT  *
FROM    table
WHERE   some_id IN (1, 2)

The ANY syntax is preferred because the array as a whole can be passed in a bound variable:

SELECT  *
FROM    table
WHERE   some_id = ANY(?::INT[])

You would need to pass a string representation of the array: {1,2}

How to construct a WebSocket URI relative to the page URI?

easy:

location.href.replace(/^http/, 'ws') + '/to/ws'
// or if you hate regexp:
location.href.replace('http://', 'ws://').replace('https://', 'wss://') + '/to/ws'

Is there a reason for C#'s reuse of the variable in a foreach?

In C# 5.0, this problem is fixed and you can close over loop variables and get the results you expect.

The language specification says:

8.8.4 The foreach statement

(...)

A foreach statement of the form

foreach (V v in x) embedded-statement

is then expanded to:

{
  E e = ((C)(x)).GetEnumerator();
  try {
      while (e.MoveNext()) {
          V v = (V)(T)e.Current;
          embedded-statement
      }
  }
  finally {
      … // Dispose e
  }
}

(...)

The placement of v inside the while loop is important for how it is captured by any anonymous function occurring in the embedded-statement. For example:

int[] values = { 7, 9, 13 };
Action f = null;
foreach (var value in values)
{
    if (f == null) f = () => Console.WriteLine("First value: " + value);
}
f();

If v was declared outside of the while loop, it would be shared among all iterations, and its value after the for loop would be the final value, 13, which is what the invocation of f would print. Instead, because each iteration has its own variable v, the one captured by f in the first iteration will continue to hold the value 7, which is what will be printed. (Note: earlier versions of C# declared v outside of the while loop.)

Call PHP function from Twig template

I know this is an old thread. But with symfony 3.3 I did this:

{{ render(controller(
    'AppBundle\\Controller\\yourController::yourAction'
)) }}

Symfony docs

Node.js spawn child process and get terminal output live

Here is the cleanest approach I've found:

require("child_process").spawn('bash', ['./script.sh'], {
  cwd: process.cwd(),
  detached: true,
  stdio: "inherit"
});

Cross-reference (named anchor) in markdown

Use a name. Using an id isn't necessary in HTML 5 and will create global variables in your JavaScript

See the HTML 5 specification, 5.9.8 Navigating to a fragment identifier - both id and name are used.

It's important to know that most browsers still turn IDs into global variables. Here's a quick test. Using a name avoids creating globals and any conflicts that may result.

Example using a name:

Take me to [pookie](#pookie)

And the destination anchor:

### <a name="pookie"></a>Some heading

ORA-06502: PL/SQL: numeric or value error: character string buffer too small

CHAR is a fixed-length data type that uses as much space as possible. So a:= a||'one '; will require more space than is available. Your problem can be reduced to the following example:

declare
  v_foo char(50);
begin
  v_foo := 'A';
  dbms_output.put_line('length of v_foo(A) = ' || length(v_foo));
  -- next line will raise:
  -- ORA-06502: PL/SQL: numeric or value error: character string buffer too small
  v_foo := v_foo || 'B';
  dbms_output.put_line('length of v_foo(AB) = ' || length(v_foo));  
end;
/

Never use char. For rationale check the following question (read also the links):

php/mySQL on XAMPP: password for phpMyAdmin and mysql_connect different?

You need to change the password directly in the database because at mysql the users and their profiles are saved in the database.

So there are several ways. At phpMyAdmin you simple go to user admin, choose root and change the password.

Whether a variable is undefined

http://constc.blogspot.com/2008/07/undeclared-undefined-null-in-javascript.html

Depends on how specific you want the test to be. You could maybe get away with

if(page_name){ string += "&page_name=" + page_name; }

How to detect running app using ADB command

If you want to directly get the package name of the current app in focus, use this adb command -

adb shell dumpsys window windows | grep -E 'mFocusedApp'| cut -d / -f 1 | cut -d " " -f 7

Extra info from the result of the adb command is removed using the cut command. Original solution from here.

Temporarily change current working directory in bash to run a command

bash has a builtin

pushd SOME_PATH
run_stuff
...
...
popd 

Convert int to string?

string a = i.ToString();
string b = Convert.ToString(i);
string c = string.Format("{0}", i);
string d = $"{i}";
string e = "" + i;
string f = string.Empty + i;
string g = new StringBuilder().Append(i).ToString();

Copy multiple files in Python

import os
import shutil
os.chdir('C:\\') #Make sure you add your source and destination path below

dir_src = ("C:\\foooo\\")
dir_dst = ("C:\\toooo\\")

for filename in os.listdir(dir_src):
    if filename.endswith('.txt'):
        shutil.copy( dir_src + filename, dir_dst)
    print(filename)

NullInjectorError: No provider for AngularFirestore

I had same issue and below is resolved.

Old Service Code:

@Injectable()

Updated working Service Code:

@Injectable({
  providedIn: 'root'
})

JAXB Exception: Class not known to this context

I had this error because I registered the wrong class in this line of code:

JAXBContext context = JAXBContext.newInstance(MyRootXmlClass.class);

How to insert a string which contains an "&"

Stop using SQL/Plus, I highly recommend PL/SQL Developer it's much more than an SQL tool.

p.s. Some people prefer TOAD.

How to stop docker under Linux

In my case, it was neither systemd nor a cron job, but it was snap. So I had to run:

sudo snap stop docker
sudo snap remove docker

... and the last command actually never ended, I don't know why: this snap thing is really a pain. So I also ran:

sudo apt purge snap

:-)

TypeError: 'str' does not support the buffer interface

>>> s = bytes("s","utf-8")
>>> print(s)
b's'
>>> s = s.decode("utf-8")
>>> print(s)
s

Well if useful for you in case removing annoying 'b' character.If anyone got better idea please suggest me or feel free to edit me anytime in here.I'm just newbie

Simple JavaScript login form validation

Here is some useful links with example Login form Validation in javascript

function validate() {
        var username = document.getElementById("username").value;
        var password = document.getElementById("password").value;
        if (username == null || username == "") {
            alert("Please enter the username.");
            return false;
        }
        if (password == null || password == "") {
            alert("Please enter the password.");
            return false;
        }
        alert('Login successful');

    } 

  <input type="text" name="username" id="username" />
  <input type="password" name="password" id="password" />
  <input type="button" value="Login" id="submit" onclick="validate();" />

How to customise file type to syntax associations in Sublime Text?

There's an excellent plugin called ApplySyntax (previously DetectSyntax) that provides certain other niceties for file-syntax matching. allows regex expressions etc.

jQuery selector regular expressions

ids and classes are still attributes, so you can apply a regexp attribute filter to them if you select accordingly. Read more here: http://rosshawkins.net/archive/2011/10/14/jquery-wildcard-selectors-some-simple-examples.aspx

Laravel Fluent Query Builder Join with subquery

Query with sub query in Laravel

$resortData = DB::table('resort')
        ->leftJoin('country', 'resort.country', '=', 'country.id')
        ->leftJoin('states', 'resort.state', '=', 'states.id')
        ->leftJoin('city', 'resort.city', '=', 'city.id')
        ->select('resort.*', 'country.name as country_name', 'states.name as state_name','city.name as city_name', DB::raw("(SELECT GROUP_CONCAT(amenities.name) from resort_amenities LEFT JOIN amenities on amenities.id= resort_amenities.amenities_id WHERE resort_amenities.resort_id=resort.id) as amenities_name"))->groupBy('resort.id')
        ->orderBy('resort.id', 'DESC')
       ->get();

Set multiple system properties Java command line

If the required properties need to set in system then there is no option than -D But if you need those properties while bootstrapping an application then loading properties through the properties files is a best option. It will not require to change build for a single property.

Change "on" color of a Switch

The solution suggested from arlomedia worked for me. About his issue of extraspace I solved removing all the paddings to the switch.

EDIT

As requested, here what I have.

In the layout file, my switch is inside a linear layout and after a TextView.

<LinearLayout
        android:id="@+id/myLinearLayout"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_gravity="center_horizontal|center"
        android:gravity="right"
        android:padding="10dp"
        android:layout_marginTop="0dp"
        android:background="@drawable/bkg_myLinearLayout"
        android:layout_marginBottom="0dp">
        <TextView
            android:id="@+id/myTextForTheSwitch"
            android:layout_height="wrap_content"
            android:text="@string/TextForTheSwitch"
            android:textSize="18sp"
            android:layout_centerHorizontal="true"
            android:layout_gravity="center_horizontal|center"
            android:gravity="right"
            android:layout_width="wrap_content"
            android:paddingRight="20dp"
            android:textColor="@color/text_white" />
        <Switch
            android:id="@+id/mySwitch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textOn="@string/On"
            android:textOff="@string/Off"
            android:layout_centerHorizontal="true"
            android:layout_gravity="center_horizontal"
            android:layout_toRightOf="@id/myTextForTheSwitch"
            android:layout_alignBaseline="@id/myTextForTheSwitch"
            android:gravity="right" />
    </LinearLayout>

Since I'm working with Xamarin / Monodroid (min. Android 4.1) my code is:

Android.Graphics.Color colorOn = Android.Graphics.Color.Green;
Android.Graphics.Color colorOff = Android.Graphics.Color.Gray;
Android.Graphics.Color colorDisabled = Android.Graphics.Color.Green;

StateListDrawable drawable = new StateListDrawable();
drawable.AddState(new int[] { Android.Resource.Attribute.StateChecked }, new ColorDrawable(colorOn));
drawable.AddState(new int[] { -Android.Resource.Attribute.StateEnabled }, new ColorDrawable(colorDisabled));
drawable.AddState(new int[] { }, new ColorDrawable(colorOff));

swtch_EnableEdit.ThumbDrawable = drawable;

swtch_EnableEdit is previously defined like this (Xamarin):

Switch swtch_EnableEdit = view.FindViewById<Switch>(Resource.Id.mySwitch);

I don't set at all the paddings and I don't call .setPadding(0, 0, 0, 0).

C++ Vector of pointers

By dynamically allocating a Movie object with new Movie(), you get a pointer to the new object. You do not need a second vector for the movies, just store the pointers and you can access them. Like Brian wrote, the vector would be defined as

std::vector<Movie *> movies

But be aware that the vector will not delete your objects afterwards, which will result in a memory leak. It probably doesn't matter for your homework, but normally you should delete all pointers when you don't need them anymore.

How to maximize the browser window in Selenium WebDriver (Selenium 2) using C#?

using System.Windows.Forms;
using System.Drawing;

public static void MaximizeBrowser(this IE myBrowser)
{
    myBrowser.SizeWindow(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);
}

I used Jim's code, but slightly modified for use with WatiN and C# to maximize the browser.

Changing SQL Server collation to case insensitive from case sensitive?

You basically need to run the installation again to rebuild the master database with the new collation. You cannot change the entire server's collation any other way.

See:

Update: if you want to change the collation of a database, you can get the current collation using this snippet of T-SQL:

SELECT name, collation_name 
FROM sys.databases
WHERE name = 'test2'   -- put your database name here

This will yield a value something like:

Latin1_General_CI_AS

The _CI means "case insensitive" - if you want case-sensitive, use _CS in its place:

Latin1_General_CS_AS

So your T-SQL command would be:

ALTER DATABASE test2 -- put your database name here
   COLLATE Latin1_General_CS_AS   -- replace with whatever collation you need

You can get a list of all available collations on the server using:

SELECT * FROM ::fn_helpcollations()

You can see the server's current collation using:

SELECT SERVERPROPERTY ('Collation')

TypeError: cannot perform reduce with flexible type

When your are trying to apply prod on string type of value like:

['-214' '-153' '-58' ..., '36' '191' '-37']

you will get the error.

Solution: Append only integer value like [1,2,3], and you will get your expected output.

If the value is in string format before appending then, in the array you can convert the type into int type and store it in a list.

Can I send a ctrl-C (SIGINT) to an application on Windows?

Here is the code I use in my C++ app.

Positive points :

  • Works from console app
  • Works from Windows service
  • No delay required
  • Does not close the current app

Negative points :

  • The main console is lost and a new one is created (see FreeConsole)
  • The console switching give strange results...

// Inspired from http://stackoverflow.com/a/15281070/1529139
// and http://stackoverflow.com/q/40059902/1529139
bool signalCtrl(DWORD dwProcessId, DWORD dwCtrlEvent)
{
    bool success = false;
    DWORD thisConsoleId = GetCurrentProcessId();
    // Leave current console if it exists
    // (otherwise AttachConsole will return ERROR_ACCESS_DENIED)
    bool consoleDetached = (FreeConsole() != FALSE);

    if (AttachConsole(dwProcessId) != FALSE)
    {
        // Add a fake Ctrl-C handler for avoid instant kill is this console
        // WARNING: do not revert it or current program will be also killed
        SetConsoleCtrlHandler(nullptr, true);
        success = (GenerateConsoleCtrlEvent(dwCtrlEvent, 0) != FALSE);
        FreeConsole();
    }

    if (consoleDetached)
    {
        // Create a new console if previous was deleted by OS
        if (AttachConsole(thisConsoleId) == FALSE)
        {
            int errorCode = GetLastError();
            if (errorCode == 31) // 31=ERROR_GEN_FAILURE
            {
                AllocConsole();
            }
        }
    }
    return success;
}

Usage example :

DWORD dwProcessId = ...;
if (signalCtrl(dwProcessId, CTRL_C_EVENT))
{
    cout << "Signal sent" << endl;
}

What is the difference between id and class in CSS, and when should I use them?

The class attribute can be used with multiple HTML elements/tags and all will take the effect. Where as the id is meant for a single element/tag and is considered unique.

Moreoever the id has a higher specificity value than the class.

Using different Web.config in development and production environment

This is one of the huge benefits of using the machine.config. At my last job, we had development, test and production environments. We could use the machine.config for things like connection strings (to the appropriate, dev/test/prod SQL machine).

This may not be a solution for you if you don't have access to the actual production machine (like, if you were using a hosting company on a shared host).

npm install doesn't create node_modules directory

If you have a package-lock.json file, you may have to delete that file then run npm i. That worked for me

Opening Android Settings programmatically

I used the code from the most upvoted answer:

startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);

It opens the device settings in the same window, thus got the users of my android application (finnmglas/Launcher) for android stuck in there.

The answer for 2020 and beyond (in Kotlin):

startActivity(Intent(Settings.ACTION_SETTINGS))

It works in my app, should also be working in yours without any unwanted consequences.

gnuplot plotting multiple line graphs

Whatever your separator is in your ls.dat, you can specify it to gnuplot:

set datafile separator "\t"

How to copy a file to another path?

File.Move(@"c:\filename", @"c:\filenamet\filename.txt");

lodash multi-column sortBy descending

In the documentation of the version 4.11.x, says: ` "This method is like _.sortBy except that it allows specifying the sort orders of the iteratees to sort by. If orders is unspecified, all values are sorted in ascending order. Otherwise, specify an order of "desc" for descending or "asc" for ascending sort order of corresponding values." (source https://lodash.com/docs/4.17.10#orderBy)

let sorted = _.orderBy(this.items, ['fieldFoo', 'fieldBar'], ['asc', 'desc'])

for loop in Python

Try using this:

for k in range(1,c+1,2):

What does "xmlns" in XML mean?

You have name spaces so you can have globally unique elements. However, 99% of the time this doesn't really matter, but when you put it in the perspective of The Semantic Web, it starts to become important.

For example, you could make an XML mash-up of different schemes just by using the appropriate xmlns. For example, mash up friend of a friend with vCard, etc.

ImportError: No module named 'selenium'

Windows:

pip install selenium

Unix:

sudo pip install selenium

oracle sql: update if exists else insert

merge into MY_TABLE tgt
using (select [expressions]
         from dual ) src
   on (src.key_condition = tgt.key_condition)
when matched then 
     update tgt
        set tgt.column1 = src.column1 [,...]
when not matched then 
     insert into tgt
        ([list of columns])
     values
        (src.column1 [,...]);

I keep getting "Uncaught SyntaxError: Unexpected token o"

Simply the response is already parsed, you don't need to parse it again. if you parse it again it will give you "unexpected token o" however you have to specify datatype in your request to be of type dataType='json'

Try-catch block in Jenkins pipeline script

try/catch is scripted syntax. So any time you are using declarative syntax to use something from scripted in general you can do so by enclosing the scripted syntax in the scripts block in a declarative pipeline. So your try/catch should go inside stage >steps >script.

This holds true for any other scripted pipeline syntax you would like to use in a declarative pipeline as well.

Best way to compare dates in Android

Note that the right format is ("dd/MM/yyyy") before the code works. "mm" means minuts !

String valid_until = "01/07/2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = null;
try {
    strDate = sdf.parse(valid_until);
} catch (ParseException e) {
    e.printStackTrace();
}
if (new Date().after(strDate)) {
    catalog_outdated = 1;
}

How to do Base64 encoding in node.js?

I have created a ultimate small js npm library for the base64 encode/decode conversion in Node.js.

Installation

npm install nodejs-base64-converter --save

Usage

var nodeBase64 = require('nodejs-base64-converter');

console.log(nodeBase64.encode("test text")); //dGVzdCB0ZXh0
console.log(nodeBase64.decode("dGVzdCB0ZXh0")); //test text

How to get height of entire document with JavaScript?

To get the width in a cross browser/device way use:

function getActualWidth() {
    var actualWidth = window.innerWidth ||
                      document.documentElement.clientWidth ||
                      document.body.clientWidth ||
                      document.body.offsetWidth;

    return actualWidth;
}

SwiftUI - How do I change the background color of a View?

The code on Scene delegate in Swift UI

Content view background-color

window.rootViewController?.view.backgroundColor = .lightGray

Could not reserve enough space for object heap

Sometimes, this error indicates that physical memory and swap on the server actually are fully utilized!

I was seeing this problem recently on a server running RedHat Enterprise Linux 5.7 with 48 GB of RAM. I found that even just running

java -version

caused the same error, which established that the problem was not specific to my application.

Running

cat /proc/meminfo

reported that MemFree and SwapFree were both well under 1% of the MemTotal and SwapTotal values, respectively:

MemTotal:     49300620 kB
MemFree:        146376 kB
...
SwapTotal:     4192956 kB
SwapFree:         1364 kB

Stopping a few other running applications on the machine brought the free memory figures up somewhat:

MemTotal:     49300620 kB
MemFree:       2908664 kB
...
SwapTotal:     4192956 kB
SwapFree:      1016052 kB

At this point, a new instance of Java would start up okay, and I was able to run my application.

(Obviously, for me, this was just a temporary solution; I still have an outstanding task to do a more thorough examination of the processes running on that machine to see if there's something that can be done to reduce the nominal memory utilization levels, without having to resort to stopping applications.)

jQuery .scrollTop(); + animation

Simple solution:

scrolling to any element by ID or NAME:

SmoothScrollTo("#elementId", 1000);

code:

function SmoothScrollTo(id_or_Name, timelength){
    var timelength = timelength || 1000;
    $('html, body').animate({
        scrollTop: $(id_or_Name).offset().top-70
    }, timelength, function(){
        window.location.hash = id_or_Name;
    });
}

Check if URL has certain string with PHP

worked for me with php

if(strpos($_SERVER['REQUEST_URI'], 'shop.php') !== false){
echo 'url contains shop';
}

How to convert datetime format to date format in crystal report using C#?

This formula works for me:

// Converts CR TimeDate format to AssignDate for WeightedAverageDate calculation.

Date( Year({DWN00500.BUDDT}), Month({DWN00500.BUDDT}), Day({DWN00500.BUDDT}) ) - CDate(1899, 12, 30)

How to check for file existence

Check out Pathname and in particular Pathname#exist?.

File and its FileTest module are perhaps simpler/more direct, but I find Pathname a nicer interface in general.

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

Docker can't connect to docker daemon

If you get the message Can't connect to docker daemon. Is 'docker -d' running on this host?, you can check it by docker version.

If you see the information like Docker Client is running. but Docker Server is not, it's obviously you need to start the Docker server.

In CentOS, you can use service to start or stop the Docker server.

$ sudo service docker stop
$ sudo service docker start

Then, after you type docker version, you will get the information of Docker Client and Docker Server, and the Docker daemon has been started.

How to remove tab indent from several lines in IDLE?

If you're using IDLE, and the Norwegian keyboard makes Ctrl-[ a problem, you can change the key.

  1. Go Options->Configure IDLE.
  2. Click the Keys tab.
  3. If necessary, click Save as New Custom Key Set.
  4. With your custom key set, find "dedent-region" in the list.
  5. Click Get New Keys for Selection.
  6. etc

I tried putting in shift-Tab and that worked nicely.

How to query between two dates using Laravel and Eloquent?

If you want to check if current date exist in between two dates in db: =>here the query will get the application list if employe's application from and to date is exist in todays date.

$list=  (new LeaveApplication())
            ->whereDate('from','<=', $today)
            ->whereDate('to','>=', $today)
            ->get();

Hour from DateTime? in 24 hours format

You can get the desired result with the code below. Two'H' in HH is for 24-hour format.

return fechaHora.Value.ToString("HH:mm");

How to programmatically set the SSLContext of a JAX-WS client?

You can move your proxy authentication and ssl staff to soap handler

  port = new SomeService().getServicePort();
  Binding binding = ((BindingProvider) port).getBinding();
  binding.setHandlerChain(Collections.<Handler>singletonList(new ProxyHandler()));

This is my example, do all network ops

  class ProxyHandler implements SOAPHandler<SOAPMessageContext> {
    static class TrustAllHost implements HostnameVerifier {
      public boolean verify(String urlHostName, SSLSession session) {
        return true;
      }
    }

    static class TrustAllCert implements X509TrustManager {
      public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return null;
      }

      public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
      }

      public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
      }
    }

    private SSLSocketFactory socketFactory;

    public SSLSocketFactory getSocketFactory() throws Exception {
      // just an example
      if (socketFactory == null) {
        SSLContext sc = SSLContext.getInstance("SSL");
        TrustManager[] trustAllCerts = new TrustManager[] { new TrustAllCert() };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        socketFactory = sc.getSocketFactory();
      }

      return socketFactory;
    }

    @Override public boolean handleMessage(SOAPMessageContext msgCtx) {
      if (!Boolean.TRUE.equals(msgCtx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)))
        return true;

      HttpURLConnection http = null;

      try {
        SOAPMessage outMessage = msgCtx.getMessage();
        outMessage.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8");
        // outMessage.setProperty(SOAPMessage.WRITE_XML_DECLARATION, true); // Not working. WTF?

        ByteArrayOutputStream message = new ByteArrayOutputStream(2048);
        message.write("<?xml version='1.0' encoding='UTF-8'?>".getBytes("UTF-8"));
        outMessage.writeTo(message);

        String endpoint = (String) msgCtx.get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
        URL service = new URL(endpoint);

        Proxy proxy = Proxy.NO_PROXY;
        //Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("{proxy.url}", {proxy.port}));

        http = (HttpURLConnection) service.openConnection(proxy);
        http.setReadTimeout(60000); // set your timeout
        http.setConnectTimeout(5000);
        http.setUseCaches(false);
        http.setDoInput(true);
        http.setDoOutput(true);
        http.setRequestMethod("POST");
        http.setInstanceFollowRedirects(false);

        if (http instanceof HttpsURLConnection) {
          HttpsURLConnection https = (HttpsURLConnection) http;
          https.setHostnameVerifier(new TrustAllHost());
          https.setSSLSocketFactory(getSocketFactory());
        }

        http.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
        http.setRequestProperty("Content-Length", Integer.toString(message.size()));
        http.setRequestProperty("SOAPAction", "");
        http.setRequestProperty("Host", service.getHost());
        //http.setRequestProperty("Proxy-Authorization", "Basic {proxy_auth}");

        InputStream in = null;
        OutputStream out = null;

        try {
          out = http.getOutputStream();
          message.writeTo(out);
        } finally {
          if (out != null) {
            out.flush();
            out.close();
          }
        }

        int responseCode = http.getResponseCode();
        MimeHeaders responseHeaders = new MimeHeaders();
        message.reset();

        try {
          in = http.getInputStream();
          IOUtils.copy(in, message);
        } catch (final IOException e) {
          try {
            in = http.getErrorStream();
            IOUtils.copy(in, message);
          } catch (IOException e1) {
            throw new RuntimeException("Unable to read error body", e);
          }
        } finally {
          if (in != null)
            in.close();
        }

        for (Map.Entry<String, List<String>> header : http.getHeaderFields().entrySet()) {
          String name = header.getKey();

          if (name != null)
            for (String value : header.getValue())
              responseHeaders.addHeader(name, value);
        }

        SOAPMessage inMessage = MessageFactory.newInstance()
          .createMessage(responseHeaders, new ByteArrayInputStream(message.toByteArray()));

        if (inMessage == null)
          throw new RuntimeException("Unable to read server response code " + responseCode);

        msgCtx.setMessage(inMessage);
        return false;
      } catch (Exception e) {
        throw new RuntimeException("Proxy error", e);
      } finally {
        if (http != null)
          http.disconnect();
      }
    }

    @Override public boolean handleFault(SOAPMessageContext context) {
      return false;
    }

    @Override public void close(MessageContext context) {
    }

    @Override public Set<QName> getHeaders() {
      return Collections.emptySet();
    }
  }

It use UrlConnection, you can use any library you want in handler. Have fun!

How to open my files in data_folder with pandas using relative path?

Pandas will start looking from where your current python file is located. Therefore you can move from your current directory to where your data is located with '..' For example:

pd.read_csv('../../../data_folder/data.csv')

Will go 3 levels up and then into a data_folder (assuming it's there) Or

pd.read_csv('data_folder/data.csv')

assuming your data_folder is in the same directory as your .py file.

Hide password with "•••••••" in a textField

You can do this by using properties of textfield from Attribute inspector

Tap on Your Textfield from storyboard and go to Attribute inspector , and just check the checkbox of "Secure Text Entry" SS is added for graphical overview to achieve same

JVM heap parameters

The JVM will start with memory useage at the initial heap level. If the maxheap is higher, it will grow to the maxheap size as memory requirements exceed it's current memory.

So,

  • -Xms512m -Xmx512m

JVM starts with 512 M, never resizes.

  • -Xms64m -Xmx512m

JVM starts with 64M, grows (up to max ceiling of 512) if mem. requirements exceed 64.

How to load a UIView using a nib file created with Interface Builder

This is a great question (+1) and the answers were almost helpful ;) Sorry guys, but I had a heck of a time slogging through this, though both Gonso & AVeryDev gave good hints. Hopefully, this answer will help others.

MyVC is the view controller holding all this stuff.

MySubview is the view that we want to load from a xib

  • In MyVC.xib, create a view of type MySubView that is the right size & shape & positioned where you want it.
  • In MyVC.h, have

    IBOutlet MySubview *mySubView
    // ...
    @property (nonatomic, retain) MySubview *mySubview;
    
  • In MyVC.m, @synthesize mySubView; and don't forget to release it in dealloc.

  • In MySubview.h, have an outlet/property for UIView *view (may be unnecessary, but worked for me.) Synthesize & release it in .m
  • In MySubview.xib
    • set file owner type to MySubview, and link the view property to your view.
    • Lay out all the bits & connect to the IBOutlet's as desired
  • Back in MyVC.m, have

    NSArray *xibviews = [[NSBundle mainBundle] loadNibNamed: @"MySubview" owner: mySubview options: NULL];
    MySubview *msView = [xibviews objectAtIndex: 0];
    msView.frame = mySubview.frame;
    UIView *oldView = mySubview;
    // Too simple: [self.view insertSubview: msView aboveSubview: mySubview];
    [[mySubview superview] insertSubview: msView aboveSubview: mySubview]; // allows nesting
    self.mySubview = msView;
    [oldCBView removeFromSuperview];
    

The tricky bit for me was: the hints in the other answers loaded my view from the xib, but did NOT replace the view in MyVC (duh!) -- I had to swap that out on my own.

Also, to get access to mySubview's methods, the view property in the .xib file must be set to MySubview. Otherwise, it comes back as a plain-old UIView.

If there's a way to load mySubview directly from its own xib, that'd rock, but this got me where I needed to be.

What is the equivalent of Select Case in Access SQL?

Consider the Switch Function as an alternative to multiple IIf() expressions. It will return the value from the first expression/value pair where the expression evaluates as True, and ignore any remaining pairs. The concept is similar to the SELECT ... CASE approach you referenced but which is not available in Access SQL.

If you want to display a calculated field as commission:

SELECT
    Switch(
        OpeningBalance < 5001, 20,
        OpeningBalance < 10001, 30,
        OpeningBalance < 20001, 40,
        OpeningBalance >= 20001, 50
        ) AS commission
FROM YourTable;

If you want to store that calculated value to a field named commission:

UPDATE YourTable
SET commission =
    Switch(
        OpeningBalance < 5001, 20,
        OpeningBalance < 10001, 30,
        OpeningBalance < 20001, 40,
        OpeningBalance >= 20001, 50
        );

Either way, see whether you find Switch() easier to understand and manage. Multiple IIf()s can become mind-boggling as the number of conditions grows.

How can I check if a string is a number?

You should use the TryParse method for the int

string text1 = "x";
    int num1;
    bool res = int.TryParse(text1, out num1);
    if (res == false)
    {
        // String is not a number.
    }

Scale iFrame css width 100% like an image

Big difference between an image and an iframe is the fact that an image keeps its aspect-ratio. You could combine an image and an iframe with will result in a responsive iframe. Hope this answerers your question.

Check this link for example : http://jsfiddle.net/Masau/7WRHM/

HTML:

<div class="wrapper">
    <div class="h_iframe">
        <!-- a transparent image is preferable -->
        <img class="ratio" src="http://placehold.it/16x9"/>
        <iframe src="http://www.youtube.com/embed/WsFWhL4Y84Y" frameborder="0" allowfullscreen></iframe>
    </div>
    <p>Please scale the "result" window to notice the effect.</p>
</div>

CSS:

html,body        {height:100%;}
.wrapper         {width:80%;height:100%;margin:0 auto;background:#CCC}
.h_iframe        {position:relative;}
.h_iframe .ratio {display:block;width:100%;height:auto;}
.h_iframe iframe {position:absolute;top:0;left:0;width:100%; height:100%;}

note: This only works with a fixed aspect-ratio.

Using numpy to build an array of all combinations of two arrays

Pandas merge offers a naive, fast solution to the problem:

# given the lists
x, y, z = [1, 2, 3], [4, 5], [6, 7]

# get dfs with same, constant index 
x = pd.DataFrame({'x': x}, index=np.repeat(0, len(x))
y = pd.DataFrame({'y': y}, index=np.repeat(0, len(y))
z = pd.DataFrame({'z': z}, index=np.repeat(0, len(z))

# get all permutations stored in a new df
df = pd.merge(x, pd.merge(y, z, left_index=True, righ_index=True),
              left_index=True, right_index=True)

FloatingActionButton example with Support Library

for AndroidX use like

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/ic_add" />

Add a link to an image in a css style sheet

You could do something like

<a href="http://home.com"><img src="images/logo.png" alt="" id="logo"></a>

in HTML

Cannot catch toolbar home button click event

In my case I had to put the icon using:

toolbar.setNavigationIcon(R.drawable.ic_my_home);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);

And then listen to click events with default onOptionsItemSelected and android.R.id.home id

Delayed function calls

It's indeed a very bad design, let alone singleton by itself is bad design.

However, if you really do need to delay execution, here's what you may do:

BackgroundWorker barInvoker = new BackgroundWorker();
barInvoker.DoWork += delegate
    {
        Thread.Sleep(TimeSpan.FromSeconds(1));
        bar();
    };
barInvoker.RunWorkerAsync();

This will, however, invoke bar() on a separate thread. If you need to call bar() in the original thread you might need to move bar() invocation to RunWorkerCompleted handler or do a bit of hacking with SynchronizationContext.

How to add Class in <li> using wp_nav_menu() in Wordpress?

Without walker menu it's not possible to directly add it. You can, however, add it by javascript.

$('#menu > li').addClass('class_name');

Use the auto keyword in C++ STL

This is new item in the language which I think we are going to be struggling with for years to come. The 'auto' of the start presents not only readability problem , from now on when you encounter it you will have to spend considerable time trying to figure out wtf it is(just like the time that intern named all variables xyz :)), but you also will spend considerable time cleaning after easily excitable programmers , like the once who replied before me. Example from above , I can bet $1000 , will be written "for (auto it : s)", not "for (auto& it : s)", as a result invoking move semantics where you list expecting it, modifying your collection underneath .

Another example of the problem is your question itself. You clearly don't know much about stl iterators and you trying to overcome that gap through usage of the magic of 'auto', as a result you create the code that might be problematic later on

Sending SMS from PHP

Clickatell is a popular SMS gateway. It works in 200+ countries.

Their API offers a choice of connection options via: HTTP/S, SMPP, SMTP, FTP, XML, SOAP. Any of these options can be used from php.

The HTTP/S method is as simple as this:

http://api.clickatell.com/http/sendmsg?to=NUMBER&msg=Message+Body+Here

The SMTP method consists of sending a plain-text e-mail to: [email protected], with the following body:

user: xxxxx
password: xxxxx
api_id: xxxxx
to: 448311234567
text: Meet me at home

You can also test the gateway (incoming and outgoing) for free from your browser

Postgresql - unable to drop database because of some auto connections to DB

Simply check what is the connection, where it's coming from. You can see all this in:

SELECT * FROM pg_stat_activity WHERE datname = 'TARGET_DB';

Perhaps it is your connection?

jquery - return value using ajax result on success

Add async: false to your attributes list. This forces the javascript thread to wait until the return value is retrieved before moving on. Obviously, you wouldn't want to do this in every circumstance, but if a value is needed before proceeding, this will do it.

How does the "this" keyword work?

The this keyword behaves differently in JavaScript compared to other languages. In Object Oriented languages, the this keyword refers to the current instance of the class. In JavaScript the value of this is determined by the invocation context of function (context.function()) and where it is called.

1. When used in global context

When you use this in global context, it is bound to global object (window in browser)

document.write(this);  //[object Window]

When you use this inside a function defined in the global context, this is still bound to global object since the function is actually made a method of global context.

function f1()
{
   return this;
}
document.write(f1());  //[object Window]

Above f1 is made a method of global object. Thus we can also call it on window object as follows:

function f()
{
    return this;
}

document.write(window.f()); //[object Window]

2. When used inside object method

When you use this keyword inside an object method, this is bound to the "immediate" enclosing object.

var obj = {
    name: "obj",
    f: function () {
        return this + ":" + this.name;
    }
};
document.write(obj.f());  //[object Object]:obj

Above I have put the word immediate in double quotes. It is to make the point that if you nest the object inside another object, then this is bound to the immediate parent.

var obj = {
    name: "obj1",
    nestedobj: {
        name:"nestedobj",
        f: function () {
            return this + ":" + this.name;
        }
    }            
}

document.write(obj.nestedobj.f()); //[object Object]:nestedobj

Even if you add function explicitly to the object as a method, it still follows above rules, that is this still points to the immediate parent object.

var obj1 = {
    name: "obj1",
}

function returnName() {
    return this + ":" + this.name;
}

obj1.f = returnName; //add method to object
document.write(obj1.f()); //[object Object]:obj1

3. When invoking context-less function

When you use this inside function that is invoked without any context (i.e. not on any object), it is bound to the global object (window in browser)(even if the function is defined inside the object) .

var context = "global";

var obj = {  
    context: "object",
    method: function () {                  
        function f() {
            var context = "function";
            return this + ":" +this.context; 
        };
        return f(); //invoked without context
    }
};

document.write(obj.method()); //[object Window]:global 

Trying it all with functions

We can try above points with functions too. However there are some differences.

  • Above we added members to objects using object literal notation. We can add members to functions by using this. to specify them.
  • Object literal notation creates an instance of object which we can use immediately. With function we may need to first create its instance using new operator.
  • Also in an object literal approach, we can explicitly add members to already defined object using dot operator. This gets added to the specific instance only. However I have added variable to the function prototype so that it gets reflected in all instances of the function.

Below I tried out all the things that we did with Object and this above, but by first creating function instead of directly writing an object.

/********************************************************************* 
  1. When you add variable to the function using this keyword, it 
     gets added to the function prototype, thus allowing all function 
     instances to have their own copy of the variables added.
*********************************************************************/
function functionDef()
{
    this.name = "ObjDefinition";
    this.getName = function(){                
        return this+":"+this.name;
    }
}        

obj1 = new functionDef();
document.write(obj1.getName() + "<br />"); //[object Object]:ObjDefinition   

/********************************************************************* 
   2. Members explicitly added to the function protorype also behave 
      as above: all function instances have their own copy of the 
      variable added.
*********************************************************************/
functionDef.prototype.version = 1;
functionDef.prototype.getVersion = function(){
    return "v"+this.version; //see how this.version refers to the
                             //version variable added through 
                             //prototype
}
document.write(obj1.getVersion() + "<br />"); //v1

/********************************************************************* 
   3. Illustrating that the function variables added by both above 
      ways have their own copies across function instances
*********************************************************************/
functionDef.prototype.incrementVersion = function(){
    this.version = this.version + 1;
}
var obj2 = new functionDef();
document.write(obj2.getVersion() + "<br />"); //v1

obj2.incrementVersion();      //incrementing version in obj2
                              //does not affect obj1 version

document.write(obj2.getVersion() + "<br />"); //v2
document.write(obj1.getVersion() + "<br />"); //v1

/********************************************************************* 
   4. `this` keyword refers to the immediate parent object. If you 
       nest the object through function prototype, then `this` inside 
       object refers to the nested object not the function instance
*********************************************************************/
functionDef.prototype.nestedObj = { name: 'nestedObj', 
                                    getName1 : function(){
                                        return this+":"+this.name;
                                    }                            
                                  };

document.write(obj2.nestedObj.getName1() + "<br />"); //[object Object]:nestedObj

/********************************************************************* 
   5. If the method is on an object's prototype chain, `this` refers 
      to the object the method was called on, as if the method was on 
      the object.
*********************************************************************/
var ProtoObj = { fun: function () { return this.a } };
var obj3 = Object.create(ProtoObj); //creating an object setting ProtoObj
                                    //as its prototype
obj3.a = 999;                       //adding instance member to obj3
document.write(obj3.fun()+"<br />");//999
                                    //calling obj3.fun() makes 
                                    //ProtoObj.fun() to access obj3.a as 
                                    //if fun() is defined on obj3

4. When used inside constructor function.

When the function is used as a constructor (that is when it is called with new keyword), this inside function body points to the new object being constructed.

var myname = "global context";
function SimpleFun()
{
    this.myname = "simple function";
}

var obj1 = new SimpleFun(); //adds myname to obj1
//1. `new` causes `this` inside the SimpleFun() to point to the
//   object being constructed thus adding any member
//   created inside SimipleFun() using this.membername to the
//   object being constructed
//2. And by default `new` makes function to return newly 
//   constructed object if no explicit return value is specified

document.write(obj1.myname); //simple function

5. When used inside function defined on prototype chain

If the method is on an object's prototype chain, this inside such method refers to the object the method was called on, as if the method is defined on the object.

var ProtoObj = {
    fun: function () {
        return this.a;
    }
};
//Object.create() creates object with ProtoObj as its
//prototype and assigns it to obj3, thus making fun() 
//to be the method on its prototype chain

var obj3 = Object.create(ProtoObj);
obj3.a = 999;
document.write(obj3.fun()); //999

//Notice that fun() is defined on obj3's prototype but 
//`this.a` inside fun() retrieves obj3.a   

6. Inside call(), apply() and bind() functions

  • All these methods are defined on Function.prototype.
  • These methods allows to write a function once and invoke it in different context. In other words, they allows to specify the value of this which will be used while the function is being executed. They also take any parameters to be passed to the original function when it is invoked.
  • fun.apply(obj1 [, argsArray]) Sets obj1 as the value of this inside fun() and calls fun() passing elements of argsArray as its arguments.
  • fun.call(obj1 [, arg1 [, arg2 [,arg3 [, ...]]]]) - Sets obj1 as the value of this inside fun() and calls fun() passing arg1, arg2, arg3, ... as its arguments.
  • fun.bind(obj1 [, arg1 [, arg2 [,arg3 [, ...]]]]) - Returns the reference to the function fun with this inside fun bound to obj1 and parameters of fun bound to the parameters specified arg1, arg2, arg3,....
  • By now the difference between apply, call and bind must have become apparent. apply allows to specify the arguments to function as array-like object i.e. an object with a numeric length property and corresponding non-negative integer properties. Whereas call allows to specify the arguments to the function directly. Both apply and call immediately invokes the function in the specified context and with the specified arguments. On the other hand, bind simply returns the function bound to the specified this value and the arguments. We can capture the reference to this returned function by assigning it to a variable and later we can call it any time.
function add(inc1, inc2)
{
    return this.a + inc1 + inc2;
}

var o = { a : 4 };
document.write(add.call(o, 5, 6)+"<br />"); //15
      //above add.call(o,5,6) sets `this` inside
      //add() to `o` and calls add() resulting:
      // this.a + inc1 + inc2 = 
      // `o.a` i.e. 4 + 5 + 6 = 15
document.write(add.apply(o, [5, 6]) + "<br />"); //15
      // `o.a` i.e. 4 + 5 + 6 = 15

var g = add.bind(o, 5, 6);       //g: `o.a` i.e. 4 + 5 + 6
document.write(g()+"<br />");    //15

var h = add.bind(o, 5);          //h: `o.a` i.e. 4 + 5 + ?
document.write(h(6) + "<br />"); //15
      // 4 + 5 + 6 = 15
document.write(h() + "<br />");  //NaN
      //no parameter is passed to h()
      //thus inc2 inside add() is `undefined`
      //4 + 5 + undefined = NaN</code>

7. this inside event handlers

  • When you assign function directly to event handlers of an element, use of this directly inside event handling function refers to the corresponding element. Such direct function assignment can be done using addeventListener method or through the traditional event registration methods like onclick.
  • Similarly, when you use this directly inside the event property (like <button onclick="...this..." >) of the element, it refers to the element.
  • However use of this indirectly through the other function called inside the event handling function or event property resolves to the global object window.
  • The same above behavior is achieved when we attach the function to the event handler using Microsoft's Event Registration model method attachEvent. Instead of assigning the function to the event handler (and the thus making the function method of the element), it calls the function on the event (effectively calling it in global context).

I recommend to better try this in JSFiddle.

<script> 
    function clickedMe() {
       alert(this + " : " + this.tagName + " : " + this.id);
    } 
    document.getElementById("button1").addEventListener("click", clickedMe, false);
    document.getElementById("button2").onclick = clickedMe;
    document.getElementById("button5").attachEvent('onclick', clickedMe);   
</script>

<h3>Using `this` "directly" inside event handler or event property</h3>
<button id="button1">click() "assigned" using addEventListner() </button><br />
<button id="button2">click() "assigned" using click() </button><br />
<button id="button3" onclick="alert(this+ ' : ' + this.tagName + ' : ' + this.id);">used `this` directly in click event property</button>

<h3>Using `this` "indirectly" inside event handler or event property</h3>
<button onclick="alert((function(){return this + ' : ' + this.tagName + ' : ' + this.id;})());">`this` used indirectly, inside function <br /> defined & called inside event property</button><br />

<button id="button4" onclick="clickedMe()">`this` used indirectly, inside function <br /> called inside event property</button> <br />

IE only: <button id="button5">click() "attached" using attachEvent() </button>

8. this in ES6 arrow function

In an arrow function, this will behave like common variables: it will be inherited from its lexical scope. The function's this, where the arrow function is defined, will be the arrow function's this.

So, that's the same behavior as:

(function(){}).bind(this)

See the following code:

const globalArrowFunction = () => {
  return this;
};

console.log(globalArrowFunction()); //window

const contextObject = {
  method1: () => {return this},
  method2: function(){
    return () => {return this};
  }
};

console.log(contextObject.method1()); //window

const contextLessFunction = contextObject.method1;

console.log(contextLessFunction()); //window

console.log(contextObject.method2()()) //contextObject

const innerArrowFunction = contextObject.method2();

console.log(innerArrowFunction()); //contextObject 

ResourceDictionary in a separate assembly

Check out the pack URI syntax. You want something like this:

<ResourceDictionary Source="pack://application:,,,/YourAssembly;component/Subfolder/YourResourceFile.xaml"/>

Creating a JSON Array in node js

This one helped me,

res.format({
        json:function(){
                            var responseData    = {};
                            responseData['status'] = 200;
                            responseData['outputPath']  = outputDirectoryPath;
                            responseData['sourcePath']  = url;
                            responseData['message'] = 'Scraping of requested resource initiated.';
                            responseData['logfile'] = logFileName;
                            res.json(JSON.stringify(responseData));
                        }
    });

Fastest way to check a string is alphanumeric in Java

A regex will probably be quite efficient, because you would specify ranges: [0-9a-zA-Z]. Assuming the implementation code for regexes is efficient, this would simply require an upper and lower bound comparison for each range. Here's basically what a compiled regex should do:

boolean isAlphanumeric(String str) {
    for (int i=0; i<str.length(); i++) {
        char c = str.charAt(i);
        if (c < 0x30 || (c >= 0x3a && c <= 0x40) || (c > 0x5a && c <= 0x60) || c > 0x7a)
            return false;
    }

    return true;
}

I don't see how your code could be more efficient than this, because every character will need to be checked, and the comparisons couldn't really be any simpler.

How to draw lines in Java

I built a whole class of methods to draw points, lines, rectangles, circles, etc. I designed it to treat the window as a piece of graph paper where the origin doesn't have to be at the top left and the y values increase as you go up. Here's how I draw lines:

public static void drawLine (double x1, double y1, double x2, double y2)
{       
    ((Graphics2D)g).draw(new Line2D.Double(x0+x1*scale, y0-y1*scale, x0+x2*scale, y0-y2*scale));
}

In the example above, (x0, y0) represents the origin in screen coordinates and scale is a scaling factor. The input parameters are to be supplied as graph coordinates, not screen coordinates. There is no repaint() being called. You can save that til you've drawn all the lines you need.

It occurs to me that someone might not want to think in terms of graph paper:

    ((Graphics2D)g).draw(new Line2D.Double(x1, y1, x2, y2));

Notice the use of Graphics2D. This allows us to draw a Line2D object using doubles instead of ints. Besides other shapes, my class has support for 3D perspective drawing and several convenience methods (like drawing a circle centered at a certain point given a radius.) If anyone is interested, I would be happy to share more of this class.

How to do something to each file in a directory with a batch script

I had some malware that marked all files in a directory as hidden/system/readonly. If anyone else finds themselves in this situation, cd into the directory and run for /f "delims=|" %f in ('forfiles') do attrib -s -h -r %f.

PHP Adding 15 minutes to Time value

Though you can do this through PHP's time functions, let me introduce you to PHP's DateTime class, which along with it's related classes, really should be in any PHP developer's toolkit.

// note this will set to today's current date since you are not specifying it in your passed parameter. This probably doesn't matter if you are just going to add time to it.
$datetime = DateTime::createFromFormat('g:i:s', $selectedTime);
$datetime->modify('+15 minutes');
echo $datetime->format('g:i:s');

Note that if what you are looking to do is basically provide a 12 or 24 hours clock functionality to which you can add/subtract time and don't actually care about the date, so you want to eliminate possible problems around daylights saving times changes an such I would recommend one of the following formats:

!g:i:s 12-hour format without leading zeroes on hour

!G:i:s 12-hour format with leading zeroes

Note the ! item in format. This would set date component to first day in Linux epoch (1-1-1970)

how to make label visible/invisible?

you could try

if (isValid) {
    document.getElementById("endTimeLabel").style.display = "none";
}else {
    document.getElementById("endTimeLabel").style.display = "block";
}

alone those lines

Can the :not() pseudo-class have multiple arguments?

If you're using SASS in your project, I've built this mixin to make it work the way we all want it to:

@mixin not($ignorList...) {
    //if only a single value given
    @if (length($ignorList) == 1){
        //it is probably a list variable so set ignore list to the variable
        $ignorList: nth($ignorList,1);
    }
    //set up an empty $notOutput variable
    $notOutput: '';
    //for each item in the list
    @each $not in $ignorList {
        //generate a :not([ignored_item]) segment for each item in the ignore list and put them back to back
        $notOutput: $notOutput + ':not(#{$not})';
    }
    //output the full :not() rule including all ignored items
    &#{$notOutput} {
        @content;
    }
}

it can be used in 2 ways:

Option 1: list the ignored items inline

input {
  /*non-ignored styling goes here*/
  @include not('[type="radio"]','[type="checkbox"]'){
    /*ignored styling goes here*/
  }
}

Option 2: list the ignored items in a variable first

$ignoredItems:
  '[type="radio"]',
  '[type="checkbox"]'
;

input {
  /*non-ignored styling goes here*/
  @include not($ignoredItems){
    /*ignored styling goes here*/
  }
}

Outputted CSS for either option

input {
    /*non-ignored styling goes here*/
}

input:not([type="radio"]):not([type="checkbox"]) {
    /*ignored styling goes here*/
}

Is it possible to send an array with the Postman Chrome extension?

It is important to know, that the VALUE box is only allowed to contain a numeral value (no specifiers).

If you want to send e.g. an array of "messages" with Postman, each having a list of key/value pairs, enter e.g. messages[][reason] into the KEY box and the value of reason into the VALUE box:

enter image description here

The server will receive:

{"messages"=>[{"reason"=>"scrolled", "tabid"=>"2"}, {"reason"=>"reload", "tabid"=>"1"}], "endpoint"=>{}}

How can I iterate over the elements in Hashmap?

Need Key & Value in Iteration

Use entrySet() to iterate through Map and need to access value and key:

Map<String, Person> hm = new HashMap<String, Person>();

hm.put("A", new Person("p1"));
hm.put("B", new Person("p2"));
hm.put("C", new Person("p3"));
hm.put("D", new Person("p4"));
hm.put("E", new Person("p5"));

Set<Map.Entry<String, Person>> set = hm.entrySet();

for (Map.Entry<String, Person> me : set) {
  System.out.println("Key :"+me.getKey() +" Name : "+ me.getValue().getName()+"Age :"+me.getValue().getAge());

}

Need Key in Iteration

If you want just to iterate over keys of map you can use keySet()

for(String key: map.keySet()) {
     Person value = map.get(key); 
}

Need Value in Iteration

If you just want to iterate over values of map you can use values()

for(Person person: map.values()) {

}

CRC32 C or C++ implementation

rurban's fork of SMHasher (the original SMHasher seems abandoned) has hardware CRC32 support. The changes were added before the initial commit, but try comparing the new CMakeLists.txt and the old one (which doesn't mention SSE at all).

The best option is probably Intel's zlib fork with PCLMULQDQ support described in this paper. This library also has the SSE 4.2 optimizations.

If you don't need portability and you're on Linux, you can use the kernel's implementation (which is hardware accelerated if available): https://stackoverflow.com/a/11156040/309483

How to .gitignore all files/folder in a folder, but not the folder itself?

Put this .gitignore into the folder, then git add .gitignore.

*
*/
!.gitignore

The * line tells git to ignore all files in the folder, but !.gitignore tells git to still include the .gitignore file. This way, your local repository and any other clones of the repository all get both the empty folder and the .gitignore it needs.

Edit: May be obvious but also add */ to the .gitignore to also ignore subfolders.

What's the idiomatic syntax for prepending to a short python list?

The s.insert(0, x) form is the most common.

Whenever you see it though, it may be time to consider using a collections.deque instead of a list.

Calculating how many minutes there are between two times

Try this

DateTime startTime = varValue
DateTime endTime = varTime

TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( "Time Difference (minutes): " + span.TotalMinutes );

Edit: If are you trying 'span.Minutes', this will return only the minutes of timespan [0~59], to return sum of all minutes from this interval, just use 'span.TotalMinutes'.

Vim multiline editing like in sublimetext?

I'm not sure what vim is doing, but it is an interesting effect. The way you're describing what you want sounds more like how macros work (:help macro). Something like this would do what you want with macros (starting in normal-mode):

  1. qa: Record macro to a register.
  2. 0w: 0 goto start of line, w jump one word.
  3. i"<Esc>: Enter insert-mode, insert a " and return to normal-mode.
  4. 2e: Jump to end of second word.
  5. a"<Esc>: Append a ".
  6. jq Move to next line and end macro recording.

Taken together: qa0wi"<Esc>2ea"<Esc>

Now you can execute the macro with @a, repeat last macro with @@. To apply to the rest of the file, do something like 99@a which assumes you do not have more than 99 lines, macro execution will end when it reaches end of file.

Here is how to achieve what you want with visual-block-mode (starting in normal mode):

  1. Navigate to where you want the first quote to be.
  2. Enter visual-block-mode, select the lines you want to affect, G to go to the bottom of the file.
  3. Hit I"<Esc>.
  4. Move to the next spot you want to insert a ".
  5. You want to repeat what you just did so a simple . will suffice.

VBA Count cells in column containing specified value

If you're looking to match non-blank values or empty cells and having difficulty with wildcard character, I found the solution below from here.

Dim n as Integer
n = Worksheets("Sheet1").Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count

SELECT CASE WHEN THEN (SELECT)

I ended up leaving the common properties from the SELECT queries and making a second SELECT query later on in the page. I used a php IF command to call for different scripts depending on the first SELECT query, the scripts contained the second SELECT query.