Programs & Examples On #Openbd

OpenBD is an open source GPL Java and Google App Engine CFML runtime.

The maximum value for an int type in Go

A lightweight package contains them (as well as other int types limits and some widely used integer functions):

import (
    "fmt"
    "<Full URL>/go-imath/ix"
    "<Full URL>/go-imath/ux"
)
...
fmt.Println(ix.Minimal) // Output: -2147483648 (32-bit) or -9223372036854775808 (64-bit)
fmt.Println(ix.Maximal) // Output: 2147483647 or 9223372036854775807
fmt.Println(ux.Minimal) // Output: 0
fmt.Println(ux.Maximal) // Output: 4294967295 or 18446744073709551615

Why do I get "a label can only be part of a statement and a declaration is not a statement" if I have a variable that is initialized after a label?

The language standard simply doesn't allow for it. Labels can only be followed by statements, and declarations do not count as statements in C. The easiest way to get around this is by inserting an empty statement after your label, which relieves you from keeping track of the scope the way you would need to inside a block.

#include <stdio.h>
int main () 
{
    printf("Hello ");
    goto Cleanup;
Cleanup: ; //This is an empty statement.
    char *str = "World\n";
    printf("%s\n", str);
}

DateTimePicker: pick both date and time

Unfortunately, this is one of the many misnomers in the framework, or at best a violation of SRP.

To use the DateTimePicker for times, set the Format property to either Time or Custom (Use Custom if you want to control the format of the time using the CustomFormat property). Then set the ShowUpDown property to true.

Although a user may set the date and time together manually, they cannot use the GUI to set both.

Is it possible to have different Git configuration for different projects?

There are 3 levels of git config; project, global and system.

  • project: Project configs are only available for the current project and stored in .git/config in the project's directory.
  • global: Global configs are available for all projects for the current user and stored in ~/.gitconfig.
  • system: System configs are available for all the users/projects and stored in /etc/gitconfig.

Create a project specific config, you have to execute this under the project's directory:

$ git config user.name "John Doe" 

Create a global config:

$ git config --global user.name "John Doe"

Create a system config:

$ git config --system user.name "John Doe" 

And as you may guess, project overrides global and global overrides system.

Note: Project configs are local to just one particular copy/clone of this particular repo, and need to be reapplied if the repo is recloned clean from the remote. It changes a local file that is not sent to the remote with a commit/push.

React - Display loading screen while DOM is rendering?

Edit your index.html file location in the public folder. Copy your image to same location as index.html in public folder. And then replace the part of the contents of index.html containing <div id="root"> </div> tags to the below given html code.

<div id="root">  <img src="logo-dark300w.png" alt="Spideren" style="vertical-align: middle; position: absolute;
   top: 50%;
   left: 50%;
   margin-top: -100px; /* Half the height */
   margin-left: -250px; /* Half the width */" />  </div>

Logo will now appear in the middle of the page during the loading process. And will then be replaced after a few seconds by React.

Eclipse IDE: How to zoom in on text?

Just by pressing Ctrl + Shift + '+' or '-'.

At least, it worked for me at Eclipse "2020-03" version.

How to get JS variable to retain value after page refresh?

In addition to cookies and localStorage, there's at least one other place you can store "semi-persistent" client data: window.name. Any string value you assign to window.name will stay there until the window is closed.

To test it out, just open the console and type window.name = "foo", then refresh the page and type window.name; it should respond with foo.

This is a bit of a hack, but if you don't want cookies filled with unnecessary data being sent to the server with every request, and if you can't use localStorage for whatever reason (legacy clients), it may be an option to consider.

window.name has another interesting property: it's visible to windows served from other domains; it's not subject to the same-origin policy like nearly every other property of window. So, in addition to storing "semi-persistent" data there while the user navigates or refreshes the page, you can also use it for CORS-free cross-domain communication.

Note that window.name can only store strings, but with the wide availability of JSON, this shouldn't be much of an issue even for complex data.

Detect whether there is an Internet connection available on Android

The getActiveNetworkInfo() method of ConnectivityManager returns a NetworkInfo instance representing the first connected network interface it can find or null if none of the interfaces are connected. Checking if this method returns null should be enough to tell if an internet connection is available or not.

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

You will also need:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

in your android manifest.

Edit:

Note that having an active network interface doesn't guarantee that a particular networked service is available. Network issues, server downtime, low signal, captive portals, content filters and the like can all prevent your app from reaching a server. For instance you can't tell for sure if your app can reach Twitter until you receive a valid response from the Twitter service.

How to output something in PowerShell

You can use any of these in your scenario since they write to the default streams (output and error). If you were piping output to another commandlet you would want to use Write-Output, which will eventually terminate in Write-Host.

This article describes the different output options: PowerShell O is for Output

VarBinary vs Image SQL Server Data Type to Store Binary Data?

There is also the rather spiffy FileStream, introduced in SQL Server 2008.

Setting Environment Variables for Node to retrieve

Environment variables (in this case) are being used to pass credentials to your application. USER_ID and USER_KEY can both be accessed from process.env.USER_ID and process.env.USER_KEY respectively. You don't need to edit them, just access their contents.

It looks like they are simply giving you the choice between loading your USER_ID and USER_KEY from either process.env or some specificed file on disk.

Now, the magic happens when you run the application.

USER_ID=239482 USER_KEY=foobar node app.js

That will pass the user id 239482 and the user key as foobar. This is suitable for testing, however for production, you will probably be configuring some bash scripts to export variables.

Correct use for angular-translate in controllers

What is happening is that Angular-translate is watching the expression with an event-based system, and just as in any other case of binding or two-way binding, an event is fired when the data is retrieved, and the value changed, which obviously doesn't work for translation. Translation data, unlike other dynamic data on the page, must, of course, show up immediately to the user. It can't pop in after the page loads.

Even if you can successfully debug this issue, the bigger problem is that the development work involved is huge. A developer has to manually extract every string on the site, put it in a .json file, manually reference it by string code (ie 'pageTitle' in this case). Most commercial sites have thousands of strings for which this needs to happen. And that is just the beginning. You now need a system of keeping the translations in synch when the underlying text changes in some of them, a system for sending the translation files out to the various translators, of reintegrating them into the build, of redeploying the site so the translators can see their changes in context, and on and on.

Also, as this is a 'binding', event-based system, an event is being fired for every single string on the page, which not only is a slower way to transform the page but can slow down all the actions on the page, if you start adding large numbers of events to it.

Anyway, using a post-processing translation platform makes more sense to me. Using GlobalizeIt for example, a translator can just go to a page on the site and start editing the text directly on the page for their language, and that's it: https://www.globalizeit.com/HowItWorks. No programming needed (though it can be programmatically extensible), it integrates easily with Angular: https://www.globalizeit.com/Translate/Angular, the transformation of the page happens in one go, and it always displays the translated text with the initial render of the page.

Full disclosure: I'm a co-founder :)

Local dependency in package.json

Actually, as of npm 2.0, there is support now local paths (see here).

Showing the stack trace from a running Python application

python -dv yourscript.py

That will make the interpreter to run in debug mode and to give you a trace of what the interpreter is doing.

If you want to interactively debug the code you should run it like this:

python -m pdb yourscript.py

That tells the python interpreter to run your script with the module "pdb" which is the python debugger, if you run it like that the interpreter will be executed in interactive mode, much like GDB

SSL certificate is not trusted - on mobile only

Put your domain name here: https://www.ssllabs.com/ssltest/analyze.html You should be able to see if there are any issues with your ssl certificate chain. I am guessing that you have SSL chain issues. A short description of the problem is that there's actually a list of certificates on your server (and not only one) and these need to be in the correct order. If they are there but not in the correct order, the website will be fine on desktop browsers (an iOs as well I think), but android is more strict about the order of certificates, and will give an error if the order is incorrect. To fix this you just need to re-order the certificates.

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

this works for me:

myTuple= tuple(myList)
sql="select fooid from foo where bar in "+str(myTuple)
cursor.execute(sql)

What are App Domains in Facebook Apps?

To add to the answers above, the App Domain is required for security reasons. For example, your app has been sending the browser to "www.example.com/PAGE_NAME_HERE", but suddenly a third party application (or something else) sends the user to "www.supposedlymaliciouswebsite.com/PAGE_HERE", then a 191 error is thrown saying that this wasn't part of the app domains you listed in your Facebook application settings.

Configuring diff tool with .gitconfig

Git offers a range of difftools pre-configured "out-of-the-box" (kdiff3, kompare, tkdiff, meld, xxdiff, emerge, vimdiff, gvimdiff, ecmerge, diffuse, opendiff, p4merge and araxis), and also allows you to specify your own. To use one of the pre-configured difftools (for example, "vimdiff"), you add the following lines to your ~/.gitconfig:

[diff]
    tool = vimdiff

Now, you will be able to run "git difftool" and use your tool of choice.

Specifying your own difftool, on the other hand, takes a little bit more work, see How do I view 'git diff' output with my preferred diff tool/ viewer?

BeanFactory not initialized or already closed - call 'refresh' before

In my case, the error "BeanFactory not initialized or already closed - call 'refresh' before" was a consequence of a previous error that I didn't noticed in the server startup. I think that it is not always the real cause of the problem.

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

Use next:

(1..10).each do |a|
  next if a.even?
  puts a
end

prints:

1
3   
5
7
9

For additional coolness check out also redo and retry.

Works also for friends like times, upto, downto, each_with_index, select, map and other iterators (and more generally blocks).

For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.

How do you add an SDK to Android Studio?

You have to put your SDK's in a given directory or .app directory. You have to do it in finder while you are out of the application i'm assuming, but personally I'd use terminal in Mac instead of doing it in the App itself or finder. According to Google:

On Windows and Mac, the individual tools and other SDK packages are saved within the Android Studio application directory. To access the tools directly, use a terminal to navigate into the application and locate the sdk/ directory. For example:

 Windows: \Users\<user>\AppData\Local\Android\android-studio\sdk\
 Mac: /Applications/Android\ Studio.app/sdk/

.htaccess file to allow access to images folder to view pictures?

Create a .htaccess file in the images folder and add this

<IfModule mod_rewrite.c>
RewriteEngine On
# directory browsing
Options All +Indexes
</IfModule>

you can put this Options All -Indexes in the project file .htaccess ,file to deny direct access to other folders.

This does what you want

AngularJS : Difference between the $observe and $watch methods

Why is $observe different than $watch?

The watchExpression is evaluated and compared to the previous value each digest() cycle, if there's a change in the watchExpression value, the watch function is called.

$observe is specific to watching for interpolated values. If a directive's attribute value is interpolated, eg dir-attr="{{ scopeVar }}", the observe function will only be called when the interpolated value is set (and therefore when $digest has already determined updates need to be made). Basically there's already a watcher for the interpolation, and the $observe function piggybacks off that.

See $observe & $set in compile.js

List all files and directories in a directory + subdirectories

Some improved version with max lvl to go down in directory and option to exclude folders:

using System;
using System.IO;

class MainClass {
  public static void Main (string[] args) {

    var dir = @"C:\directory\to\print";
    PrintDirectoryTree(dir, 2, new string[] {"folder3"});
  }


  public static void PrintDirectoryTree(string directory, int lvl, string[] excludedFolders = null, string lvlSeperator = "")
  {
    excludedFolders = excludedFolders ?? new string[0];

    foreach (string f in Directory.GetFiles(directory))
    {
        Console.WriteLine(lvlSeperator+Path.GetFileName(f));
    } 

    foreach (string d in Directory.GetDirectories(directory))
    {
        Console.WriteLine(lvlSeperator + "-" + Path.GetFileName(d));

        if(lvl > 0 && Array.IndexOf(excludedFolders, Path.GetFileName(d)) < 0)
        {
          PrintDirectoryTree(d, lvl-1, excludedFolders, lvlSeperator+"  ");
        }
    }
  }
}

input directory:

-folder1
  file1.txt
  -folder2
    file2.txt
    -folder5
      file6.txt
  -folder3
    file3.txt
  -folder4
    file4.txt
    file5.txt

output of the function (content of folder5 is excluded due to lvl limit and content of folder3 is excluded because it is in excludedFolders array):

-folder1
  file1.txt
  -folder2
    file2.txt
    -folder5
  -folder3
  -folder4
    file4.txt
    file5.txt

Is the Scala 2.8 collections library a case of "the longest suicide note in history"?

I don't know how to break it to you, but I have a PhD from Cambridge, and I'm using 2.8 just fine.

More seriously, I hardly spent any time with 2.7 (it won't inter-op with a Java library I am using) and started using Scala just over a month ago. I have some experience with Haskell (not much), but just ignored the stuff you're worried about and looked for methods that matched my experience with Java (which I use for a living).

So: I am a "new user" and I wasn't put off - the fact that it works like Java gave me enough confidence to ignore the bits I didn't understand.

(However, the reason I was looking at Scala was partly to see whether to push it at work, and I am not going to do so yet. Making the documentation less intimidating would certainly help, but what surprised me is how much it is still changing and being developed (to be fair what surprised me most was how awesome it is, but the changes came a close second). So I guess what I am saying is that I'd rather prefer the limited resources were put into getting it into a final state - I don't think they were expecting to be this popular this soon.)

Extract code country from phone number [libphonenumber]

Here's a an answer how to find country calling code without using third-party libraries (as real developer does):

Get list of all available country codes, Wikipedia can help here: https://en.wikipedia.org/wiki/List_of_country_calling_codes

Parse data in a tree structure where each digit is a branch.

Traverse your tree digit by digit until you are at the last branch - that's your country code.

How to draw a circle with text in the middle?

Using this code it will be responsive also.

<div class="circle">ICON</div>

.circle {
  position: relative;
  display: inline-block;
  width: 100%;
  height: 0;
  padding: 50% 0;
  border-radius: 50%;
  /* Just making it pretty */
  -webkit-box-shadow: 0 4px 0 0 rgba(0, 0, 0, 0.1);
  box-shadow: 0 4px 0 0 rgba(0, 0, 0, 0.1);
  text-shadow: 0 4px 0 rgba(0, 0, 0, 0.1);
  background: #38a9e4;
  color: white;
  font-family: Helvetica, Arial Black, sans;
  font-size: 48px;
  text-align: center;
}

ORA-01461: can bind a LONG value only for insert into a LONG column-Occurs when querying

Ok, well, since you didn't show any code, I'll make a few assumptions here.

Based on the ORA-1461 error, it seems that you've specified a LONG datatype in a select statement? And you're trying to bind it to an output variable? Is that right? The error is pretty straight forward. You can only bind a LONG value for insert into LONG column.

Not sure what else to say. The error is fairly self-explanatory.

In general, it's a good idea to move away from LONG datatype to a CLOB. CLOBs are much better supported, and LONG datatypes really are only there for backward compatibility.

Here's a list of LONG datatype restrictions

Hope that helps.

Conditionally hide CommandField or ButtonField in Gridview

If this was based on roles you could use the multiview panel but not sure if you could do the same against a property of the record.

However, you could do this via code. In your rowdatabound event you can hide or show the button in it.

How to use ng-if to test if a variable is defined

You can still use angular.isDefined()

You just need to set

$rootScope.angular = angular;

in the "run" phase.

See update plunkr: http://plnkr.co/edit/h4ET5dJt3e12MUAXy1mS?p=preview

Python 2.7 getting user input and manipulating as string without quotations

We can use the raw_input() function in Python 2 and the input() function in Python 3. By default the input function takes an input in string format. For other data type you have to cast the user input.

In Python 2 we use the raw_input() function. It waits for the user to type some input and press return and we need to store the value in a variable by casting as our desire data type. Be careful when using type casting

x = raw_input("Enter a number: ") #String input

x = int(raw_input("Enter a number: ")) #integer input

x = float(raw_input("Enter a float number: ")) #float input

x = eval(raw_input("Enter a float number: ")) #eval input

In Python 3 we use the input() function which returns a user input value.

x = input("Enter a number: ") #String input

If you enter a string, int, float, eval it will take as string input

x = int(input("Enter a number: ")) #integer input

If you enter a string for int cast ValueError: invalid literal for int() with base 10:

x = float(input("Enter a float number: ")) #float input

If you enter a string for float cast ValueError: could not convert string to float

x = eval(input("Enter a float number: ")) #eval input

If you enter a string for eval cast NameError: name ' ' is not defined Those error also applicable for Python 2.

Best way to check for nullable bool in a condition expression (if ...)

If you're in a situation where you don't have control over whether part of the condition is checking a nullable value, you can always try the following:

if( someInt == 6 && someNullableBool == null ? false : (bool)someNullableBool){
    //perform your actions if true
}

I know it's not exactly a purist approach putting a ternary in an if statement but it does resolve the issue cleanly.

This is, of course, a manual way of saying GetValueOrDefault(false)

How to remove RVM (Ruby Version Manager) from my system

Run:

rvm implode

Now you need to uninstall the RVM gem using:

gem uninstall rvm

Check if there are any remaining RVM files in your home directory, if yes remove them.

Go to the home directory and list all hidden files:

ls -a

rm  .rvm
rm  .rvmrc

Fatal error compiling: invalid target release: 1.8 -> [Help 1]

As mentioned by Camila Macedo - you have to explicitly point the java version for compiler-plugin. For spring boot you can do that by next property:

  <properties>
    <java.version>1.8</java.version>
    <maven.compiler.release>8</maven.compiler.release>
  </properties>

Git - What is the difference between push.default "matching" and "simple"

Git v2.0 Release Notes

Backward compatibility notes

When git push [$there] does not say what to push, we have used the traditional "matching" semantics so far (all your branches were sent to the remote as long as there already are branches of the same name over there). In Git 2.0, the default is now the "simple" semantics, which pushes:

  • only the current branch to the branch with the same name, and only when the current branch is set to integrate with that remote branch, if you are pushing to the same remote as you fetch from; or

  • only the current branch to the branch with the same name, if you are pushing to a remote that is not where you usually fetch from.

You can use the configuration variable "push.default" to change this. If you are an old-timer who wants to keep using the "matching" semantics, you can set the variable to "matching", for example. Read the documentation for other possibilities.

When git add -u and git add -A are run inside a subdirectory without specifying which paths to add on the command line, they operate on the entire tree for consistency with git commit -a and other commands (these commands used to operate only on the current subdirectory). Say git add -u . or git add -A . if you want to limit the operation to the current directory.

git add <path> is the same as git add -A <path> now, so that git add dir/ will notice paths you removed from the directory and record the removal. In older versions of Git, git add <path> used to ignore removals. You can say git add --ignore-removal <path> to add only added or modified paths in <path>, if you really want to.

Using Jasmine to spy on a function without an object

There is 2 alternative which I use (for jasmine 2)

This one is not quite explicit because it seems that the function is actually a fake.

test = createSpy().and.callFake(test); 

The second more verbose, more explicit, and "cleaner":

test = createSpy('testSpy', test).and.callThrough();

-> jasmine source code to see the second argument

Replace part of a string in Python?

You can easily use .replace() as also previously described. But it is also important to keep in mind that strings are immutable. Hence if you do not assign the change you are making to a variable, then you will not see any change. Let me explain by;

    >>stuff = "bin and small"
    >>stuff.replace('and', ',')
    >>print(stuff)
    "big and small" #no change

To observe the change you want to apply, you can assign same or another variable;

    >>stuff = "big and small"
    >>stuff = stuff.replace("and", ",")   
    >>print(stuff)
    'big, small'

finished with non zero exit value

I was also getting this issue.

  • I generally face this issue when I import some sample or already existing module into my project.
  • I just added latest v7 and v4 to my project from maven in android studio and got it fixed
  • Removed duplicate dependencies from project like wise if your library project and application project are using v7 or v4 or any other library , they should be of same version. or try to have it only in your library project

How to manually install an artifact in Maven 2?

If you ever get similar errors when using Windows PowerShell, you should try Windows' simple command-line. I didn't find out what caused this, but PowerShell seems to interpret some of Maven's parameters.

Vue.js redirection to another page

If you are using vue-router, you should use router.go(path) to navigate to any particular route. The router can be accessed from within a component using this.$router.

Otherwise, window.location.href = 'some url'; works fine for non single-page apps.

EDIT: router.go() changed in VueJS 2.0. You can use router.push({ name: "yourroutename"}) or just router.push("yourroutename") now to redirect.

Documentation

P.S: In controllers use: this.$router.push({ name: 'routename' })

Creating a Custom Event

Based on @ionden's answer, the call to the delegate could be simplified using null propagation since C# 6.0.

Your code would simply be:

class MyClass {
    public event EventHandler MyEvent;

    public void Method() {
        MyEvent?.Invoke(this, EventArgs.Empty);
    }
}

Use it like this:

MyClass myObject = new MyClass();
myObject.MyEvent += new EventHandler(myObject_MyEvent);
myObject.Method();

When do items in HTML5 local storage expire?

@sebarmeli's approach is the best in my opinion, but if you only want data to persist for the life of a session then sessionStorage is probably a better option:

This is a global object (sessionStorage) that maintains a storage area that's available for the duration of the page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.

MDN: sessionStorage

Git Cherry-Pick and Conflicts

Do, I need to resolve all the conflicts before proceeding to next cherry -pick

Yes, at least with the standard git setup. You cannot cherry-pick while there are conflicts.

Furthermore, in general conflicts get harder to resolve the more you have, so it's generally better to resolve them one by one.

That said, you can cherry-pick multiple commits at once, which would do what you are asking for. See e.g. How to cherry-pick multiple commits . This is useful if for example some commits undo earlier commits. Then you'd want to cherry-pick all in one go, so you don't have to resolve conflicts for changes that are undone by later commits.

Further, is it suggested to do cherry-pick or branch merge in this case?

Generally, if you want to keep a feature branch up to date with main development, you just merge master -> feature branch. The main advantage is that a later merge feature branch -> master will be much less painful.

Cherry-picking is only useful if you must exclude some changes in master from your feature branch. Still, this will be painful so I'd try to avoid it.

Convert a string to integer with decimal in Python

How about this?

>>> s = '23.45678'
>>> int(float(s))
23

Or...

>>> int(Decimal(s))
23

Or...

>>> int(s.split('.')[0])
23

I doubt it's going to get much simpler than that, I'm afraid. Just accept it and move on.

Reinitialize Slick js after successful ajax call

This should work.

$.ajax({
    type: 'get',
    url: '/public/index',
    dataType: 'script',
    data: data_send,
    success: function() {
        $('.skills_section').slick('reinit');
      }
});

how to set value of a input hidden field through javascript?

The first thing I will try - determine if your code with alerts is actually rendered. I see some server "if" code in what you posted, so may be condition to render javascript is not satisfied. So, on the page you working on, right-click -> view source. Try to find the js code there. Please tell us if you found the code on the page.

How to make grep only match if the entire line matches?

Most suggestions will fail if there so much as a single leading or trailing space, which would matter if the file is being edited by hand. This would make it less susceptible in that case:

grep '^[[:blank:]]*ABB\.log[[:blank:]]*$' a.tmp

A simple while-read loop in shell would do this implicitly:

while read file
do 
  case $file in
    (ABB.log) printf "%s\n" "$file"
  esac
done < a.tmp

std::string length() and size() member functions

When using coding practice tools(LeetCode) it seems that size() is quicker than length() (although basically negligible)

Intellij Cannot resolve symbol on import

Please try File-> Synchronize. Then close and reopen IntelliJ before you invalidate.

Once I restarted. I would have invalidated but the synchronize cleared everything after restarting.

Is it possible to forward-declare a function in Python?

I apologize for reviving this thread, but there was a strategy not discussed here which may be applicable.

Using reflection it is possible to do something akin to forward declaration. For instance lets say you have a section of code that looks like this:

# We want to call a function called 'foo', but it hasn't been defined yet.
function_name = 'foo'
# Calling at this point would produce an error

# Here is the definition
def foo():
    bar()

# Note that at this point the function is defined
    # Time for some reflection...
globals()[function_name]()

So in this way we have determined what function we want to call before it is actually defined, effectively a forward declaration. In python the statement globals()[function_name]() is the same as foo() if function_name = 'foo' for the reasons discussed above, since python must lookup each function before calling it. If one were to use the timeit module to see how these two statements compare, they have the exact same computational cost.

Of course the example here is very useless, but if one were to have a complex structure which needed to execute a function, but must be declared before (or structurally it makes little sense to have it afterwards), one can just store a string and try to call the function later.

How to stop an unstoppable zombie job on Jenkins without restarting the server?

Go to "Manage Jenkins" > "Script Console" to run a script on your server to interrupt the hanging thread.

You can get all the live threads with Thread.getAllStackTraces() and interrupt the one that's hanging.

Thread.getAllStackTraces().keySet().each() {
  t -> if (t.getName()=="YOUR THREAD NAME" ) {   t.interrupt();  }
}

UPDATE:

The above solution using threads may not work on more recent Jenkins versions. To interrupt frozen pipelines refer to this solution (by alexandru-bantiuc) instead and run:

Jenkins.instance.getItemByFullName("JobName")
                .getBuildByNumber(JobNumber)
                .finish(
                        hudson.model.Result.ABORTED,
                        new java.io.IOException("Aborting build")
                );

Disable browser 'Save Password' functionality

The cleanest way is to use autocomplete="off" tag attribute but Firefox does not properly obey it when you switch fields with Tab.

The only way you could stop this is to add a fake hidden password field which tricks the browser to populate the password there.

<input type="text" id="username" name="username"/>
<input type="password" id="prevent_autofill" autocomplete="off" style="display:none" tabindex="-1" />
<input type="password" id="password" autocomplete="off" name="password"/>

It is an ugly hack, because you change the browser behavior, which should be considered bad practice. Use it only if you really need it.

Note: this will effectively stop password autofill, because FF will "save" the value of #prevent_autofill (which is empty) and will try to populate any saved passwords there, as it always uses the first type="password" input it finds in DOM after the respective "username" input.

How to hide a div after some time period?

setTimeout('$("#someDivId").hide()',1500);

LabelEncoder: TypeError: '>' not supported between instances of 'float' and 'str'

Or use a cast with split to uniform type of str

unique, counts = numpy.unique(str(a).split(), return_counts=True)

Argparse optional positional arguments?

Use nargs='?' (or nargs='*' if you need more than one dir)

parser.add_argument('dir', nargs='?', default=os.getcwd())

extended example:

>>> import os, argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-v', action='store_true')
_StoreTrueAction(option_strings=['-v'], dest='v', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('dir', nargs='?', default=os.getcwd())
_StoreAction(option_strings=[], dest='dir', nargs='?', const=None, default='/home/vinay', type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args('somedir -v'.split())
Namespace(dir='somedir', v=True)
>>> parser.parse_args('-v'.split())
Namespace(dir='/home/vinay', v=True)
>>> parser.parse_args(''.split())
Namespace(dir='/home/vinay', v=False)
>>> parser.parse_args(['somedir'])
Namespace(dir='somedir', v=False)
>>> parser.parse_args('somedir -h -v'.split())
usage: [-h] [-v] [dir]

positional arguments:
  dir

optional arguments:
  -h, --help  show this help message and exit
  -v

How to break out of a loop in Bash?

It's not that different in bash.

workdone=0
while : ; do
  ...
  if [ "$workdone" -ne 0 ]; then
      break
  fi
done

: is the no-op command; its exit status is always 0, so the loop runs until workdone is given a non-zero value.


There are many ways you could set and test the value of workdone in order to exit the loop; the one I show above should work in any POSIX-compatible shell.

No input file specified

Adding php5.ini doesn't work at all. But see the 'Disable FastCGI' section in this article on GoDaddy: http://support.godaddy.com/help/article/5121/changing-your-hosting-accounts-file-extensions

Add these lines to .htaccess files (webroot & website installation directory):

Options +ExecCGI
addhandler x-httpd-php5-cgi .php

It saves me a day! Cheers! Thanks DragonLord!

How to write lists inside a markdown table?

If you use the html approach:

don't add blank lines

Like this:

<table>
    <tbody>

        <tr>
            <td>1</td>
            <td>2</td>
        </tr>

        <tr>
            <td>1</td>
            <td>2</td>
        </tr>

    </tbody>
</table>

the markup will break.

Remove blank lines:

<table>
    <tbody>
        <tr>
            <td>1</td>
            <td>2</td>
        </tr>
        <tr>
            <td>1</td>
            <td>2</td>
        </tr>
    </tbody>
</table>

Check if an element is a child of a parent

If you are only interested in the direct parent, and not other ancestors, you can just use parent(), and give it the selector, as in target.parent('div#hello').

Example: http://jsfiddle.net/6BX9n/

function fun(evt) {
    var target = $(evt.target);    
    if (target.parent('div#hello').length) {
        alert('Your clicked element is having div#hello as parent');
    }
}

Or if you want to check to see if there are any ancestors that match, then use .parents().

Example: http://jsfiddle.net/6BX9n/1/

function fun(evt) {
    var target = $(evt.target);    
    if (target.parents('div#hello').length) {
        alert('Your clicked element is having div#hello as parent');
    }
}

Using OpenSSL what does "unable to write 'random state'" mean?

I have come accross this problem today on AWS Lambda. I created an environment variable RANDFILE = /tmp/.random

That did the trick.

importing jar libraries into android-studio

I also faced same obstacle but not able to find out solution from given answers. Might be it's happening due to project path which is having special characters & space etc... So please try to add this line in your build.gradle.

compile files('../app/libs/jtwitter.jar')// pass your .jar file name

".." (Double dot) will find your root directory of your project.

How can I make Bootstrap 4 columns all the same height?

Equal height columns is the default behaviour for Bootstrap 4 grids.

_x000D_
_x000D_
.col { background: red; }_x000D_
.col:nth-child(odd) { background: yellow; }
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
    </div>_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
      <br>_x000D_
      Line 2_x000D_
      <br>_x000D_
      Line 3_x000D_
    </div>_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Check if a specific tab page is selected (active)

This can work as well.

if (tabControl.SelectedTab.Text == "tabText" )
{
    .. do stuff
}

Extract Google Drive zip from Google colab notebook

To extract Google Drive zip from a Google colab notebook:

import zipfile
from google.colab import drive

drive.mount('/content/drive/')

zip_ref = zipfile.ZipFile("/content/drive/My Drive/ML/DataSet.zip", 'r')
zip_ref.extractall("/tmp")
zip_ref.close()

How to parse JSON in Scala using standard Scala classes?

scala.util.parsing.json.JSON is deprecated.

Here is another approach with circe. FYI documentation: https://circe.github.io/circe/cursors.html

Add the dependency in build.sbt, I used scala 2.13.4, note the scala version must align with the library version.

val circeVersion = "0.14.0-M2"

libraryDependencies ++= Seq(
  "io.circe"  %% "circe-core"     % circeVersion,
  "io.circe"  %% "circe-generic"  % circeVersion,
  "io.circe"  %% "circe-parser"   % circeVersion
)

Example 1:

case class Person(name: String, age: Int)

object Main {
  def main(args: Array[String]): Unit = {
    val input =
      """
        |{
        |  "kind": "Listing",
        |  "data": [
        |    {
        |      "name": "Frodo",
        |      "age": 51
        |    },
        |    {
        |      "name": "Bilbo",
        |      "age": 60
        |    }
        |  ]
        |}
        |""".stripMargin

    implicit val decoderPerson: Decoder[Person] = deriveDecoder[Person] // decoder required to parse to custom object

    val parseResult: Json = circe.parser.parse(input).getOrElse(Json.Null)
    val data: ACursor = parseResult.hcursor.downField("data") // get the data field
    val personList: List[Person] = data.as[List[Person]].getOrElse(null) // parse the dataField to a list of Person
    for {
      person <- personList
    } println(person.name + " is " + person.age)
  }
}

Example 2, json has an object within an object:

case class Person(name: String, age: Int, position: Position)
case class Position(x: Int, y: Int)

object Main {
  def main(args: Array[String]): Unit = {
    val input =
      """
        |{
        |  "kind": "Listing",
        |  "data": [
        |    {
        |      "name": "Frodo",
        |      "age": 51,
        |      "position": {
        |        "x": 10,
        |        "y": 20
        |      }
        |    },
        |    {
        |      "name": "Bilbo",
        |      "age": 60,
        |      "position": {
        |        "x": 75,
        |        "y": 85
        |      }
        |    }
        |  ]
        |}
        |""".stripMargin

    implicit val decoderPosition: Decoder[Position] = deriveDecoder[Position] // must be defined before the Person decoder
    implicit val decoderPerson: Decoder[Person] = deriveDecoder[Person]

    val parseResult = circe.parser.parse(input).getOrElse(Json.Null)
    val data = parseResult.hcursor.downField("data")
    val personList = data.as[List[Person]].getOrElse(null)
    for {
      person <- personList
    } println(person.name + " is " + person.age + " at " + person.position)
  }
}

How to create text file and insert data to that file on Android

Using this code you can write to a text file in the SDCard. Along with it, you need to set a permission in the Android Manifest.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

This is the code :

public void generateNoteOnSD(Context context, String sFileName, String sBody) {
    try {
        File root = new File(Environment.getExternalStorageDirectory(), "Notes");
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, sFileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
        Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Before writing files you must also check whether your SDCard is mounted & the external storage state is writable.

Environment.getExternalStorageState()

Center a H1 tag inside a DIV

You could add padding to the h1:

#AlertDiv h1 {
  padding:15px 18px;
}

How to build and run Maven projects after importing into Eclipse IDE

answer 1

  1. Right click on your project in eclipse
  2. go to maven -> Update Project

answer 2

simply press Alt+F5 after updating your pom.xml. This will build your project again and download all jar files

Dictionary text file

What about /usr/share/dict/words on any Unix system? How many words are we talking about? Like OED-Unabridged?

Jquery bind double click and single click separately

i am implementing this simple solution , http://jsfiddle.net/533135/VHkLR/5/
html code

<p>Click on this paragraph.</p>
<b> </b>

script code

var dbclick=false;    
$("p").click(function(){
setTimeout(function(){
if(dbclick ==false){
$("b").html("clicked")
}

},200)

}).dblclick(function(){
dbclick = true
$("b").html("dbclicked")
setTimeout(function(){
dbclick = false


},300)
});


its not much laggy

How to check if an user is logged in Symfony2 inside a controller?

If you using roles you could check for ROLE_USER that is the solution i use:

if (TRUE === $this->get('security.authorization_checker')->isGranted('ROLE_USER')) {
    // user is logged in
} 

jQuery - replace all instances of a character in a string

'some+multi+word+string'.replace(/\+/g, ' ');
                                   ^^^^^^

'g' = "global"

Cheers

Passing string to a function in C - with or without pointers?

The accepted convention of passing C-strings to functions is to use a pointer:

void function(char* name)

When the function modifies the string you should also pass in the length:

void function(char* name, size_t name_length)

Your first example:

char *functionname(char *string name[256])

passes an array of pointers to strings which is not what you need at all.

Your second example:

char functionname(char string[256])

passes an array of chars. The size of the array here doesn't matter and the parameter will decay to a pointer anyway, so this is equivalent to:

char functionname(char *string)

See also this question for more details on array arguments in C.

Run CRON job everyday at specific time

Cron utility is an effective way to schedule a routine background job at a specific time and/or day on an on-going basis.

Linux Crontab Format

MIN HOUR DOM MON DOW CMD

enter image description here

Example::Scheduling a Job For a Specific Time

The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM.

Please note that the time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.

30 08 10 06 * /home/yourname/full-backup
  • 30 – 30th Minute
  • 08 – 08 AM
  • 10 – 10th Day
  • 06 – 6th Month (June)
  • *– Every day of the week

In your case, for 2.30PM,

30 14 * * * YOURCMD
  1. 30 – 30th Minute
  2. 14 – 2PM
  3. *– Every day
  4. *– Every month
  5. *– Every day of the week

To know more about cron, visit this website.

commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated

I would mention one more thing that concerns Primefaces's p:commandButton!

When you use a p:commandButton for the action that needs to be done on the server, you can not use type="button" because that is for Push buttons which are used to execute custom javascript without causing an ajax/non-ajax request to the server.

For this purpose, you can dispense the type attribute (default value is "submit") or you can explicitly use type="submit".

Hope this will help someone!

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

I reproduced this error message in the following three cases:

  • There does not exist database user with username written in application.properties file or persistence.properties file or, as in your case, in HibernateConfig file
  • The deployed database has that user but user is identified by different password than that in one of above files
  • The database has that user and the passwords match but that user does not have all privileges needed to accomplish all database tasks that your spring-boot app does

The obvious solution is to create new database user with the same username and password as in the spring-boot app or change username and password in your spring-boot app files to match an existing database user and grant sufficient privileges to that database user. In case of MySQL database this can be done as shown below:

mysql -u root -p 
>CREATE USER 'theuser'@'localhost' IDENTIFIED BY 'thepassword';
>GRANT ALL ON *.* to theuser@localhost IDENTIFIED BY 'thepassword';
>FLUSH PRIVILEGES;

Obviously there are similar commands in Postgresql but I haven't tested if in case of Postgresql this error message can be reproduced in these three cases.

How to use a ViewBag to create a dropdownlist?

You cannot used the Helper @Html.DropdownListFor, because the first parameter was not correct, change your helper to:

@Html.DropDownList("accountid", new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))

@Html.DropDownListFor receive in the first parameters a lambda expression in all overloads and is used to create strongly typed dropdowns.

Here's the documentation

If your View it's strongly typed to some Model you may change your code using a helper to created a strongly typed dropdownlist, something like

@Html.DropDownListFor(x => x.accountId, new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))

How to add column to numpy array

The easiest solution is to use numpy.insert().

The Advantage of np.insert() over np.append is that you can insert the new columns into custom indices.

import numpy as np

X = np.arange(20).reshape(10,2)

X = np.insert(X, [0,2], np.random.rand(X.shape[0]*2).reshape(-1,2)*10, axis=1)
'''

Java NIO FileChannel versus FileOutputstream performance / usefulness

If the thing you want to compare is performance of file copying, then for the channel test you should do this instead:

final FileInputStream inputStream = new FileInputStream(src);
final FileOutputStream outputStream = new FileOutputStream(dest);
final FileChannel inChannel = inputStream.getChannel();
final FileChannel outChannel = outputStream.getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
inChannel.close();
outChannel.close();
inputStream.close();
outputStream.close();

This won't be slower than buffering yourself from one channel to the other, and will potentially be massively faster. According to the Javadocs:

Many operating systems can transfer bytes directly from the filesystem cache to the target channel without actually copying them.

gitbash command quick reference

Git command Quick Reference

git [command] -help

Git command Manual Pages

git help [command]
git [command] --help

Autocomplete

git <tab>

Cheat Sheets

How to install Guest addition in Mac OS as guest and Windows machine as host

You can use SSH and SFTP as suggested here.

  1. In the Guest OS (Mac OS X), open System Preferences > Sharing, then activate Remote Login; note the ip address specified in the Remote Login instructions, e.g. ssh [email protected]
  2. In VirtualBox, open Devices > Network > Network Settings > Advanced > Port Forwarding and specify Host IP = 127.0.0.1, Host Port 2222, Guest IP 10.0.2.15, Guest Port 22
  3. On the Host OS, run the following command sftp -P 2222 [email protected]; if you prefer a graphical interface, you can use FileZilla

Replace user and 10.0.2.15 with the appropriate values relevant to your configuration.

How to deal with SettingWithCopyWarning in Pandas

Some may want to simply suppress the warning:

class SupressSettingWithCopyWarning:
    def __enter__(self):
        pd.options.mode.chained_assignment = None

    def __exit__(self, *args):
        pd.options.mode.chained_assignment = 'warn'

with SupressSettingWithCopyWarning():
    #code that produces warning

How do I push to GitHub under a different username?

git config user.name only changes the name I commit. I still cannot push. This is how I solved it, and I think is an easy way to me.

  1. Generate a SSH key under the user name you want to push on the computer you will use https://help.github.com/articles/connecting-to-github-with-ssh/

  2. Add this key to the github user account that you want to push to https://help.github.com/articles/adding-a-new-ssh-key-to-your-github-account/

  3. Choose to Clone with SSH

You can push in as this user to that repo now.

How to let PHP to create subdomain automatically for each user?

You could [potentially] do a rewrite of the URL, but yes: you have to have control of your DNS settings so that when a user is added it gets its own subdomain.

How to find sum of multiple columns in a table in SQL Server 2005?

Try this:

select sum(num_tax_amount+num_total_amount) from table_name;

Copy entire contents of a directory to another using php

With Symfony this is very easy to accomplish:

$fileSystem = new Symfony\Component\Filesystem\Filesystem();
$fileSystem->mirror($from, $to);

See https://symfony.com/doc/current/components/filesystem.html

Cannot run Eclipse; JVM terminated. Exit code=13

I had the same issue on Ubuntu, and solved it by unpack all *.pack files in jdk directory. for example: cd /usr/java/jdk1.7.0_03/jre/lib sudo ../bin/unpack200 rt.pack rt.jar

Open a URL without using a browser from a batch file

You can use the HH command to open any website.

hh <http://url>

For example,

hh http://shuvankar.com

Though it will not open the website in the browser, but this will open the website in an HTML help window.

jquery - disable click

assuming your using click events, just unbind that one.

example

if (current = 1){ 
    $('li:eq(2)').unbind("click");
}

EDIT: Are you currently binding a click event to your list somewhere? Based on your comment above, I'm wondering if this is really what you're doing? How are you enabling the click? Is it just an anchor(<a> tag) ? A little more explicit information will help us answer your question.

UPDATE:

Did some playing around with the :eq() operator. http://jsfiddle.net/ehudokai/VRGfS/5/

As I should have expected it is a 0 based index operator. So if you want to turn of the second element in your selection, where your selection is

$("#navigation a")

you would simply add :eq(1) (the second index) and then .unbind("click") So:

if(current == 1){
    $("#navigation a:eq(1)").unbind("click");
}

Ought to do the trick.

Hope this helps!

How to print to console when using Qt

Well, after studying several examples on the Internet describing how to output messages from a GUI in Qt to stdout, I have refined a working stand-alone example on redirecting messages to a console, via qDebug() and installing qInstallMessageHandler(). The console will be showed at the same time as the GUI and can be hidden if deemed necessary. The code is easy to integrate with existing code in your project. Here is the full sample and feel free to use it in any way as you like, as long as you adhere to the License GNU GPL v2. You have to use a form of some sort and a MainWindow I think - otherwise the sample will run, but probably crash when forced to quit. Note: there is no way to quit via a close button or a menu close because I have tested those alternatives and the application will crash eventually every now and then. Without the close button the application will be stable and you can close it down from the main window. Enjoy!

#include "mainwindow.h"
#include <QApplication>

//GNU GPL V2, 2015-02-07
#include <QMessageBox>
#include <windows.h>
#define CONSOLE_COLUMNS 80
#define CONSOLE_ROWS    5000
#define YOURCONSOLETITLE "Your_Console_Title"

typedef struct{

    CONSOLE_SCREEN_BUFFER_INFOEX conScreenBuffInfoEX;

    HANDLE con_screenbuf;
    HWND hwndConsole;
    HMENU consoleMenu ;
    QString consoleTitle;

    QMessageBox mBox;
    QString localMsg;
    QString errorMessage;
    WINBOOL errorCode;

} consoleT;

static consoleT *console;

BOOL WINAPI catchCTRL( DWORD ctrlMsg ){

        if( ctrlMsg == CTRL_C_EVENT ){

            HWND hwndWin = GetConsoleWindow();
               ShowWindow(hwndWin,SW_FORCEMINIMIZE);
        }

    return TRUE;
}

void removeCloseMenu(){

    int i;

    for( i = 0; i < 10; i++){

        console->hwndConsole = FindWindowW( NULL, console->consoleTitle.toStdWString().data());

        if(console->hwndConsole != NULL)
            break;
    }

    if( !(console->errorCode = 0) && (console->hwndConsole == NULL))
            console->errorMessage += QString("\nFindWindowW error: %1 \n").arg(console->errorCode);

    if( !(console->errorCode = 0) &&  !(console->consoleMenu = GetSystemMenu( console->hwndConsole, FALSE )) )
        console->errorMessage += QString("GetSystemMenu error: %1 \n").arg(console->errorCode);

    if(!(console->errorCode = DeleteMenu( console->consoleMenu, SC_CLOSE, MF_BYCOMMAND )))
           console->errorMessage += QString("DeleteMenu error: %1 \n").arg(console->errorCode);
}

void initialiseConsole(){

    console->conScreenBuffInfoEX.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX);
    console->consoleMenu = NULL;
    console->consoleTitle = YOURCONSOLETITLE;
    console->con_screenbuf = INVALID_HANDLE_VALUE;
    console->errorCode = 0;
    console->errorMessage = "";
    console->hwndConsole = NULL;
    console->localMsg = "";

    if(!(console->errorCode = FreeConsole()))
        console->errorMessage += QString("\nFreeConsole error: %1 \n").arg(console->errorCode);

    if(!(console->errorCode = AllocConsole()))
        console->errorMessage += QString("\nAllocConsole error: %1 \n").arg(console->errorCode);

    if( (console->errorCode = -1) && (INVALID_HANDLE_VALUE ==(console->con_screenbuf = CreateConsoleScreenBuffer( GENERIC_WRITE | GENERIC_READ,0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL))))
        console->errorMessage += QString("\nCreateConsoleScreenBuffer error: %1 \n").arg(console->errorCode);

    if(!(console->errorCode = SetConsoleActiveScreenBuffer(console->con_screenbuf)))
        console->errorMessage += QString("\nSetConsoleActiveScreenBuffer error: %1 \n").arg(console->errorCode);

    if(!(console->errorCode = GetConsoleScreenBufferInfoEx(console->con_screenbuf, &console->conScreenBuffInfoEX)))
        console->errorMessage += QString("\nGetConsoleScreenBufferInfoEx error: %1 \n").arg(console->errorCode);

    console->conScreenBuffInfoEX.dwSize.X = CONSOLE_COLUMNS;
    console->conScreenBuffInfoEX.dwSize.Y = CONSOLE_ROWS;

    if(!(console->errorCode = SetConsoleScreenBufferInfoEx(console->con_screenbuf, &console->conScreenBuffInfoEX)))
       console->errorMessage += QString("\nSetConsoleScreenBufferInfoEx error: %1 \n").arg(console->errorCode);

    if(!(console->errorCode = SetConsoleTitleW(console->consoleTitle.toStdWString().data())))
        console->errorMessage += QString("SetConsoleTitle error: %1 \n").arg(console->errorCode);

    SetConsoleCtrlHandler(NULL, FALSE);
    SetConsoleCtrlHandler(catchCTRL, TRUE);

    removeCloseMenu();

    if(console->errorMessage.length() > 0){
        console->mBox.setText(console->errorMessage);
        console->mBox.show();
    }

}

void messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg){


    if((console->con_screenbuf != INVALID_HANDLE_VALUE)){

        switch (type) {

        case QtDebugMsg:
            console->localMsg = console->errorMessage + "Debug: " + msg;
            WriteConsoleW(console->con_screenbuf, console->localMsg.toStdWString().data(), console->localMsg.toStdWString().length(), NULL, NULL );
            WriteConsoleA(console->con_screenbuf, "\n--\n", 4, NULL, NULL );
            break;

        case QtWarningMsg:
            console->localMsg = console->errorMessage + "Warning: " + msg;
            WriteConsoleW(console->con_screenbuf, console->localMsg.toStdWString().data(), console->localMsg.toStdWString().length() , NULL, NULL );
            WriteConsoleA(console->con_screenbuf, "\n--\n", 4, NULL, NULL );
            break;

        case QtCriticalMsg:
            console->localMsg = console->errorMessage + "Critical: " + msg;
            WriteConsoleW(console->con_screenbuf, console->localMsg.toStdWString().data(), console->localMsg.toStdWString().length(), NULL, NULL );
            WriteConsoleA(console->con_screenbuf, "\n--\n", 4, NULL, NULL );
            break;

        case QtFatalMsg:
            console->localMsg = console->errorMessage + "Fatal: " + msg;
            WriteConsoleW(console->con_screenbuf, console->localMsg.toStdWString().data(), console->localMsg.toStdWString().length(), NULL, NULL );
            WriteConsoleA(console->con_screenbuf, "\n--\n", 4, NULL, NULL );
            abort();
        }
    }
}



int main(int argc, char *argv[])
{

    qInstallMessageHandler(messageHandler);

    QApplication a(argc, argv);

    console = new consoleT();
    initialiseConsole();

    qDebug() << "Hello World!";

    MainWindow w;
    w.show();

    return a.exec();
}

How does ApplicationContextAware work in Spring?

When spring instantiates beans, it looks for a couple of interfaces like ApplicationContextAware and InitializingBean. If they are found, the methods are invoked. E.g. (very simplified)

Class<?> beanClass = beanDefinition.getClass();
Object bean = beanClass.newInstance();
if (bean instanceof ApplicationContextAware) {
    ((ApplicationContextAware) bean).setApplicationContext(ctx);
}

Note that in newer version it may be better to use annotations, rather than implementing spring-specific interfaces. Now you can simply use:

@Inject // or @Autowired
private ApplicationContext ctx;

Merging dataframes on index with pandas

You can do this with merge:

df_merged = df1.merge(df2, how='outer', left_index=True, right_index=True)

The keyword argument how='outer' keeps all indices from both frames, filling in missing indices with NaN. The left_index and right_index keyword arguments have the merge be done on the indices. If you get all NaN in a column after doing a merge, another troubleshooting step is to verify that your indices have the same dtypes.

The merge code above produces the following output for me:

                V1    V2
A 2012-01-01  12.0  15.0
  2012-02-01  14.0   NaN
  2012-03-01   NaN  21.0
B 2012-01-01  15.0  24.0
  2012-02-01   8.0   9.0
C 2012-01-01  17.0   NaN
  2012-02-01   9.0   NaN
D 2012-01-01   NaN   7.0
  2012-02-01   NaN  16.0

How do I put a border around an Android textview?

I found a better way to put a border around a TextView.

Use a nine-patch image for the background. It's pretty simple, the SDK comes with a tool to make the 9-patch image, and it involves absolutely no coding.

The link is http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch.

How do I use FileSystemObject in VBA?

After adding the reference, I had to use

Dim fso As New Scripting.FileSystemObject

Multiple Order By with LINQ

You can use the ThenBy and ThenByDescending extension methods:

foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)

How to Code Double Quotes via HTML Codes

There really aren't any differences.

&quot; is processed as &#34; which is the decimal equivalent of &x22; which is the ISO 8859-1 equivalent of ".

The only reason you may be against using &quot; is because it was mistakenly omitted from the HTML 3.2 specification.

Otherwise it all boils down to personal preference.

Twitter API returns error 215, Bad Authentication Data

A very concise code without any other php file include of oauth etc. Please note to obtain following keys you need to sign up with https://dev.twitter.com and create application.

<?php
$token = 'YOUR_TOKEN';
$token_secret = 'YOUR_TOKEN_SECRET';
$consumer_key = 'CONSUMER_KEY';
$consumer_secret = 'CONSUMER_SECRET';

$host = 'api.twitter.com';
$method = 'GET';
$path = '/1.1/statuses/user_timeline.json'; // api call path

$query = array( // query parameters
    'screen_name' => 'twitterapi',
    'count' => '5'
);

$oauth = array(
    'oauth_consumer_key' => $consumer_key,
    'oauth_token' => $token,
    'oauth_nonce' => (string)mt_rand(), // a stronger nonce is recommended
    'oauth_timestamp' => time(),
    'oauth_signature_method' => 'HMAC-SHA1',
    'oauth_version' => '1.0'
);

$oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
$query = array_map("rawurlencode", $query);

$arr = array_merge($oauth, $query); // combine the values THEN sort

asort($arr); // secondary sort (value)
ksort($arr); // primary sort (key)

// http_build_query automatically encodes, but our parameters
// are already encoded, and must be by this point, so we undo
// the encoding step
$querystring = urldecode(http_build_query($arr, '', '&'));

$url = "https://$host$path";

// mash everything together for the text to hash
$base_string = $method."&".rawurlencode($url)."&".rawurlencode($querystring);

// same with the key
$key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret);

// generate the hash
$signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));

// this time we're using a normal GET query, and we're only encoding the query params
// (without the oauth params)
$url .= "?".http_build_query($query);
$url=str_replace("&amp;","&",$url); //Patch by @Frewuill

$oauth['oauth_signature'] = $signature; // don't want to abandon all that work!
ksort($oauth); // probably not necessary, but twitter's demo does it

// also not necessary, but twitter's demo does this too
function add_quotes($str) { return '"'.$str.'"'; }
$oauth = array_map("add_quotes", $oauth);

// this is the full value of the Authorization line
$auth = "OAuth " . urldecode(http_build_query($oauth, '', ', '));

// if you're doing post, you need to skip the GET building above
// and instead supply query parameters to CURLOPT_POSTFIELDS
$options = array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
                  //CURLOPT_POSTFIELDS => $postfields,
                  CURLOPT_HEADER => false,
                  CURLOPT_URL => $url,
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_SSL_VERIFYPEER => false);

// do our business
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);

$twitter_data = json_decode($json);


foreach ($twitter_data as &$value) {
   $tweetout .= preg_replace("/(http:\/\/|(www\.))(([^\s<]{4,68})[^\s<]*)/", '<a href="http://$2$3" target="_blank">$1$2$4</a>', $value->text);
   $tweetout = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>", $tweetout);
   $tweetout = preg_replace("/#(\w+)/", "<a href=\"http://search.twitter.com/search?q=\\1\" target=\"_blank\">#\\1</a>", $tweetout);
}

echo $tweetout;

?>

Regards

How to SUM parts of a column which have same text value in different column in the same row

A PivotTable might suit, though I am not quite certain of the layout of your data:

SO19669814 example

The bold numbers (one of each pair of duplicates) need not be shown as the field does not have to be subtotalled eg:

SO19669814 second example

C++ auto keyword. Why is it magic?

The auto keyword is an important and frequently used keyword for C ++.When initializing a variable, auto keyword is used for type inference(also called type deduction).

There are 3 different rules regarding the auto keyword.

First Rule

auto x = expr; ----> No pointer or reference, only variable name. In this case, const and reference are ignored.

int  y = 10;
int& r = y;
auto x = r; // The type of variable x is int. (Reference Ignored)

const int y = 10;
auto x = y; // The type of variable x is int. (Const Ignored)

int y = 10;
const int& r = y;
auto x = r; // The type of variable x is int. (Both const and reference Ignored)

const int a[10] = {};
auto x = a; //  x is const int *. (Array to pointer conversion)

Note : When the name defined by auto is given a value with the name of a function,
       the type inference will be done as a function pointer.

Second Rule

auto& y = expr; or auto* y = expr; ----> Reference or pointer after auto keyword.

Warning : const is not ignored in this rule !!! .

int y = 10;
auto& x = y; // The type of variable x is int&.

Warning : In this rule, array to pointer conversion (array decay) does not occur !!!.

auto& x = "hello"; // The type of variable x is  const char [6].

static int x = 10;
auto y = x; // The variable y is not static.Because the static keyword is not a type. specifier 
            // The type of variable x is int.

Third Rule

auto&& z = expr; ----> This is not a Rvalue reference.

Warning : If the type inference is in question and the && token is used, the names introduced like this are called "Forwarding Reference" (also called Universal Reference).

auto&& r1 = x; // The type of variable r1 is int&.Because x is Lvalue expression. 

auto&& r2 = x+y; // The type of variable r2 is int&&.Because x+y is PRvalue expression. 

How can I get the IP address from NIC in Python?

This will gather all IPs on the host and filter out loopback/link-local and IPv6. This can also be edited to allow for IPv6 only, or both IPv4 and IPv6, as well as allowing loopback/link-local in IP list.

from socket import getaddrinfo, gethostname
import ipaddress

def get_ip(ip_addr_proto="ipv4", ignore_local_ips=True):
    # By default, this method only returns non-local IPv4 Addresses
    # To return IPv6 only, call get_ip('ipv6')
    # To return both IPv4 and IPv6, call get_ip('both')
    # To return local IPs, call get_ip(None, False)
    # Can combime options like so get_ip('both', False)

    af_inet = 2
    if ip_addr_proto == "ipv6":
        af_inet = 30
    elif ip_addr_proto == "both":
        af_inet = 0

    system_ip_list = getaddrinfo(gethostname(), None, af_inet, 1, 0)
    ip_list = []

    for ip in system_ip_list:
        ip = ip[4][0]

        try:
            ipaddress.ip_address(str(ip))
            ip_address_valid = True
        except ValueError:
            ip_address_valid = False
        else:
            if ipaddress.ip_address(ip).is_loopback and ignore_local_ips or ipaddress.ip_address(ip).is_link_local and ignore_local_ips:
                pass
            elif ip_address_valid:
                ip_list.append(ip)

    return ip_list

print(f"Your IP Address is: {get_ip()}")

Returns Your IP Address is: ['192.168.1.118']

If I run get_ip('both', False), it returns

Your IP Address is: ['::1', 'fe80::1', '127.0.0.1', '192.168.1.118', 'fe80::cb9:d2dd:a505:423a']

Properties order in Margin

Just because @MartinCapodici 's comment is awesome I write here as an answer to give visibility.

All clockwise:

  • WPF start West (left->top->right->bottom)
  • Netscape (ie CSS) start North (top->right->bottom->left)

What is the best algorithm for overriding GetHashCode?

Here is my simplistic approach. I am using the classic builder pattern for this. It is typesafe (no boxing/unboxing) and also compatbile with .NET 2.0 (no extension methods etc.).

It is used like this:

public override int GetHashCode()
{
    HashBuilder b = new HashBuilder();
    b.AddItems(this.member1, this.member2, this.member3);
    return b.Result;
} 

And here is the acutal builder class:

internal class HashBuilder
{
    private const int Prime1 = 17;
    private const int Prime2 = 23;
    private int result = Prime1;

    public HashBuilder()
    {
    }

    public HashBuilder(int startHash)
    {
        this.result = startHash;
    }

    public int Result
    {
        get
        {
            return this.result;
        }
    }

    public void AddItem<T>(T item)
    {
        unchecked
        {
            this.result = this.result * Prime2 + item.GetHashCode();
        }
    }

    public void AddItems<T1, T2>(T1 item1, T2 item2)
    {
        this.AddItem(item1);
        this.AddItem(item2);
    }

    public void AddItems<T1, T2, T3>(T1 item1, T2 item2, T3 item3)
    {
        this.AddItem(item1);
        this.AddItem(item2);
        this.AddItem(item3);
    }

    public void AddItems<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, 
        T4 item4)
    {
        this.AddItem(item1);
        this.AddItem(item2);
        this.AddItem(item3);
        this.AddItem(item4);
    }

    public void AddItems<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, 
        T4 item4, T5 item5)
    {
        this.AddItem(item1);
        this.AddItem(item2);
        this.AddItem(item3);
        this.AddItem(item4);
        this.AddItem(item5);
    }        

    public void AddItems<T>(params T[] items)
    {
        foreach (T item in items)
        {
            this.AddItem(item);
        }
    }
}

Does adding a duplicate value to a HashSet/HashMap replace the previous value

You need to check put method in Hash map first as HashSet is backed up by HashMap

  1. When you add duplicate value say a String "One" into HashSet,
  2. An entry ("one", PRESENT) will get inserted into Hashmap(for all the values added into set, the value will be "PRESENT" which if of type Object)
  3. Hashmap adds the entry into Map and returns the value, which is in this case "PRESENT" or null if Entry is not there.
  4. Hashset's add method then returns true if the returned value from Hashmap equals null otherwise false which means an entry already exists...

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

A date-time object is not a String

The java.sql.Timestamp class has no format. Its toString method generates a String with a format.

Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.

java.time

First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.

Instant instant = mySqlDate.toInstant() ;

Lose the fraction of a second you don't want.

instant = instant.truncatedTo( ChronoUnit.Seconds );

Assign the time zone to adjust from UTC used by Instant.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );

Generate a String close to your desired output. Replace its T in the middle with a SPACE.

DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

Culprit is preflight request using OPTIONS method

For HTTP request methods that can cause side-effects on user data (in particular, for HTTP methods other than GET, or for POST usage with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method.

Web specification refer to: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

I resolved the problem by adding following lines in Nginx conf.

    location / {
               if ($request_method = OPTIONS ) {
                   add_header Access-Control-Allow-Origin  "*";
                   add_header Access-Control-Allow-Methods "POST, GET, PUT, UPDATE, DELETE, OPTIONS";
                   add_header Access-Control-Allow-Headers "Authorization";
                   add_header Access-Control-Allow-Credentials  "true";
                   add_header Content-Length 0;
                   add_header Content-Type text/plain;
                   return 200;
               }
    location ~ ^/(xxxx)$ {
                if ($request_method = OPTIONS) {
                    rewrite ^(.*)$ / last;
                }
    }

Is there a way to use PhantomJS in Python?

In case you are using Buildout, you can easily automate the installation processes that Pykler describes using the gp.recipe.node recipe.

[nodejs]
recipe = gp.recipe.node
version = 0.10.32
npms = phantomjs
scripts = phantomjs

That part installs node.js as binary (at least on my system) and then uses npm to install PhantomJS. Finally it creates an entry point bin/phantomjs, which you can call the PhantomJS webdriver with. (To install Selenium, you need to specify it in your egg requirements or in the Buildout configuration.)

driver = webdriver.PhantomJS('bin/phantomjs')

Change header text of columns in a GridView

You can do it with gridview's datarow bound event. try the following sample of code:

protected void grv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Text = "TiTle";
}
}

For more details about the row databound event study Thsi....

How do you access the matched groups in a JavaScript regular expression?

Your code works for me (FF3 on Mac) even if I agree with PhiLo that the regex should probably be:

/\bformat_(.*?)\b/

(But, of course, I'm not sure because I don't know the context of the regex.)

C fopen vs open

open() is a low-level os call. fdopen() converts an os-level file descriptor to the higher-level FILE-abstraction of the C language. fopen() calls open() in the background and gives you a FILE-pointer directly.

There are several advantages to using FILE-objects rather raw file descriptors, which includes greater ease of usage but also other technical advantages such as built-in buffering. Especially the buffering generally results in a sizeable performance advantage.

How to acces external json file objects in vue.js app

If your file looks like this:

[
    {
        "firstname": "toto",
        "lastname": "titi"
    },
    {
        "firstname": "toto2",
        "lastname": "titi2"
    },
]

You can do:

import json from './json/data.json';
// ....
json.forEach(x => { console.log(x.firstname, x.lastname); });

How can I remove the string "\n" from within a Ruby string?

When you want to remove a string, rather than replace it you can use String#delete (or its mutator equivalent String#delete!), e.g.:

x = "foo\nfoo"
x.delete!("\n")

x now equals "foofoo"

In this specific case String#delete is more readable than gsub since you are not actually replacing the string with anything.

How to add bootstrap to an angular-cli project

Since this became so confusing and the answers here are totally mixed I will just suggest going with the official ui-team for BS4 repo (yes there are so many of those repos for NG-Bootstrap.

Just follow the instructions here https://github.com/ng-bootstrap/ng-bootstrap to get BS4.

Quoting from the lib:

This library is being built from scratch by the ui-bootstrap team. We are using TypeScript and targeting the Bootstrap 4 CSS framework.

As with Bootstrap 4, this library is a work in progress. Please check out our list of issues to see all the things we are implementing. Feel free to make comments there.

Just copy pasting what is there for the sake of it:

npm install --save @ng-bootstrap/ng-bootstrap

Once installed you need to import our main module:

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

The only remaining part is to list the imported module in your application module. The exact method will be slightly different for the root (top-level) module for which you should end up with the code similar to (notice NgbModule.forRoot()):

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  declarations: [AppComponent, ...],
  imports: [NgbModule.forRoot(), ...],  
  bootstrap: [AppComponent]
})
export class AppModule {
}

Other modules in your application can simply import NgbModule:

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  declarations: [OtherComponent, ...],
  imports: [NgbModule, ...], 
})
export class OtherModule {
}

This seems to be the most consistent behavior by far

SyntaxError: Unexpected token function - Async Await Nodejs

include and specify the node engine version to the latest, say at this time I did add version 8.

{
  "name": "functions",
  "dependencies": {
    "firebase-admin": "~7.3.0",
    "firebase-functions": "^2.2.1",
  },
  "engines": {
    "node": "8"
  },
  "private": true
}

in the following file

package.json

How do I get the name of the current executable in C#?

System.AppDomain.CurrentDomain.FriendlyName

How to replace four spaces with a tab in Sublime Text 2?

Select all, then:

Windows / Linux:

Ctrl+Shift+p

then type "indent"


Mac:

Shift+Command+p

then type "indent"

Height equal to dynamic width (CSS fluid layout)

Using jQuery you can achieve this by doing

var cw = $('.child').width();
$('.child').css({'height':cw+'px'});

Check working example at http://jsfiddle.net/n6DAu/1/

Regular Expression: Allow letters, numbers, and spaces (with at least one letter or number)

You can use a lookaround:

^(?=.*[A-Za-z0-9])[A-Za-z0-9 _]*$

It will check ahead that the string has a letter or number, if it does it will check that the rest of the chars meet your requirements. This can probably be improved upon, but it seems to work with my tests.

UPDATE:

Adding modifications suggested by Chris Lutz:

^(?=.*[^\W_])[\w ]*$/

How to select a radio button by default?

XHTML solution:

<input type="radio" name="imgsel" value="" checked="checked" />

Please note, that the actual value of checked attribute does not actually matter; it's just a convention to assign "checked". Most importantly, strings like "true" or "false" don't have any special meaning.

If you don't aim for XHTML conformance, you can simplify the code to:

<input type="radio" name="imgsel" value="" checked>

Maximum call stack size exceeded error

in my case I m getting this error on ajax call and the data I tried to pass that variable haven't defined, that is showing me this error but not describing that variable not defined. I added defined that variable n got value.

PHP split alternative?

I want to clear here that preg_split(); is far away from it but explode(); can be used in similar way as split();

following is the comparison between split(); and explode(); usage

How was split() used

<?php

$date = "04/30/1973";
list($month, $day, $year) = split('[/.-]', $date);
echo $month; // foo
echo $day; // *
echo $year;

?>

URL: http://php.net/manual/en/function.split.php

How explode() can be used

<?php

$data = "04/30/1973";
list($month, $day, $year) = explode("/", $data);
echo $month; // foo
echo $day; // *
echo $year;

?>

URL: http://php.net/manual/en/function.explode.php

Here is how we can use it :)

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

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

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

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

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

Important(!) if you choose regex:

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

Random row selection in Pandas dataframe

Below line will randomly select n number of rows out of the total existing row numbers from the dataframe df without replacement.

df=df.take(np.random.permutation(len(df))[:n])

Excel cell value as string won't store as string

Use Range("A1").Text instead of .Value

post comment edit:
Why?
Because the .Text property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92 then <- Text will return exactly what it in the cell including any formatting.
The .Value and .Value2 properties return what's stored in the cell under the hood excluding formatting. Specially .Value2 for date types, it will return the decimal representation.

If you want to dig deeper into the meaning and performance, I just found this article which seems like a good guide

another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
Dont Format column A, Format B as TEXT, C as Date, D as Percentage
now,
paste this code in a module

Sub main()

    Dim ws As Worksheet, i&, j&
    Set ws = Sheets(1)
    For i = 3 To 7
        For j = 1 To 4
            Debug.Print _
                    "row " & i & vbTab & vbTab & _
                    Cells(i, j).Text & vbTab & _
                    Cells(i, j).Value & vbTab & _
                    Cells(i, j).Value2
        Next j
    Next i
End Sub

and Analyse the output! Its really easy and there isn't much more i can do to help :)

            .TEXT              .VALUE             .VALUE2
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 4       1                 1                   1
row 4       1                 1                   1
row 4       01/01/1900        31/12/1899          1
row 4       1.00%             0.01                0.01
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 6       63                63                  63
row 6       =7*9              =7*9                =7*9
row 6       03/03/1900        03/03/1900          63
row 6       6300.00%          63                  63
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013        29/05/2013          29/05/2013
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013%       29/05/2013%         29/05/2013%

What does `void 0` mean?

void 0 returns undefined and can not be overwritten while undefined can be overwritten.

var undefined = "HAHA";

Is it possible to insert HTML content in XML document?

so long as your html content doesn't need to contain a CDATA element, you can contain the HTML in a CDATA element, otherwise you'll have to escape the XML entities.

<element><![CDATA[<p>your html here</p>]]></element>

VS

<element>&lt;p&gt;your html here&lt;/p&gt;</element>

Code coverage with Mocha

You need an additional library for code coverage, and you are going to be blown away by how powerful and easy istanbul is. Try the following, after you get your mocha tests to pass:

npm install nyc

Now, simply place the command nyc in front of your existing test command, for example:

{
  "scripts": {
    "test": "nyc mocha"
  }
}

How to use tick / checkmark symbol (?) instead of bullets in unordered list?

You can use a pseudo-element to insert that character before each list item:

_x000D_
_x000D_
ul {_x000D_
  list-style: none;_x000D_
}_x000D_
_x000D_
ul li:before {_x000D_
  content: '?';_x000D_
}
_x000D_
<ul>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Ruby max integer

FIXNUM_MAX = (2**(0.size * 8 -2) -1)
FIXNUM_MIN = -(2**(0.size * 8 -2))

Convert Pandas Series to DateTime in a DataFrame

Some handy script:

hour = df['assess_time'].dt.hour.values[0]

java.net.ConnectException: failed to connect to /192.168.253.3 (port 2468): connect failed: ECONNREFUSED (Connection refused)

Why this might have happened:

  1. The server couldn't send a response: Ensure that the backend is working properly at IP and port mentioned.
  2. SSL connections are being blocked: Fix this by importing SSL certificates

Less likely:

  1. Cookies not being sent
  2. Request timeout: Change request timeout

python re.split() to split by spaces, commas, and periods, but not in cases like 1,000 or 1.50

So you want to split on spaces, and on commas and periods that aren't surrounded by numbers. This should work:

r" |(?<![0-9])[.,](?![0-9])"

List file using ls command in Linux with full path

Print the full path (also called resolved path) with:

realpath README.md

In interactive mode you can use shell expansion to list all files in the directory with their full paths:

realpath *

If you're programming a bash script, I guess you'll have a variable for the individual file names.

Thanks to VIPIN KUMAR for pointing to the related readlink command.

What is difference between arm64 and armhf?

armhf stands for "arm hard float", and is the name given to a debian port for arm processors (armv7+) that have hardware floating point support.

On the beaglebone black, for example:

:~$ dpkg --print-architecture
armhf

Although other commands (such as uname -a or arch) will just show armv7l

:~$ cat /proc/cpuinfo 
processor       : 0
model name      : ARMv7 Processor rev 2 (v7l)
BogoMIPS        : 995.32
Features        : half thumb fastmult vfp edsp thumbee neon vfpv3 tls
...

The vfpv3 listed under Features is what refers to the floating point support.

Incidentally, armhf, if your processor supports it, basically supersedes Raspbian, which if I understand correctly was mainly a rebuild of armhf with work arounds to deal with the lack of floating point support on the original raspberry pi's. Nowdays, of course, there's a whole ecosystem build up around Raspbian, so they're probably not going to abandon it. However, this is partly why the beaglebone runs straight debian, and that's ok even if you're used to Raspbian, unless you want some of the special included non-free software such as Mathematica.

How to set ChartJS Y axis title?

For me it works like this:

    options : {
      scales: {
        yAxes: [{
          scaleLabel: {
            display: true,
            labelString: 'probability'
          }
        }]
      }
    }

How to use DISTINCT and ORDER BY in same SELECT statement?

Distinct will sort records in ascending order. If you want to sort in desc order use:

SELECT DISTINCT Category
FROM MonitoringJob
ORDER BY Category DESC

If you want to sort records based on CreationDate field then this field must be in the select statement:

SELECT DISTINCT Category, creationDate
FROM MonitoringJob
ORDER BY CreationDate DESC

Tkinter: "Python may not be configured for Tk"

To anyone using Windows and Windows Subsystem for Linux, make sure that when you run the python command from the command line, it's not accidentally running the python installation from WSL! This gave me quite a headache just now. A quick check you can do for this is just
which <python command you're using>
If that prints something like /usr/bin/python2 even though you're in powershell, that's probably what's going on.

how to get docker-compose to use the latest image from repository

Since 2020-05-07, the docker-compose spec also defines the "pull_policy" property for a service:

version: '3.7'

services:
  my-service:
    image: someimage/somewhere
    pull_policy: always

The docker-compose spec says:

pull_policy defines the decisions Compose implementations will make when it starts to pull images.

Possible values are (tl;dr, check spec for more details):

  • always: always pull
  • never: don't pull (breaks if the image can not be found)
  • missing: pulls if the image is not cached
  • build: always build or rebuild

MD5 hashing in Android

If using Apache Commons Codec is an option, then this would be a shorter implementation:

String md5Hex = new String(Hex.encodeHex(DigestUtils.md5(data)));

Or SHA:

String shaHex= new String(Hex.encodeHex(DigestUtils.sha("textToHash")));

Source for above.

Please follow the link and upvote his solution to award the correct person.


Maven repo link: https://mvnrepository.com/artifact/commons-codec/commons-codec

Current Maven dependency (as of 6 July 2016):

<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.10</version>
</dependency>

Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'

I am using python 3 in windows. I also faced this issue. I just uninstalled 'mysqlclient' and then installed it again. It worked somehow

How to run html file on localhost?

On macOS:

Open Terminal (or iTerm) install Homebrew then run brew install live-server and run live-server.

You also can install Python 3 and run python3 -m http.server PORT.

On Windows:

If you have VS Code installed open it and install extension liveserver, then click Go Live in the bottom right corner.

Alternatively you can install WSL2 and follow the macOS steps via apt (sudo apt-get).

On Linux:

Open your favorite terminal emulator and follow the macOS steps via apt (sudo apt-get).

Capture characters from standard input without waiting for enter to be pressed

The closest thing to portable is to use the ncurses library to put the terminal into "cbreak mode". The API is gigantic; the routines you'll want most are

  • initscr and endwin
  • cbreak and nocbreak
  • getch

Good luck!

What are the differences between B trees and B+ trees?

A B+tree is a balanced tree in which every path from the root of the tree to a leaf is of the same length, and each nonleaf node of the tree has between [n/2] and [n] children, where n is fixed for a particular tree. It contains index pages and data pages. Binary trees only have two children per parent node, B+ trees can have a variable number of children for each parent node

SQL Server principal "dbo" does not exist,

As the message said, you should set permission as owner to your user. So you can use following:

ALTER AUTHORIZATION 
ON DATABASE::[YourDBName]
TO [UserLogin];

Hope helpful! Leave comment if it's ok for you.

Creating a Plot Window of a Particular Size

A convenient function for saving plots is ggsave(), which can automatically guess the device type based on the file extension, and smooths over differences between devices. You save with a certain size and units like this:

ggsave("mtcars.png", width = 20, height = 20, units = "cm")

In R markdown, figure size can be specified by chunk:

```{r, fig.width=6, fig.height=4}  
plot(1:5)
```

How to find out the MySQL root password

In your "hostname".err file inside the data folder MySQL works on, try to look for a string that starts with:

"A temporary password is generated for roor@localhost "

you can use

less /mysql/data/dir/hostname.err 

then slash command followed by the string you wish to look for

/"A temporary password"

Then press n, to go to the Next result.

How can I uninstall npm modules in Node.js?

In case you are on Windows, run CMD as administrator and type:

npm -g uninstall <package name>

Java, Check if integer is multiple of a number

Use modulo

whenever a number x is a multiple of some number y, then always x % y equal to 0, which can be used as a check. So use

if (j % 4 == 0) 

Angular ng-repeat Error "Duplicates in a repeater are not allowed."

My JSON response was like this:

{"items": 
  &nbsp;[
    &nbsp;&nbsp;{
      "index": 1,
      "name": "Samantha",
      "rarity": "Scarborough",
      "email": "[email protected]"
    },
    &nbsp;&nbsp;{
      "index": 2,
      "name": "Amanda",
      "rarity": "Vick",
      "email": "[email protected]"
    }]
}

So, I used ng-repeat = "item in variables.items" to display it.

Possible to restore a backup of SQL Server 2014 on SQL Server 2012?

Sure it's possible... use Export Wizard in source option use SQL SERVER NATIVE CLIENT 11, later your source server ex.192.168.100.65\SQLEXPRESS next step select your new destination server ex.192.168.100.65\SQL2014

Just be sure to be using correct instance and connect each other

Just pay attention in Stored procs must be recompiled

How do I manage conflicts with git submodules?

First, find the hash you want to your submodule to reference. then run

~/supery/subby $ git co hashpointerhere
~/supery/subby $ cd ../
~/supery $ git add subby
~/supery $ git commit -m 'updated subby reference'

that has worked for me to get my submodule to the correct hash reference and continue on with my work without getting any further conflicts.

UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples

the same problem also happened to me when i training my classification model. the reason caused this problem is as what the warning message said "in labels with no predicated samples", it will caused the zero-division when compute f1-score. I found another solution when i read sklearn.metrics.f1_score doc, there is a note as follows:

When true positive + false positive == 0, precision is undefined; When true positive + false negative == 0, recall is undefined. In such cases, by default the metric will be set to 0, as will f-score, and UndefinedMetricWarning will be raised. This behavior can be modified with zero_division

the zero_division default value is "warn", you could set it to 0 or 1 to avoid UndefinedMetricWarning. it works for me ;) oh wait, there is another problem when i using zero_division, my sklearn report that no such keyword argument by using scikit-learn 0.21.3. Just update your sklearn to the latest version by running pip install scikit-learn -U

ctypes - Beginner

Here's a quick and dirty ctypes tutorial.

First, write your C library. Here's a simple Hello world example:

testlib.c

#include <stdio.h>

void myprint(void);

void myprint()
{
    printf("hello world\n");
}

Now compile it as a shared library (mac fix found here):

$ gcc -shared -Wl,-soname,testlib -o testlib.so -fPIC testlib.c

# or... for Mac OS X 
$ gcc -shared -Wl,-install_name,testlib.so -o testlib.so -fPIC testlib.c

Then, write a wrapper using ctypes:

testlibwrapper.py

import ctypes

testlib = ctypes.CDLL('/full/path/to/testlib.so')
testlib.myprint()

Now execute it:

$ python testlibwrapper.py

And you should see the output

Hello world
$

If you already have a library in mind, you can skip the non-python part of the tutorial. Make sure ctypes can find the library by putting it in /usr/lib or another standard directory. If you do this, you don't need to specify the full path when writing the wrapper. If you choose not to do this, you must provide the full path of the library when calling ctypes.CDLL().

This isn't the place for a more comprehensive tutorial, but if you ask for help with specific problems on this site, I'm sure the community would help you out.

PS: I'm assuming you're on Linux because you've used ctypes.CDLL('libc.so.6'). If you're on another OS, things might change a little bit (or quite a lot).

Can I apply multiple background colors with CSS3?

In this LIVE DEMO i've achieved this by using the :before css selector which seems to work quite nicely.

_x000D_
_x000D_
.myDiv  {_x000D_
position: relative; /*Parent MUST be relative*/_x000D_
z-index: 9;_x000D_
background: green;_x000D_
    _x000D_
/*Set width/height of the div in 'parent'*/    _x000D_
width:100px;_x000D_
height:100px;_x000D_
}_x000D_
_x000D_
_x000D_
.myDiv:before {_x000D_
content: "";_x000D_
position: absolute;/*set 'child' to be absolute*/_x000D_
z-index: -1; /*Make this lower so text appears in front*/_x000D_
   _x000D_
    _x000D_
/*You can choose to align it left, right, top or bottom here*/_x000D_
top: 0; _x000D_
right:0;_x000D_
bottom: 60%;_x000D_
left: 0;_x000D_
    _x000D_
    _x000D_
background: red;_x000D_
}
_x000D_
<div class="myDiv">this is my div with multiple colours. It work's with text too!</div>
_x000D_
_x000D_
_x000D_

I thought i would add this as I feel it could work quite well for a percentage bar/visual level of something.

It also means you're not creating multiple divs if you don't have to, and keeps this page up-to-date

How to force a script reload and re-execute?

Here's a method which is similar to Kelly's but will remove any pre-existing script with the same source, and uses jQuery.

<script>
    function reload_js(src) {
        $('script[src="' + src + '"]').remove();
        $('<script>').attr('src', src).appendTo('head');
    }
    reload_js('source_file.js');
</script>

Note that the 'type' attribute is no longer needed for scripts as of HTML5. (http://www.w3.org/html/wg/drafts/html/master/scripting-1.html#the-script-element)

How to change the current URL in javascript?

This is more robust:

mi = location.href.split(/(\d+)/);
no = mi.length - 2;
os = mi[no];
mi[no]++;
if ((mi[no] + '').length < os.length) mi[no] = os.match(/0+/) + mi[no];
location.href = mi.join('');

When the URL has multiple numbers, it will change the last one:

http://mywebsite.com/8815/1.html

It supports numbers with leading zeros:

http://mywebsite.com/0001.html

Example

Cannot uninstall angular-cli

Step 1:

npm uninstall -g angular-cli

Step 2:

npm cache clean

Step 3:

npm cache verify

Step 4:

npm cache verify --force

Note: You can also delete by the following the paths

C:\Users"System_name"\AppData\Roaming\npm and

C:\Users"System_name"\AppData\Roaming\npm-cache

Then

Step 5:

npm install -g @angular/cli@latest

Loop until a specific user input

As an alternative to @Mark Byers' approach, you can use while True:

guess = 50     # this should be outside the loop, I think
while True:    # infinite loop
    n = raw_input("\n\nTrue, False or Correct?: ")
    if n == "Correct":
        break  # stops the loop
    elif n == "True":
        # etc.

Errno 13 Permission denied Python

If nothing worked for you, make sure the file is not open in another program. I was trying to import an xlsx file and Excel was blocking me from doing so.

Does Notepad++ show all hidden characters?

For non-printing characters, you can do the following:

  • if you could identify the character, where cursor takes 2 arrow keys to move, just select that character.
  • do Ctrl-F
  • now you can count or replace or even mark all such characters

How to split a data frame?

Splitting the data frame seems counter-productive. Instead, use the split-apply-combine paradigm, e.g., generate some data

df = data.frame(grp=sample(letters, 100, TRUE), x=rnorm(100))

then split only the relevant columns and apply the scale() function to x in each group, and combine the results (using split<- or ave)

df$z = 0
split(df$z, df$grp) = lapply(split(df$x, df$grp), scale)
## alternative: df$z = ave(df$x, df$grp, FUN=scale)

This will be very fast compared to splitting data.frames, and the result remains usable in downstream analysis without iteration. I think the dplyr syntax is

library(dplyr)
df %>% group_by(grp) %>% mutate(z=scale(x))

In general this dplyr solution is faster than splitting data frames but not as fast as split-apply-combine.

Get the Selected value from the Drop down box in PHP

Posting it from my project.

<select name="parent" id="parent"><option value="0">None</option>
<?php
 $select="select=selected";
 $allparent=mysql_query("select * from tbl_page_content where parent='0'");
 while($parent=mysql_fetch_array($allparent))
   {?>
   <option value="<?= $parent['id']; ?>" <?php if( $pageDetail['parent']==$parent['id'] ) { echo($select); }?>><?= $parent['name']; ?></option>
  <?php 
   }
  ?></select>

Calculate a MD5 hash from a string

You can use Convert.ToBase64String to convert 16 byte output of MD5 to a ~24 char string. A little bit better without reducing security. (j9JIbSY8HuT89/pwdC8jlw== for your example)

Force LF eol in git repo and working copy

Without a bit of information about what files are in your repository (pure source code, images, executables, ...), it's a bit hard to answer the question :)

Beside this, I'll consider that you're willing to default to LF as line endings in your working directory because you're willing to make sure that text files have LF line endings in your .git repository wether you work on Windows or Linux. Indeed better safe than sorry....

However, there's a better alternative: Benefit from LF line endings in your Linux workdir, CRLF line endings in your Windows workdir AND LF line endings in your repository.

As you're partially working on Linux and Windows, make sure core.eol is set to native and core.autocrlf is set to true.

Then, replace the content of your .gitattributes file with the following

* text=auto

This will let Git handle the automagic line endings conversion for you, on commits and checkouts. Binary files won't be altered, files detected as being text files will see the line endings converted on the fly.

However, as you know the content of your repository, you may give Git a hand and help him detect text files from binary files.

Provided you work on a C based image processing project, replace the content of your .gitattributes file with the following

* text=auto
*.txt text
*.c text
*.h text
*.jpg binary

This will make sure files which extension is c, h, or txt will be stored with LF line endings in your repo and will have native line endings in the working directory. Jpeg files won't be touched. All of the others will be benefit from the same automagic filtering as seen above.

In order to get a get a deeper understanding of the inner details of all this, I'd suggest you to dive into this very good post "Mind the end of your line" from Tim Clem, a Githubber.

As a real world example, you can also peek at this commit where those changes to a .gitattributes file are demonstrated.

UPDATE to the answer considering the following comment

I actually don't want CRLF in my Windows directories, because my Linux environment is actually a VirtualBox sharing the Windows directory

Makes sense. Thanks for the clarification. In this specific context, the .gitattributes file by itself won't be enough.

Run the following commands against your repository

$ git config core.eol lf
$ git config core.autocrlf input

As your repository is shared between your Linux and Windows environment, this will update the local config file for both environment. core.eol will make sure text files bear LF line endings on checkouts. core.autocrlf will ensure potential CRLF in text files (resulting from a copy/paste operation for instance) will be converted to LF in your repository.

Optionally, you can help Git distinguish what is a text file by creating a .gitattributes file containing something similar to the following:

# Autodetect text files
* text=auto

# ...Unless the name matches the following
# overriding patterns

# Definitively text files 
*.txt text
*.c text
*.h text

# Ensure those won't be messed up with
*.jpg binary
*.data binary

If you decided to create a .gitattributes file, commit it.

Lastly, ensure git status mentions "nothing to commit (working directory clean)", then perform the following operation

$ git checkout-index --force --all

This will recreate your files in your working directory, taking into account your config changes and the .gitattributes file and replacing any potential overlooked CRLF in your text files.

Once this is done, every text file in your working directory WILL bear LF line endings and git status should still consider the workdir as clean.

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

I don't think this is your problem, but it still looks pretty bad to me. You have a duplicate layer of com.examples.quote in your project. Your Activity section in your AndroidManifest.xml should look more like this:

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

You may even have your classes under src/com.example.quotes/com.example.quotes instead of just in com.example.quotes.

I'm not sure if this is causing your problem. But it looks a bit messed up. All your other stuff looks pretty standard to me.

React Native android build failed. SDK location not found

  • Go to the android/ directory of your react-native project
  • Create a file called local.properties with this line:
sdk.dir = /Users/USERNAME/Library/Android/sdk

Where USERNAME is your macOS username

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

In my case:

PHImageRequestOptions *requestOptions = [PHImageRequestOptions new];
requestOptions.synchronous            = NO;

Was trying to do this with dispatch_group

Fluid or fixed grid system, in responsive design, based on Twitter Bootstrap

When you decide between fixed width and fluid width you need to think in terms of your ENTIRE page. Generally, you want to pick one or the other, but not both. The examples you listed in your question are, in-fact, in the same fixed-width page. In other words, the Scaffolding page is using a fixed-width layout. The fixed grid and fluid grid on the Scaffolding page are not meant to be examples, but rather the documentation for implementing fixed and fluid width layouts.

The proper fixed width example is here. The proper fluid width example is here.

When observing the fixed width example, you should not see the content changing sizes when your browser is greater than 960px wide. This is the maximum (fixed) width of the page. Media queries in a fixed-width design will designate the minimum widths for particular styles. You will see this in action when you shrink your browser window and see the layout snap to a different size.

Conversely, the fluid-width layout will always stretch to fit your browser window, no matter how wide it gets. The media queries indicate when the styles change, but the width of containers are always a percentage of your browser window (rather than a fixed number of pixels).

The 'responsive' media queries are all ready to go. You just need to decide if you want to use a fixed width or fluid width layout for your page.

Previously, in bootstrap 2, you had to use row-fluid inside a fluid container and row inside a fixed container. With the introduction of bootstrap 3, row-fluid was removed, do no longer use it.

EDIT: As per the comments, some jsFiddles for:

These fiddles are completely Bootstrap-free, based on pure CSS media queries, which makes them a good starting point, for anyone willing to craft similar solution without using Twitter Bootstrap.

"column not allowed here" error in INSERT statement

Scanner sc = new Scanner(System.in); 
String name = sc.nextLine();
String surname = sc.nextLine();
Statement statement = connection.createStatement();
String query = "INSERT INTO STUDENT VALUES("+'"name"'+","+'"surname"'+")";
statement.executeQuery();

Do not miss to add '"----"' when concat the string.

Chain-calling parent initialisers in python

The way you are doing it is indeed the recommended one (for Python 2.x).

The issue of whether the class is passed explicitly to super is a matter of style rather than functionality. Passing the class to super fits in with Python's philosophy of "explicit is better than implicit".

How to launch an application from a browser?

The correct method is to register your custom URL Protocol in windows registry as follows:

[HKEY_CLASSES_ROOT\customurl]
@="Description here"
"URL Protocol"=""

[HKEY_CLASSES_ROOT\customurl\shell]

[HKEY_CLASSES_ROOT\customurl\shell\open]

[HKEY_CLASSES_ROOT\customurl\shell\open\command]
@="\"C:\\Path To Your EXE\\ExeName.exe\" \"%1\""

Once the above keys and values are added, from the web page, just call "customurl:\\parameter1=xxx&parameter2=xxx" . You will receive the entire url as the argument in exe, which you need to process inside your exe. Change 'customurl' with the text of your choice.

Why are Python lambdas useful?

A lambda is part of a very important abstraction mechanism which deals with higher order functions. To get proper understanding of its value, please watch high quality lessons from Abelson and Sussman, and read the book SICP

These are relevant issues in modern software business, and becoming ever more popular.

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

We've had similar issue in the past (as mentioned by TweeZz). In our case we're controlling outputting of TextBoxFor by our custom htmlHelper extension method which is building MvcHtmlString, there in one step we need to add these unobtrusive validation attributes, which is done via

var attrs = htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata)

after call to this method, attributes are html encoded, so we simply check if there was Regular expression validator there and if so, we html unencode this attribute and then merge them into tagBuilder (for building "input" tag)

if(attrs.ContainsKey("data-val-regex"))
    attrs["data-val-regex"] = ((string)attrs["data-val-regex"]).Replace("&amp;","&");
tagBuilder.MergeAttributes(attrs);

We only cared about & amps, that's why this literal replacement

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

My problem was resolved just by adding http:// to my url address. for example I used http://localhost:3000/movies instead of localhost:3000/movies.

Can you find all classes in a package using reflection?

Google Guava 14 includes a new class ClassPath with three methods to scan for top level classes:

  • getTopLevelClasses()
  • getTopLevelClasses(String packageName)
  • getTopLevelClassesRecursive(String packageName)

See the ClassPath javadocs for more info.

How can I write variables inside the tasks file in ansible

Whenever you have a module followed by a variable on the same line in ansible the parser will treat the reference variable as the beginning of an in-line dictionary. For example:

- name: some example
  command: {{ myapp }} -a foo

The default here is to parse the first part of {{ myapp }} -a foo as a dictionary instead of a string and you will get an error.

So you must quote the argument like so:

- name: some example
  command: "{{ myapp }} -a foo"

How do I change the figure size for a seaborn plot?

The top answers by Paul H and J. Li do not work for all types of seaborn figures. For the FacetGrid type (for instance sns.lmplot()), use the size and aspect parameter.

Size changes both the height and width, maintaining the aspect ratio.

Aspect only changes the width, keeping the height constant.

You can always get your desired size by playing with these two parameters.

Credit: https://stackoverflow.com/a/28765059/3901029

How to Select Top 100 rows in Oracle?

First 10 customers inserted into db (table customers):

select * from customers where customer_id <=
(select  min(customer_id)+10 from customers)

Last 10 customers inserted into db (table customers):

select * from customers where customer_id >=
(select  max(customer_id)-10 from customers)

Hope this helps....

Can you use a trailing comma in a JSON object?

According to the Class JSONArray specification:

  • An extra , (comma) may appear just before the closing bracket.
  • The null value will be inserted when there is , (comma) elision.

So, as I understand it, it should be allowed to write:

[0,1,2,3,4,5,]

But it could happen that some parsers will return the 7 as item count (like IE8 as Daniel Earwicker pointed out) instead of the expected 6.


Edited:

I found this JSON Validator that validates a JSON string against RFC 4627 (The application/json media type for JavaScript Object Notation) and against the JavaScript language specification. Actually here an array with a trailing comma is considered valid just for JavaScript and not for the RFC 4627 specification.

However, in the RFC 4627 specification is stated that:

2.3. Arrays

An array structure is represented as square brackets surrounding zero or more values (or elements). Elements are separated by commas.

array = begin-array [ value *( value-separator value ) ] end-array

To me this is again an interpretation problem. If you write that Elements are separated by commas (without stating something about special cases, like the last element), it could be understood in both ways.

P.S. RFC 4627 isn't a standard (as explicitly stated), and is already obsolited by RFC 7159 (which is a proposed standard) RFC 7159

How to sum the values of one column of a dataframe in spark/scala

Using spark sql query..just incase if it helps anyone!

import org.apache.spark.sql.SparkSession 
import org.apache.spark.SparkConf 
import org.apache.spark.sql.functions._ 
import org.apache.spark.SparkContext 
import java.util.stream.Collectors

val conf = new SparkConf().setMaster("local[2]").setAppName("test")
val spark = SparkSession.builder.config(conf).getOrCreate()
val df = spark.sparkContext.parallelize(Seq(1, 2, 3, 4, 5, 6, 7)).toDF()

df.createOrReplaceTempView("steps")
val sum = spark.sql("select  sum(steps) as stepsSum from steps").map(row => row.getAs("stepsSum").asInstanceOf[Long]).collect()(0)
println("steps sum = " + sum) //prints 28

How to declare and use 1D and 2D byte arrays in Verilog?

In addition to Marty's excellent Answer, the SystemVerilog specification offers the byte data type. The following declares a 4x8-bit variable (4 bytes), assigns each byte a value, then displays all values:

module tb;

byte b [4];

initial begin
    foreach (b[i]) b[i] = 1 << i;
    foreach (b[i]) $display("Address = %0d, Data = %b", i, b[i]);
    $finish;
end

endmodule

This prints out:

Address = 0, Data = 00000001
Address = 1, Data = 00000010
Address = 2, Data = 00000100
Address = 3, Data = 00001000

This is similar in concept to Marty's reg [7:0] a [0:3];. However, byte is a 2-state data type (0 and 1), but reg is 4-state (01xz). Using byte also requires your tool chain (simulator, synthesizer, etc.) to support this SystemVerilog syntax. Note also the more compact foreach (b[i]) loop syntax.

The SystemVerilog specification supports a wide variety of multi-dimensional array types. The LRM can explain them better than I can; refer to IEEE Std 1800-2005, chapter 5.

How to convert List to Json in Java

You need an external library for this.

JSONArray jsonA = JSONArray.fromObject(mybeanList);
System.out.println(jsonA);

Google GSON is one of such libraries

You can also take a look here for examples on converting Java object collection to JSON string.

select2 changing items dynamically

For v4 this is a known issue that won't be addressed in 4.0 but there is a workaround. Check https://github.com/select2/select2/issues/2830

how to prevent "directory already exists error" in a makefile when using mkdir

A little simpler than Lars' answer:

something_needs_directory_xxx : xxx/..

and generic rule:

%/.. : ;@mkdir -p $(@D)

No touch-files to clean up or make .PRECIOUS :-)

If you want to see another little generic gmake trick, or if you're interested in non-recursive make with minimal scaffolding, you might care to check out Two more cheap gmake tricks and the other make-related posts in that blog.

Installing PDO driver on MySQL Linux server

At first install necessary PDO parts by running the command

`sudo apt-get install php*-mysql` 

where * is a version name of php like 5.6, 7.0, 7.1, 7.2

After installation you need to mention these two statements

extension=pdo.so
extension=pdo_mysql.so

in your .ini file (uncomment if it is already there) and restart server by command

sudo service apache2 restart

Tomcat 8 Maven Plugin for Java 8

Almost 2 years later....
This github project readme has a some clarity of configuration of the maven plugin and it seems, according to this apache github project, the plugin itself will materialise soon enough.

What exactly is Python's file.flush() doing?

Basically, flush() cleans out your RAM buffer, its real power is that it lets you continue to write to it afterwards - but it shouldn't be thought of as the best/safest write to file feature. It's flushing your RAM for more data to come, that is all. If you want to ensure data gets written to file safely then use close() instead.

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

I disagree with the accepted answer here by Óscar López. That answer is inaccurate!

It is NOT @JoinColumn which indicates that this entity is the owner of the relationship. Instead, it is the @ManyToOne annotation which does this (in his example).

The relationship annotations such as @ManyToOne, @OneToMany and @ManyToMany tell JPA/Hibernate to create a mapping. By default, this is done through a seperate Join Table.


@JoinColumn

The purpose of @JoinColumn is to create a join column if one does not already exist. If it does, then this annotation can be used to name the join column.


MappedBy

The purpose of the MappedBy parameter is to instruct JPA: Do NOT create another join table as the relationship is already being mapped by the opposite entity of this relationship.



Remember: MappedBy is a property of the relationship annotations whose purpose is to generate a mechanism to relate two entities which by default they do by creating a join table. MappedBy halts that process in one direction.

The entity not using MappedBy is said to be the owner of the relationship because the mechanics of the mapping are dictated within its class through the use of one of the three mapping annotations against the foreign key field. This not only specifies the nature of the mapping but also instructs the creation of a join table. Furthermore, the option to suppress the join table also exists by applying @JoinColumn annotation over the foreign key which keeps it inside the table of the owner entity instead.

So in summary: @JoinColumn either creates a new join column or renames an existing one; whilst the MappedBy parameter works collaboratively with the relationship annotations of the other (child) class in order to create a mapping either through a join table or by creating a foreign key column in the associated table of the owner entity.

To illustrate how MapppedBy works, consider the code below. If MappedBy parameter were to be deleted, then Hibernate would actually create TWO join tables! Why? Because there is a symmetry in many-to-many relationships and Hibernate has no rationale for selecting one direction over the other.

We therefore use MappedBy to tell Hibernate, we have chosen the other entity to dictate the mapping of the relationship between the two entities.

@Entity
public class Driver {
    @ManyToMany(mappedBy = "drivers")
    private List<Cars> cars;
}

@Entity
public class Cars {
    @ManyToMany
    private List<Drivers> drivers;
}

Adding @JoinColumn(name = "driverID") in the owner class (see below), will prevent the creation of a join table and instead, create a driverID foreign key column in the Cars table to construct a mapping:

@Entity
public class Driver {
    @ManyToMany(mappedBy = "drivers")
    private List<Cars> cars;
}

@Entity
public class Cars {
    @ManyToMany
    @JoinColumn(name = "driverID")
    private List<Drivers> drivers;
}

Colorized grep -- viewing the entire file with highlighted matches

Here's my approach, inspired by @kepkin's solution:

# Adds ANSI colors to matched terms, similar to grep --color but without
# filtering unmatched lines. Example:
#   noisy_command | highlight ERROR INFO
#
# Each argument is passed into sed as a matching pattern and matches are
# colored. Multiple arguments will use separate colors.
#
# Inspired by https://stackoverflow.com/a/25357856
highlight() {
  # color cycles from 0-5, (shifted 31-36), i.e. r,g,y,b,m,c
  local color=0 patterns=()
  for term in "$@"; do
    patterns+=("$(printf 's|%s|\e[%sm\\0\e[0m|g' "${term//|/\\|}" "$(( color+31 ))")")
    color=$(( (color+1) % 6 ))
  done
  sed -f <(printf '%s\n' "${patterns[@]}")
}

This accepts multiple arguments (but doesn't let you customize the colors). Example:

$ noisy_command | highlight ERROR WARN

How to use opencv in using Gradle?

I've imported the Java project from OpenCV SDK into an Android Studio gradle project and made it available at https://github.com/ctodobom/OpenCV-3.1.0-Android

You can include it on your project only adding two lines into build.gradle file thanks to jitpack.io service.

apache not accepting incoming connections from outside of localhost

Try with below setting in iptables.config table

iptables -A INPUT -p tcp --dport 80 -j ACCEPT

Run the below command to restart the iptable service

service iptables restart

change the httpd.config file to

Listen 192.170.2.1:80

re-start the apache.

Try now.

Open Redis port for remote connections

1- Comment out bind 127.0.0.1

2- set requirepass yourpassword

then check if the firewall blocked your port

iptables -L -n

service iptables stop

How to change active class while click to another link in bootstrap use jquery?

guys try this is a perfect answer for this question:

_x000D_
_x000D_
<script>
    $(function(){
        $('.nav li a').filter(function(){return this.href==location.href}).parent().addClass('active').siblings().removeClass('active')
        $('.nav li a').click(function(){
            $(this).parent().addClass('active').siblings().removeClass('active')    
        })
    })
    </script>
_x000D_
_x000D_
_x000D_

Adding simple legend to plot in R

Take a look at ?legend and try this:

legend('topright', names(a)[-1] , 
   lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)

enter image description here

How do you rebase the current branch's changes on top of changes being merged in?

Another way to look at it is to consider git rebase master as:

Rebase the current branch on top of master

Here , 'master' is the upstream branch, and that explain why, during a rebase, ours and theirs are reversed.

Get controller and action name from within controller?

Add this to your base controller inside GetDefaults() method

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
         GetDefaults();
         base.OnActionExecuting(filterContext);
    }

    private void GetDefaults()
    {
    var actionName = filterContext.ActionDescriptor.ActionName;
    var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
    }

Implement your controllers to Basecontroller

Add a partial view _Breadcrumb.cshtml and add it in all required pages with @Html.Partial("_Breadcrumb")

_Breadcrumb.cshtml

<span>
    <a href="../@ViewData["controllerName"]">
        @ViewData["controllerName"]
    </a> > @ViewData["actionName"]
</span>

Global keyboard capture in C# application

Here's my code that works:

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace SnagFree.TrayApp.Core
{
    class GlobalKeyboardHookEventArgs : HandledEventArgs
    {
        public GlobalKeyboardHook.KeyboardState KeyboardState { get; private set; }
        public GlobalKeyboardHook.LowLevelKeyboardInputEvent KeyboardData { get; private set; }

        public GlobalKeyboardHookEventArgs(
            GlobalKeyboardHook.LowLevelKeyboardInputEvent keyboardData,
            GlobalKeyboardHook.KeyboardState keyboardState)
        {
            KeyboardData = keyboardData;
            KeyboardState = keyboardState;
        }
    }

    //Based on https://gist.github.com/Stasonix
    class GlobalKeyboardHook : IDisposable
    {
        public event EventHandler<GlobalKeyboardHookEventArgs> KeyboardPressed;

        public GlobalKeyboardHook()
        {
            _windowsHookHandle = IntPtr.Zero;
            _user32LibraryHandle = IntPtr.Zero;
            _hookProc = LowLevelKeyboardProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour.

            _user32LibraryHandle = LoadLibrary("User32");
            if (_user32LibraryHandle == IntPtr.Zero)
            {
                int errorCode = Marshal.GetLastWin32Error();
                throw new Win32Exception(errorCode, $"Failed to load library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
            }



            _windowsHookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, _hookProc, _user32LibraryHandle, 0);
            if (_windowsHookHandle == IntPtr.Zero)
            {
                int errorCode = Marshal.GetLastWin32Error();
                throw new Win32Exception(errorCode, $"Failed to adjust keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
            }
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                // because we can unhook only in the same thread, not in garbage collector thread
                if (_windowsHookHandle != IntPtr.Zero)
                {
                    if (!UnhookWindowsHookEx(_windowsHookHandle))
                    {
                        int errorCode = Marshal.GetLastWin32Error();
                        throw new Win32Exception(errorCode, $"Failed to remove keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
                    }
                    _windowsHookHandle = IntPtr.Zero;

                    // ReSharper disable once DelegateSubtraction
                    _hookProc -= LowLevelKeyboardProc;
                }
            }

            if (_user32LibraryHandle != IntPtr.Zero)
            {
                if (!FreeLibrary(_user32LibraryHandle)) // reduces reference to library by 1.
                {
                    int errorCode = Marshal.GetLastWin32Error();
                    throw new Win32Exception(errorCode, $"Failed to unload library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
                }
                _user32LibraryHandle = IntPtr.Zero;
            }
        }

        ~GlobalKeyboardHook()
        {
            Dispose(false);
        }

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

        private IntPtr _windowsHookHandle;
        private IntPtr _user32LibraryHandle;
        private HookProc _hookProc;

        delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll")]
        private static extern IntPtr LoadLibrary(string lpFileName);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern bool FreeLibrary(IntPtr hModule);

        /// <summary>
        /// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
        /// You would install a hook procedure to monitor the system for certain types of events. These events are
        /// associated either with a specific thread or with all threads in the same desktop as the calling thread.
        /// </summary>
        /// <param name="idHook">hook type</param>
        /// <param name="lpfn">hook procedure</param>
        /// <param name="hMod">handle to application instance</param>
        /// <param name="dwThreadId">thread identifier</param>
        /// <returns>If the function succeeds, the return value is the handle to the hook procedure.</returns>
        [DllImport("USER32", SetLastError = true)]
        static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);

        /// <summary>
        /// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.
        /// </summary>
        /// <param name="hhk">handle to hook procedure</param>
        /// <returns>If the function succeeds, the return value is true.</returns>
        [DllImport("USER32", SetLastError = true)]
        public static extern bool UnhookWindowsHookEx(IntPtr hHook);

        /// <summary>
        /// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain.
        /// A hook procedure can call this function either before or after processing the hook information.
        /// </summary>
        /// <param name="hHook">handle to current hook</param>
        /// <param name="code">hook code passed to hook procedure</param>
        /// <param name="wParam">value passed to hook procedure</param>
        /// <param name="lParam">value passed to hook procedure</param>
        /// <returns>If the function succeeds, the return value is true.</returns>
        [DllImport("USER32", SetLastError = true)]
        static extern IntPtr CallNextHookEx(IntPtr hHook, int code, IntPtr wParam, IntPtr lParam);

        [StructLayout(LayoutKind.Sequential)]
        public struct LowLevelKeyboardInputEvent
        {
            /// <summary>
            /// A virtual-key code. The code must be a value in the range 1 to 254.
            /// </summary>
            public int VirtualCode;

            /// <summary>
            /// A hardware scan code for the key. 
            /// </summary>
            public int HardwareScanCode;

            /// <summary>
            /// The extended-key flag, event-injected Flags, context code, and transition-state flag. This member is specified as follows. An application can use the following values to test the keystroke Flags. Testing LLKHF_INJECTED (bit 4) will tell you whether the event was injected. If it was, then testing LLKHF_LOWER_IL_INJECTED (bit 1) will tell you whether or not the event was injected from a process running at lower integrity level.
            /// </summary>
            public int Flags;

            /// <summary>
            /// The time stamp stamp for this message, equivalent to what GetMessageTime would return for this message.
            /// </summary>
            public int TimeStamp;

            /// <summary>
            /// Additional information associated with the message. 
            /// </summary>
            public IntPtr AdditionalInformation;
        }

        public const int WH_KEYBOARD_LL = 13;
        //const int HC_ACTION = 0;

        public enum KeyboardState
        {
            KeyDown = 0x0100,
            KeyUp = 0x0101,
            SysKeyDown = 0x0104,
            SysKeyUp = 0x0105
        }

        public const int VkSnapshot = 0x2c;
        //const int VkLwin = 0x5b;
        //const int VkRwin = 0x5c;
        //const int VkTab = 0x09;
        //const int VkEscape = 0x18;
        //const int VkControl = 0x11;
        const int KfAltdown = 0x2000;
        public const int LlkhfAltdown = (KfAltdown >> 8);

        public IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam)
        {
            bool fEatKeyStroke = false;

            var wparamTyped = wParam.ToInt32();
            if (Enum.IsDefined(typeof(KeyboardState), wparamTyped))
            {
                object o = Marshal.PtrToStructure(lParam, typeof(LowLevelKeyboardInputEvent));
                LowLevelKeyboardInputEvent p = (LowLevelKeyboardInputEvent)o;

                var eventArguments = new GlobalKeyboardHookEventArgs(p, (KeyboardState)wparamTyped);

                EventHandler<GlobalKeyboardHookEventArgs> handler = KeyboardPressed;
                handler?.Invoke(this, eventArguments);

                fEatKeyStroke = eventArguments.Handled;
            }

            return fEatKeyStroke ? (IntPtr)1 : CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
        }
    }
}

Usage:

using System;
using System.Windows.Forms;

namespace SnagFree.TrayApp.Core
{
    internal class Controller : IDisposable
    {
        private GlobalKeyboardHook _globalKeyboardHook;

        public void SetupKeyboardHooks()
        {
            _globalKeyboardHook = new GlobalKeyboardHook();
            _globalKeyboardHook.KeyboardPressed += OnKeyPressed;
        }

        private void OnKeyPressed(object sender, GlobalKeyboardHookEventArgs e)
        {
            //Debug.WriteLine(e.KeyboardData.VirtualCode);

            if (e.KeyboardData.VirtualCode != GlobalKeyboardHook.VkSnapshot)
                return;

            // seems, not needed in the life.
            //if (e.KeyboardState == GlobalKeyboardHook.KeyboardState.SysKeyDown &&
            //    e.KeyboardData.Flags == GlobalKeyboardHook.LlkhfAltdown)
            //{
            //    MessageBox.Show("Alt + Print Screen");
            //    e.Handled = true;
            //}
            //else

            if (e.KeyboardState == GlobalKeyboardHook.KeyboardState.KeyDown)
            {
                MessageBox.Show("Print Screen");
                e.Handled = true;
            }
        }

        public void Dispose()
        {
            _globalKeyboardHook?.Dispose();
        }
    }
}

Traverse a list in reverse order in Python

>>> l = ["a","b","c","d"]
>>> l.reverse()
>>> l
['d', 'c', 'b', 'a']

OR

>>> print l[::-1]
['d', 'c', 'b', 'a']